<?php
ini_set('display_errors', 1);

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 = $_POST;
// checkIfNoPhpContentsReceive();
$api_signature = $postdata['api_signature'];
validateApiSignature($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 = (isset($postdata['book_id']) and !empty($postdata['book_id'])) ? $postdata['book_id'] : null;
        }
    } else {
        $branch_id = (isset($postdata['branch_id']) and !empty($postdata['branch_id'])) ? $postdata['branch_id'] : null;
       $book_id = (isset($postdata['book_id']) and !empty($postdata['book_id'])) ? $postdata['book_id'] : null;
    }
} else {
   $company_id = (isset($postdata['company_id']) and !empty($postdata['company_id'])) ? $postdata['company_id'] : null;
   $branch_id = (isset($postdata['branch_id']) and !empty($postdata['branch_id'])) ? $postdata['branch_id'] : null;
   $book_id = (isset($postdata['book_id']) and !empty($postdata['book_id'])) ? $postdata['book_id'] : null;
}
if (checkIfIssetAndNotEmpty($postdata['filename'])) {
    $filename_by_user = trim($postdata['filename']);
    // regex
} else {
    errorreturn("File name is mandatory.");
}


// mandatory function type should be upload_to_my_files
if (!checkIfIssetAndNotEmpty($postdata['function_type']) or $postdata['function_type'] != 'upload_to_drive') {
    errorreturn('Access denied.');
}
$function_code = $postdata['function_type'];
$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);
    }
}

 $category_id = (isset($postdata['category_id']) and !empty($postdata['category_id'])) ? $postdata['category_id'] : null;
    //echo 'here';
    if($category_id ==  null){
      
       
         $sql = "Select id from  upload_categories where  workspace_id = ? ";
        $fetch_category = $specific_db_conn->prepare($sql);
        $fetch_category->execute(array($workspace_id));
        $result  = $fetch_category->fetchAll();
        
        if (count($result) < 1) {
    
            errorreturn('Category name not found.');
        }
    
        $category_id =  $result[0]['id'];
   
    }else if($category_id !=  null){
        
    $sql = "Select name from  upload_categories where id = ? and workspace_id = ? ";
    $fetch_category = $specific_db_conn->prepare($sql);
    $fetch_category->execute(array($category_id, $workspace_id));
    if (count($fetch_category->fetchAll()) != 1) {

        errorreturn('Category name not found .');
    }
    }


$filesattached = array();

