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

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

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/currency_functions.php";
require_once $base_path_to_resources . 'lib/validate_api_signature.php';
require_once $base_path_to_resources . 'lib/validate_function.php';

//valdation file
require_once $base_path . 'user_management/authenticate.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";
//creating dynamic db
require_once $base_path_to_resources . 'includes/specific_db_config.php';
require_once $base_path_to_resources . 'includes/aws_bucket_config.php';

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


$postdata = $_POST;
// print_r($postdata);die();
// checkIfNoPhpContentsReceive();

if (
    !isset($postdata['setting_id']) or !checkIfIssetAndNotEmpty($postdata['setting_id']) or !isset($postdata['company_id']) or
    !checkIfIssetAndNotEmpty($postdata['company_id']) or  !isset($postdata['branch_id']) or !checkIfIssetAndNotEmpty($postdata['branch_id']) or
    !isset($postdata['book_id']) or !checkIfIssetAndNotEmpty($postdata['book_id']) or !isset($postdata['report_print_company_name']) or !checkIfIssetAndNotEmpty($postdata['report_print_company_name'])
    or !isset($postdata['report_print_branch_name']) or !checkIfIssetAndNotEmpty($postdata['report_print_branch_name']) or  !isset($postdata['report_print_book_name']) or !checkIfIssetAndNotEmpty($postdata['report_print_book_name']) or !isset($postdata['function_type']) or !checkIfIssetAndNotEmpty($postdata['function_type']) or !isset($postdata['jwt_token']) or !checkIfIssetAndNotEmpty($postdata['jwt_token'])
) {
    errorreturn("All * fields are required.");
}

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;


