<?php
ini_set('display_errors', 1);
// this file will get results based from user_uploads as filtered by user to narrow down aand get a list of documents.

require_once '../../../resources/base_path_include.php';

//valdation file
require_once $base_path_to_resources . "includes/config.php"; // use require for mandatory files
require_once $base_path_to_resources . 'lib/function.php';
require_once $base_path_to_resources . 'lib/validate_api_signature.php';
require_once $base_path_to_resources . 'lib/validate_function.php';
require_once $base_path . 'user_management/authenticate.php';

//function file
require_once $base_path . 'modules/accounting/book_management/basic_book_info_function.php';

//user upload
require_once $base_path_to_resources . 'lib/bucket_functions/bucket_functions.php';

//aws image store
require_once $base_path . "vendor/autoload.php";

require_once $base_path_to_resources . 'includes/aws_bucket_config.php';


//creating dynamic db
require_once $base_path_to_resources . 'includes/specific_db_config.php';

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

$postdata = json_decode(file_get_contents("php://input"), true);
checkIfNoPhpContentsReceive();
validateApiSignature($postdata['api_signature']);

//authenticate jwt token
$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
//then workspace_id is decoded in data of jwt use from there
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$role = $jwt_validate->data->role;
$created_by = $jwt_validate->data->username;

// company, branch, book,  optional if not found make them null
if (isset($postdata['company_id']) and checkIfIssetAndNotEmpty($postdata['company_id'])) {
    $company_id = trim($postdata['company_id']);
    if (isset($postdata['branch_id']) and checkIfIssetAndNotEmpty($postdata['branch_id'])) {
        $branch_id = trim($postdata['branch_id']);
        if (isset($postdata['book_id']) and checkIfIssetAndNotEmpty($postdata['book_id'])) {
            $book_id = trim($postdata['book_id']);
        } else {
            $book_id = null;
        }
    } else {
        $branch_id = null;
        $book_id = null;
    }
} else {
    $company_id = null;
    $branch_id = null;
    $book_id = null;
}

// mandatory function type should be upload_to_my_files
if (!checkIfIssetAndNotEmpty($postdata['function_type']) or $postdata['function_type'] != 'view_drive_items') {
    errorreturn('Access denied.');
}
$function_code = $postdata['function_type'];
$confirmed_role_user = validatePrimaryAccess($conn, $workspace_id, $role, $userid, ['superadmin', 'admin', null]);
if (!$confirmed_role_user) {
    errorreturn('Access denied.');
} else {
    $specific_db_conn = dynamicDbConnection($confirmed_role_user);
    if ($role == null) {
        checkCompanyBranchFunctionAccess($specific_db_conn, $role, $userid, $workspace_id, null, null, null,  $function_code);
    }
}

if (isset($postdata['limit']) and is_numeric($postdata['limit']) and $postdata['limit'] > 0) {
    $limit = intval($postdata['limit']);
} else {
    $limit = 15;
}
if (isset($postdata['page']) and is_numeric($postdata['page']) and $postdata['page'] > 0) {
    $offset = (intval($postdata['page']) - 1) * $limit;
} else {
    $offset = 0;
}
if (isset($postdata['search_in_company_filter']) and $postdata['search_in_company_filter'] == 0) {
    $search_in_company_filter = 0;
} else {
    $search_in_company_filter = 1;
}

$sql = "Select * from user_upload where workspace_id = ? and category NOT IN ('stock_icon', 'transaction_attachment')";
$array_params = [$workspace_id];
if ($search_in_company_filter == 1) {
    if ($company_id != null) {
        $sql .= " and company_id = ?";
        $array_params[] = $company_id;
    }
    if ($branch_id != null) {
        $sql .= " and branch_id = ?";
        $array_params[] = $branch_id;
    }
    if ($book_id != null) {
        $sql .= " and book_id = ?";
        $array_params[] = $book_id;
    }
}


if (isset($postdata['date_of_document']) and checkIfIssetAndNotEmpty($postdata['date_of_document']) and strtotime($postdata['date_of_document'])) {
    $date_of_document = trim($postdata['date_of_document']);
    $sql .= " and date_of_document = ?";
    $array_params[] = $date_of_document;
}
if (isset($postdata['reminder_date']) and checkIfIssetAndNotEmpty($postdata['reminder_date']) and strtotime($postdata['reminder_date'])) {
    $reminder_date = trim($postdata['reminder_date']);
    $sql .= " and reminder_date = ?";
    $array_params[] = $reminder_date;
}
if (isset($postdata['termination_document_date']) and checkIfIssetAndNotEmpty($postdata['termination_document_date']) and strtotime($postdata['termination_document_date'])) {
    $termination_document_date = trim($postdata['termination_document_date']);
    $sql .= " and termination_document_date = ?";
    $array_params[] = $termination_document_date;
}


if (isset($postdata['search_string']) and checkIfIssetAndNotEmpty($postdata['search_string'])) {
    $search_string = trim($postdata['search_string']);
    $like_search_string_contains = '%' . $search_string . '%';
    $like_search_string_starts_with = $search_string . '%';
    $sql .= " and (original_upload_name LIKE ?  or tags LIKE ? or party_1 LIKE ? or party_2 LIKE ? or party_3 LIKE ?)";
    array_push($array_params, ...[$like_search_string_contains, $like_search_string_contains, $like_search_string_starts_with, $like_search_string_starts_with, $like_search_string_starts_with]);
} else {
    $search_string = "";
}

