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

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

require_once $base_path_to_resources . "includes/config.php";
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_function.php';
require_once $base_path_to_resources . 'lib/validate_api_signature.php';

//authentication valdation file
require_once $base_path . 'user_management/authenticate.php';

//valdation file
require_once $base_path . 'modules/accounting/groups_ledgers/functions/ledger_functions.php';
require_once $base_path . 'modules/accounting/book_management/basic_book_info_function.php';
require_once $base_path . 'modules/accounting/functions/basic_balance_function.php';
require_once $base_path . 'modules/accounting/groups_ledgers/functions/display_transaction_functions.php';
require_once $base_path . 'modules/accounting/transaction_management/functions/get_transaction_uniqueid.php';


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

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

if (
    !isset($postdata['ledgerid']) or !checkIfIssetAndNotEmpty($postdata['ledgerid']) 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['api_signature']) or !checkIfIssetAndNotEmpty($postdata['api_signature']) 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;
$username = $jwt_validate->data->username;

$function_type = $postdata['function_type'];

if ($function_type  == "display_transactions") {

    $company_id = trim($postdata['company_id']);
    $branch_id = trim($postdata['branch_id']);
    $book_id = trim($postdata['book_id']);
    $ledgerid = trim($postdata['ledgerid']);
    $export_type = (isset($postdata['export_type']) and !empty($postdata['export_type'])) ? trim($postdata['export_type']) : null;
    $narration_bool = (isset($postdata['narration_bool']) and $postdata['narration_bool'] == 1) ? 1 : 0;
    if (isset($postdata['transactiontype']) and !empty($postdata['transactiontype'])) {
        $transactiontype = trim($postdata['transactiontype']);
    } else {
        $transactiontype = 'all';
    }
    $function_code = $postdata['function_type'];

    // access confirmation
    $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, $company_id, $branch_id, $book_id,  $function_code);
        }
    }

    $book_info = GetBasicBook($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id);
    // print_r($book_info);
    $book_name = $book_info['book_basic_info']['book_name'];
    $book_opening_date = $book_info['book_basic_info']['book_opening_date'];
    $book_closing_date = $book_info['book_basic_info']['book_closing_date'];


    if (isset($postdata['mindate']) and !empty($postdata['mindate'])) {
        $mindate = trim($postdata['mindate']);
    } else {
        $mindate = $book_opening_date;
    }
    if (isset($postdata['maxdate']) and !empty($postdata['maxdate'])) {
        $maxdate = trim($postdata['maxdate']);
    } else {
        $maxdate = $book_closing_date;
    }
    if (!strtotime($mindate) or $mindate < $book_opening_date) {
        errorreturn('Mininum date cannot be less than book opening date');
    }
    if (!strtotime($maxdate) or $maxdate > $book_closing_date) {

        errorreturn('Maximum date cannot be less than book opening date');
    }
    if ($maxdate < $mindate) {

        errorreturn('Invalid Date format');
    }

    $limit = $postdata['limit'];
    if (isset($postdata['page']) && is_numeric($postdata['page'])) {
        $page = (int) $postdata['page'];
    } else {
        $page = 1;  // default page number
    }

    if ($limit != 'all') {

        $offset = ($page - 1) * $limit;
    } else {
        $offset = 0;
    }

    if (isset($export_type)) { // true 
        // value check should either be spreadsheet pdf
        if ($export_type == 'spreadsheet') {
            require_once $base_path . 'modules/accounting/groups_ledgers/export/display_transactions/excel/export_display_transactions_excel.php';
        } else  if ($export_type == 'pdf') {
            require_once $base_path . 'modules/accounting/groups_ledgers/export/display_transactions/pdf/export_display_transactions_pdf.php';
        } else  if ($export_type == 'print') {
            require_once $base_path . 'modules/accounting/groups_ledgers/export/display_transactions/print/export_display_transactions_print.php';
        }
    } else {

        if ($limit != 'all') {
            $success['data'] = displayTransaction($specific_db_conn, $ledgerid, $workspace_id, $company_id, $branch_id, $book_id, $mindate, $maxdate, $limit, $offset, $narration_bool, $book_info,$transactiontype);
            successreturn($success);
        } else {
            $success['data'] = displayTransaction($specific_db_conn, $ledgerid, $workspace_id, $company_id, $branch_id, $book_id, $mindate, $maxdate, $limit, $offset, $narration_bool, $book_info,$transactiontype);
            successreturn($success);
        }
    }
}