if ($postdata['function_type']  == "global_settings") {


    $function_code = $postdata['function_type'];
    $print_id = trim($postdata['setting_id']);
    $company_id = trim($postdata['company_id']);
    $branch_id = trim($postdata['branch_id']);
    $book_id = trim($postdata['book_id']);

    $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,  $postdata['function_type']);
        }
    }

    $remove_logo = (isset($postdata['remove_logo']) and !empty($postdata['remove_logo'])) ? trim($postdata['remove_logo']) : 0; //if logo_remove is 1 then user can delete logo

    //boolean
    $report_print_company_name = $postdata['report_print_company_name'];
    $report_print_branch_name = $postdata['report_print_branch_name'];
    $report_print_book_name = $postdata['report_print_book_name'];
    $print_logo_bool = $postdata['print_logo_bool'];

    //bank_name, account_holder_name, account_number, ifsc_code,branch_Address, account_type
    $bank_details_1 = (isset($postdata['bank_details_1']) and !empty($postdata['bank_details_1'])) ? $postdata['bank_details_1'] : null;
    $bank_details_2 = (isset($postdata['bank_details_2']) and !empty($postdata['bank_details_2'])) ? $postdata['bank_details_2'] : null;
    $print_bank_details_1 = json_decode($postdata['print_bank_details_1'], true);
    $print_bank_details_2 = json_decode($postdata['print_bank_details_2'], true);
    $logo = (isset($_FILES['logo']) and !empty($_FILES['logo'])) ? $_FILES['logo'] : null;
    $terms_conditions = (isset($postdata['terms_conditions']) and !empty($postdata['terms_conditions'])) ? $postdata['terms_conditions'] : null;


    if ($print_bank_details_1 ==  '1' and $bank_details_1 != null) {

        if (isset($bank_details_1['account_number']) && !preg_match('/^\d{11}$/', $bank_details_1['account_number'])) {
            errorreturn("Account number should be 11 digits.");
        }

        if (isset($bank_details_1['ifsc_code']) && !preg_match('/^[A-Z]{4}0[A-Z0-9]{6}$/', $bank_details_1['ifsc_code'])) {
            errorreturn("IFSC code format is incorrect.");
        }

        if (isset($bank_details_1['account_holder_name']) && !preg_match('/^[A-Za-z\s]+$/', $bank_details_1['account_holder_name'])) {
            errorreturn("Account holder name should only contain letters and spaces.");
        }

        if (isset($bank_details_1['branch_dddress']) && !preg_match('/^[A-Za-z0-9\s\-.,#\/]+$/', $bank_details_1['branch_dddress'])) {
            errorreturn("Branch address contains invalid characters.");
        }

        if (isset($bank_details_1['account_type']) && $bank_details_1['account_type'] !== "savings" && $bank_details_1['account_type'] !== "current") {
            errorreturn("Invalid account type. Allowed types are 'savings' or 'current'.");
        }
    }

    if ($print_bank_details_2 ==  '1' and $bank_details_2 != null) {

        if (isset($bank_details_2['account_number']) && !preg_match('/^\d{11}$/', $bank_details_1['account_number'])) {
            errorreturn("Account number should be 11 digits.");
        }

        if (isset($bank_details_2['ifsc_code']) && !preg_match('/^[A-Z]{4}0[A-Z0-9]{6}$/', $bank_details_1['ifsc_code'])) {
            errorreturn("IFSC code format is incorrect.");
        }

        if (isset($bank_details_2['account_holder_name']) && !preg_match('/^[A-Za-z\s]+$/', $bank_details_1['account_holder_name'])) {
            errorreturn("Account holder name should only contain letters and spaces.");
        }

        if (isset($bank_details_2['branch_dddress']) && !preg_match('/^[A-Za-z0-9\s\-.,#\/]+$/', $bank_details_1['branch_dddress'])) {
            errorreturn("Branch address contains invalid characters.");
        }

        if (isset($bank_details_2['account_type']) && $bank_details_1['account_type'] !== "savings" && $bank_details_1['account_type'] !== "current") {
            errorreturn("Invalid account type. Allowed types are 'savings' or 'current'.");
        }
    }


    $bank_details_1 = serialize($bank_details_1);
    $bank_details_2 = serialize($bank_details_2);

    $res = $specific_db_conn->prepare("SELECT * FROM act_book_settings WHERE id = ? and workspace_id =? and company_id = ? and branch_id = ? and book_id = ? ");
    $res->execute(array($print_id, $workspace_id, $company_id, $branch_id, $book_id));
    $result1 = $res->fetchAll();
    if (count($result1) < 1) {
        errorreturn("Book setting not exists.");
    }


    $res = $specific_db_conn->prepare("SELECT * FROM act_book_settings WHERE id = ? and workspace_id =? and company_id = ? and branch_id = ? and book_id = ? ");
    $res->execute(array($print_id, $workspace_id, $company_id, $branch_id, $book_id));
    $result1 = $res->fetchAll();
    if (count($result1) == 1) {
        $existing_filesattached = $result1[0]['logo'];
    }

    if (!isset($logo) or $logo == null or $print_logo_bool == 0) {
        // check if removed
        if (($remove_logo == 1 or $print_logo_bool == 0) and $existing_filesattached != null) {
            // if logo empty and remove bool 1
            // delete
            $sql_get_user_upload_id = "Select id from user_upload where workspace_id = ? and path = ? and category_unique_id = ? and category = ?";
            $get_user_upload_id = $specific_db_conn->prepare($sql_get_user_upload_id);
            $get_user_upload_id->execute(array($workspace_id, $existing_filesattached, $book_id, 'book_logo'));
            $result_user_upload_id = $get_user_upload_id->fetchAll();
            if (count($result_user_upload_id) == 1) {
                awsS3UserUploadDelete($s3_finware_bucket, $finware_bucketName, $specific_db_conn, $workspace_id, $existing_filesattached, $result_user_upload_id[0]['id'], true);

                $update_print_logo = $specific_db_conn->prepare("Update act_book_settings set logo = ?, print_logo_bool = ? where workspace_id = ? and company_id = ? and branch_id = ? and book_id = ?");
                $update_print_logo->execute(array(null, 0, $workspace_id, $company_id, $branch_id, $book_id));
            }
        }
    } else {
        // delete old logo if any
        // insert new logo and then update in book_settings as well
        // save the filename as logo_(book_id).(extension of uploaded file)
        // keyname as user_uploads/workspace_id/company_id/branch_id/book_id/book_settings/logo_(book_id).(extension of uploaded file)



        if ($existing_filesattached != null) {

            $sql_get_user_upload_id = "Select id from user_upload where workspace_id = ? and path = ? and category_unique_id = ? and category = ?";
            $get_user_upload_id = $specific_db_conn->prepare($sql_get_user_upload_id);
            $get_user_upload_id->execute(array($workspace_id, $existing_filesattached, $book_id, 'book_logo'));
            $result_user_upload_id = $get_user_upload_id->fetchAll();
            if (count($result_user_upload_id) == 1) {
                awsS3UserUploadDelete($s3_finware_bucket, $finware_bucketName, $specific_db_conn, $workspace_id, $existing_filesattached, $result_user_upload_id[0]['id'], true);
            }
        }

        $currentYear = date('Y');
        $currentMonth = date('n');
        $currentDay =  date('d');


        // $directoryPathMain = "user_uploads/" . $workspace_id . "/" . $company_id . "/" . $branch_id . "/" . $book_id . "/stocks_attachments/" . $currentYear . "/" . $currentMonth . "/" . $currentDay . "/";
        $directoryPathMain = "user_uploads/" .  'workspace_'  . $workspace_id . "/" . 'company_' .  $company_id . "/" . 'branch_' .  $branch_id . "/" . 'book_' .  $book_id . "/book_setttings/";

        $filesattached = $_FILES['logo'];

        $fileTmpName = $_FILES['logo']["tmp_name"];
        $fileSize = $_FILES['logo']["size"];
        $fileType = $_FILES['logo']["type"];
        $fileError = $_FILES['logo']["error"];
        $file_extension = strtolower(pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION));
        $size = filesize($fileTmpName);
        // Check if it's a valid image
        $allowedTypes = ['image/jpeg', 'image/png', 'image/heic']; // Allowed image types
        $allowed_extensions = ['jpg', 'png', 'heic', 'jpeg'];
        $maxFileSize = 2; // Maximum file size (2MB)

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

        // Generate the image name
        $image_name = "logo_" . $book_id . "." . $file_extension;
        $keyName = $directoryPathMain . $image_name;

        $party_1 =  null;
        $party_2 =  null;
        $party_3 =  null;
        $date_of_document = null;
        $category_file_upload = 'book_logo';
        //$reminder_date=  trim(date('Y-m-d', strtotime($postdata['reminder_date'])));
        $reminder_date =  null;
        $last_modified_by = null;
        $termination_document_date =  null;
        //$tags =  null;
        $tags = null;
        $share_mode =  'public';
        $share_with =  null;

        awsS3UserUploadInsert(
            $s3_finware_bucket,
            $finware_bucketName,
            $specific_db_conn,
            $workspace_id,
            $company_id,
            $branch_id,
            $book_id,
            $userid,
            $filesattached,
            $image_name,
            $keyName,
            $size,
            strtolower($file_extension),
            $tags,
            $party_1,
            $party_2,
            $party_3,
            $date_of_document,
            $category_file_upload,
            $book_id,
            $reminder_date,
            $created_by,
            $last_modified_by,
            $termination_document_date,
            $share_mode,
            $share_with,
            0,
            0
        );

        // update
        $update_print_logo = $specific_db_conn->prepare("Update act_book_settings set logo = ?, print_logo_bool = ? where workspace_id = ? and company_id = ? and branch_id = ? and book_id = ?");
        $update_print_logo->execute(array($keyName, 1, $workspace_id, $company_id, $branch_id, $book_id));
    }

    $sql = "UPDATE act_book_settings SET report_print_company_name = ?, report_print_branch_name = ?,report_print_book_name=?,bank_details_1=?,bank_details_2=?,print_bank_details_1=?,
        print_bank_details_2=?,terms_conditions = ?";

    $array_params = [
        $report_print_company_name, $report_print_branch_name, $report_print_book_name, $bank_details_1, $bank_details_2, $print_bank_details_1,
        $print_bank_details_2, $terms_conditions, $print_id, $workspace_id, $company_id, $branch_id, $book_id
    ];

    $sql = $sql . " WHERE id = ? and workspace_id = ? and company_id = ? and branch_id= ? and book_id = ?";

    $specific_db_conn->prepare($sql)->execute($array_params);

    successreturn("Book reports and print settings updated successfully");
}