$category_name =  null;
if (isset($postdata['category_id']) and checkIfIssetAndNotEmpty($postdata['category_id'])) {
    //  echo 'enter';
    if ($postdata['category_id'] == 'all') {

        $category_id = '';
        $category_name =  null;
    } else {
        $category_id = trim($postdata['category_id']);
        $like_search_string_contains = '%' . $category_id . '%';
        ///$like_search_string_starts_with = $category_id . '%';
        $sql .= " and (category LIKE ?)";
        array_push($array_params, ...[$like_search_string_contains]);

        $sql_category = "Select name from upload_categories where id= ? and workspace_id = ?  ";
        $stmt_category = $specific_db_conn->prepare($sql_category);
        $stmt_category->execute(array($postdata['category_id'], $workspace_id));
        $result = $stmt_category->fetchAll();
        if (count($result) == 1) {
            //  print_r($result);
            $category_name = $result[0]['name'];
        } else {
            $category_name =  null;
        }
    }
}

if (isset($postdata['share_mode']) and checkIfIssetAndNotEmpty($postdata['share_mode']) and in_array($postdata['share_mode'], ['public', 'private', 'protected'])) {
    $share_mode = $postdata['share_mode'];
    $sql .= " and share_mode = ?";
    $array_params[] = $share_mode;

    if ($share_mode == 'protected' and isset($postdata['share_with']) and checkIfIssetAndNotEmpty($postdata['share_with'])) {
        // verify if it is a valid email id
        $sql_validate_share_with = "Select username from users where workspace_id = ? and email = ? and status = ?";
        $validate_user = $specific_db_conn->prepare($sql_validate_share_with);
        $validate_user->execute(array($workspace_id, $postdata['share_with'], 1));
        $result_user_validate = $validate_user->fetchAll();
        if (count($result_user_validate) == 1) {
            $share_with = $result_user_validate[0]['username'];
        } else {
            errorreturn('Unable to identify the user : ' . $postdata['share_with']);
        }
        $sql .= " and share_with LIKE ?";
        $array_params[] = '%' . $share_with . '%';
    }
} else {
    $share_mode = 'all';
}

if ($role != "superadmin" and $role != "admin") {
    // add user file validation
    // ya to khud user ki ho ya public  ya share with mei ho user
    $sql .= " and (user_id = ? or share_mode = ? or (share_mode = ? and  share_with LIKE ?))";
    array_push($array_params, ...[$userid, 'public', 'protected', '%"' . $created_by . '"%']);
}

$sql_count = $sql;

$get_count = $specific_db_conn->prepare(str_replace("Select *", "Select count(*) as total", $sql_count)); // creating a copy of sql string until here replacing * with count(*)
$get_count->execute($array_params);
$result_count = $get_count->fetchAll();
if (count($result_count) > 0) {
    $total_rows = $result_count[0]['total'] ? $result_count[0]['total'] : 0;
} else {
    $total_rows = 0;
    $maxreach = 0;
    $files_info = [];
    successreturn($success);
}

$sql .= " order by date_created desc, time_created desc limit $offset, $limit";
$fetch_files = $specific_db_conn->prepare($sql);
$fetch_files->execute($array_params);
$result_files = $fetch_files->fetchAll();
$files_info = [];
if (count($result_files) > 0) {
    foreach ($result_files as $temp_files) {
        if($temp_files['share_with'] !=  null){
            $share_with = json_decode($temp_files['share_with']);
        }else{
            $share_with =  null;
        }
        if($temp_files['tags'] !=  null){
            $tags = json_decode($temp_files['tags']);
        }else{
            $tags =  null;
        }
        $files_info[] = array(
            'id' => $temp_files['id'],
            'key' => displayFileFromS3($s3_finware_bucket, $finware_bucketName, $temp_files['path'], '10', 'minutes'),
            'filename' => pathinfo($temp_files['original_upload_name'], PATHINFO_FILENAME),
            'size_of_file' => $temp_files['size_of_file'], // this file size is in bytes 
            'file_extension' => $temp_files['file_extension'],
            'tags' => $tags,
            'share_mode' => $temp_files['share_mode'],
            'share_with' => $share_with,
            'party_1' => $temp_files['party_1'],
            'party_2' => $temp_files['party_2'],
            'party_3' => $temp_files['party_3'],
            'date_of_document' => $temp_files['date_of_document'],
            'date_created' => $temp_files['date_created'],
            'category_id' => $temp_files['category'],
            'category_name' => $category_name,
            'reminder_date' => $temp_files['reminder_date'],
            'termination_document_date' => $temp_files['termination_document_date'],
            'added_by' => $temp_files['added_by'],
            'last_modified_by' => $temp_files['last_modified_by'],
            'user_id' => $temp_files['user_id'],
            'let_others_delete' => $temp_files['let_others_delete'],
            'let_others_edit' => $temp_files['let_others_edit'],
            // write other fields received in the same order and name, to use in frontend while uploading
        );
    }
}

if (count($result_files) == $limit) {
    $maxreach = 0;
} else {
    $maxreach = 1;
}

$success['data'] = array('total_rows' => $total_rows, 'maxreach' => $maxreach, 'files_info' => $files_info);
successreturn($success);

//  and !checkIfIssetAndNotEmpty($postdata['date_of_document']) and !checkIfIssetAndNotEmpty($postdata['reminder_date']) and !checkIfIssetAndNotEmpty($postdata['termination_document_date']) and !checkIfIssetAndNotEmpty($postdata['share_mode'])) {
    // if non of these are received as non null then fetch recent uploads of the user by limit and offset


// filter on basis of search name, tags , share_mode (all / others), document_date, reminder_date, termination_date