$filesattached = (isset($_FILES['filesattached']) and !empty($_FILES['filesattached'])) ? $_FILES['filesattached'] : null;
if ($filesattached == null) {
    errorreturn('Please upload a file.');
} else {

    
    $directoryPathMain = "user_uploads/" .  'workspace_'  . $workspace_id . "/" . $userid . "/";

    // Iterate over each uploaded file

    // check if you have received an array of files
    // validate it


    $file_upload_multiple_bool = false;
    $sql_unique_filename = "Select count(original_upload_name) as total from user_upload where user_id = ? and company_id = ?  and original_upload_name = ?";
    $unique_filename = $specific_db_conn->prepare($sql_unique_filename);

    // check if multiple file upload
    $files_structures_array = [];
    $i = 1;
    if (is_array($filesattached['name'])) {
        //   echo 'enter';
        // multiple
        // count of files should not be greater than 10
        if (count($filesattached['tmp_name']) > 10) {
            // errirreturn
            errorreturn('You can upload up to 10 files at a time.');
        }
        $total_filesize = 0;
        foreach ($filesattached['tmp_name'] as $key => $name) {
            # code...
            $file_upload_multiple_bool = true;
            // Validate the file name if needed
            $file_name = $filesattached['name'][$key]; // validate that this hsould not exceed 50 characters and should not contain any special characters other than _ except the . before extension

            $fileTmpName = $filesattached["tmp_name"][$key];
            $fileSize = $filesattached["size"][$key];
            $fileType = $filesattached["type"][$key];
            $fileError = $filesattached["error"];
            $file_extension = strtolower(pathinfo($filesattached['name'][$key], PATHINFO_EXTENSION));

            $size = filesize($fileTmpName);
            $total_filesize += $size;
            $totalFileSizeLimit = 25 * 1024 * 1024; // 25 MB in bytes
            // if total size exceeds 25 MB then throw error
            if ($total_filesize > $totalFileSizeLimit) {
                errorreturn('Total file size exceeds the limit of 25 MB.');
            }

            // Check if it's a valid image
            $allowedTypes = [
                'image/jpeg', 'image/png', 'image/gif', 'image/heic',
                'application/pdf',
                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                'application/vnd.ms-excel',
                'application/msword',
                'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            ]; // Allowed image types
            $allowed_extensions = ['jpg', 'gif', 'png', 'heic', 'jpeg', 'pdf', 'xlsx', 'xls', 'doc', 'docx'];
            $maxFileSize = 25; // Maximum file size (2MB)

            checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);


            if ($i != 1) {
                $keyName = $directoryPathMain . $userid . '_' . $i  . "_" . time() . '.' . $file_extension;
                $filename_by_user_key = $filename_by_user . '_' . $i . "." . $file_extension;
            } else {
                $keyName = $directoryPathMain . $userid . "_" . time() . '.' . $file_extension;
                $filename_by_user_key = $filename_by_user . "." . $file_extension;
            }
            $i++;

            // veryifying that file name is unique
            $unique_filename->execute(array($userid, $company_id, $filename_by_user_key));
            $result_unique_filename = $unique_filename->fetchAll();
            if (count($result_unique_filename) > 0) {
                if ($result_unique_filename[0]['total'] > 0) {
                    errorreturn('File name already exists.');
                }
            }
            $files_structures_array[] = array('filename_by_user' => $filename_by_user_key, 'keyName' => $keyName, 'size' => $size, 'file_extension' => $file_extension);
        }
    } else {
       
        // print_r($filesattached);die();
        // single validation
        // Validate the file name if needed
        $file_name = $filesattached['name']; // validate that this hsould not exceed 50 characters and should not contain any special characters other than _ except the . before extension

        $fileTmpName = $filesattached["tmp_name"];
        $fileSize = $filesattached["size"];
        $fileType = $filesattached["type"];
        $fileError = $filesattached["error"];
        $file_extension = strtolower(pathinfo($filesattached['name'], PATHINFO_EXTENSION));

        $size = filesize($fileTmpName);
        // Check if it's a valid image
        $allowedTypes = [
            'image/jpeg', 'image/png', 'image/gif', 'image/heic',
            'application/pdf',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'application/vnd.ms-excel',
            'application/msword',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        ]; // Allowed image types
        $allowed_extensions = ['jpg', 'gif', 'png', 'heic', 'jpeg', 'pdf', 'xlsx', 'xls', 'doc', 'docx'];
        $maxFileSize = 25; // Maximum file size (2MB)

        checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);

        $keyName = $directoryPathMain . $userid . "_" . time() . '.' . $file_extension;

        $filename_by_user = $filename_by_user . "." . $file_extension;

        // veryifying that file name is unique

        $unique_filename->execute(array($userid, $company_id, $filename_by_user));
        $result_unique_filename = $unique_filename->fetchAll();
        if (count($result_unique_filename) > 0) {
            if ($result_unique_filename[0]['total'] > 0) {
                errorreturn('File name already exists.');
            }
        }

        $files_structures_array[] = array('filename_by_user' => $filename_by_user, 'keyName' => $keyName, 'size' => $size, 'file_extension' => $file_extension);
    }

    // validating share with

    $share_mode = (checkIfIssetAndNotEmpty($postdata['share_mode']) and in_array($postdata['share_mode'], ['public', 'private', 'protected'])) ? $postdata['share_mode'] : 'private';

    if ($share_mode == 'protected') {
        $share_with = (isset($postdata['share_with']) and !empty($postdata['share_with'])) ? json_decode($postdata['share_with'], true) : null;
    } else {
        $share_with = null;
    }

    if (is_array($share_with) and count($share_with) > 0) {
        $temp_share_with = $share_with;
        //     // get each object inside array like (name, email
        $sql = "Select username from users where workspace_id = ? and email = ? and status = ?";
        $validate_user = $conn->prepare($sql);
        $share_with = [];
        foreach ($temp_share_with as $element) {
            $validate_user->execute(array($workspace_id, $element, 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 : ' . $element['email']);
            }
        }
    }


    $i = 0; // setting according to array index
    foreach ($files_structures_array as $temp_file) {

        $tags = (isset($postdata['tags']) and !empty($postdata['tags'])) ? json_decode($postdata['tags'], true) : null;
        $party_1 = (isset($postdata['party_1']) and !empty($postdata['party_1'])) ? $postdata['party_1'] : null;
        $party_2 = (isset($postdata['party_2']) and !empty($postdata['party_2'])) ? $postdata['party_2'] : null;
        $party_3 = (isset($postdata['party_3']) and !empty($postdata['party_3'])) ? $postdata['party_3'] : null;
        $date_of_document = (isset($postdata['date_of_document']) and !empty($postdata['date_of_document'])) ? $postdata['date_of_document'] : null;
        $reminder_date = (isset($postdata['reminder_date']) and !empty($postdata['reminder_date'])) ? $postdata['reminder_date'] : null;
        $termination_document_date = (isset($postdata['termination_document_date']) and !empty($postdata['termination_document_date'])) ? $postdata['termination_document_date'] : null;
        $let_others_delete = (isset($postdata['let_others_delete']) and isset($postdata['let_others_delete']) and !empty($postdata['let_others_delete'])) ? $postdata['let_others_delete'] : 0;
        $let_others_edit = (isset($postdata['let_others_edit']) and isset($postdata['let_others_edit']) and !empty($postdata['let_others_edit'])) ? $postdata['let_others_edit'] : 0;


        $upload_id = awsS3UserUploadInsert(
            $s3_finware_bucket,
            $finware_bucketName,
            $specific_db_conn,
            $workspace_id,
            $company_id,
            $branch_id,
            $book_id,
            $userid,
            $_FILES['filesattached'],
            $temp_file['filename_by_user'],
            $temp_file['keyName'],
            $temp_file['size'],
            strtolower($temp_file['file_extension']),
            $tags,
            $party_1,
            $party_2,
            $party_3,
            $date_of_document,
            $category_id,
            null,
            $reminder_date,
            $created_by,
            null,
            $termination_document_date,
            $share_mode,
            $share_with,
            $let_others_delete,
            $let_others_edit,
            $file_upload_multiple_bool,
            $i
        );
        $i++;
    }
}

successreturn(array('upload_id' => $upload_id, 'successmsg' => "File successfully uploaded to my files."));