<?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";

//valdation file
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';
require_once $base_path . 'modules/accounting/groups_ledgers/update_ledger_balance.php';
//creating dynamic db
require_once $base_path_to_resources . 'includes/specific_db_config.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';

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

$postdata = json_decode(file_get_contents("php://input"), true);
checkIfNoPhpContentsReceive();

if (
    !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['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;

function fetchSpecificBookSettings($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id)
{

    // reeturns all data from the specific row of the profile
    $sql = $specific_db_conn->prepare("SELECT * FROM  act_book_settings  where workspace_id =? and company_id = ? and branch_id = ? and book_id = ?");
    $sql->execute(array($workspace_id, $company_id, $branch_id, $book_id));
    $rows = $sql->fetchAll();

    if (count($rows) == 1) {
        $logo = $rows[0]['logo'];
        $print_logo_bool = $rows[0]['print_logo_bool'];
        $print_bank_details_1 = $rows[0]['print_bank_details_1'];
        $print_bank_details_2 = $rows[0]['print_bank_details_2'];
        if ($print_logo_bool == 1 and $logo != null) {
            $keyName = $logo;
            $file = displayFileFromS3($GLOBALS['s3_finware_bucket'], $GLOBALS['finware_bucketName'], $keyName);
        } else {
            $file =  null;
        }

        if ($print_bank_details_1 == 1) {
            $bank_details_1 = $rows[0]['bank_details_1'];
            $serialized_bank_details_1 = unserialize($bank_details_1);
        } else {

            $serialized_bank_details_1 = null;
        }

        if ($print_bank_details_2 == 1) {
            $bank_details_2 = $rows[0]['bank_details_2'];
            $serialized_bank_details_2 = unserialize($bank_details_2);
        } else {

            $serialized_bank_details_2 = null;
        }
        return array(
            'setting_id' => $rows[0]['id'], 'logo' => $file, 'print_logo_bool' => $rows[0]['print_logo_bool'], 'report_print_company_name' => $rows[0]['report_print_company_name'],
            'report_print_branch_name' => $rows[0]['report_print_branch_name'], 'report_print_book_name' => $rows[0]['report_print_book_name'], 'bank_details_1' => $serialized_bank_details_1, 'bank_details_2' => $serialized_bank_details_2,
            'print_bank_details_1' => $print_bank_details_1, 'print_bank_details_2' => $print_bank_details_2, 'terms_conditions' => $rows[0]['terms_conditions'], 'transaction_numbering_system' => json_decode($rows[0]['transaction_numbering_system'], true),
            'prefix_financial_year' => $rows[0]['prefix_financial_year'], 'additional_transaction_prefix' => $rows[0]['additional_transaction_prefix']
        );
    } else {
        errorreturn("Book settings not found.");
    }
}


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

    $function_code = $postdata['function_type'];
    // $setting_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']);
        }
    }
    $success['data'] = fetchSpecificBookSettings($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id);
    successreturn($success);
}
