<?php

ini_set('display_errors', 1);
// error_reporting(0);

//require_once '../../resources/base_path_include.php';
require_once '../../../resources/base_path_include.php';
// should we not call header and ch
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';

//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/groups_ledgers/update_ledger_balance.php';
require_once $base_path . 'modules/accounting/functions/basic_balance_function.php';
//bank instrument
require_once $base_path . 'modules/accounting/transaction_management/functions/bank_instrument_functions.php';

//transactiontype validate
require_once $base_path . 'modules/accounting/transaction_management/functions/transactiontype_validation_functions.php';
require_once $base_path . 'modules/accounting/transaction_management/functions/get_transaction_uniqueid.php';
require_once $base_path . 'modules/accounting/transaction_management/transaction_record_classification/transactiondata.php';

require_once $base_path . 'modules/accounting/stock_management/functions/stock_transaction_function.php';
//stock transaction classification
require_once $base_path . 'modules/accounting/stock_management/functions/stock_transaction_classification.php';
require_once $base_path . 'modules/accounting/stock_management/functions/stock_function.php';
//batch details
require_once $base_path . 'modules/accounting/stock_management/functions/inventory_batch_details_function.php';

//files code for userupload
require_once $base_path . '/modules/accounting/transaction_management/functions/transaction_userupload_functions.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);
$postdata = $_POST;
// print_r($postdata);die();
// 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['date']) or !checkIfIssetAndNotEmpty($postdata['date'])
    or !checkIfIssetAndNotEmpty($postdata['transactiontype'])  or !isset($postdata['transactiontype'])  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;

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

    $company_id = trim($postdata['company_id']);
    $branch_id = trim($postdata['branch_id']);
    $book_id = trim($postdata['book_id']);
    $flexible_mode = isset($postdata['flexible_mode']) ? trim($postdata['flexible_mode']) : 0;
    $billing_address = (isset($postdata['billing_address']) and !empty($postdata['billing_address'])) ? $postdata['billing_address'] : null;
    if (!is_null($billing_address)) {
        $billing_address = json_decode($billing_address, true);
    }else{
        $billing_address =  null;
    }
    
    $shipping_address = (isset($postdata['shipping_address']) and !empty($postdata['shipping_address'])) ? $postdata['shipping_address'] : null;
    if (!is_null($billing_address)) {
          $shipping_address = json_decode($shipping_address, true);
    }else{
        $shipping_address =  null;
    }
  
    $e_way_bill = (isset($postdata['e_way_bill']) and !empty($postdata['e_way_bill'])) ? $postdata['e_way_bill'] : null;
    $date = date('Y-m-d', strtotime($postdata['date']));

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

    $book_info = GetBasicBook($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $date);

    $book_opening_date = $book_info['book_basic_info']['book_opening_date'];
    $book_closing_date = $book_info['book_basic_info']['book_closing_date'];
    // print_r($book_opening_date);die();

    if (!strtotime($date) or $date < $book_opening_date or $date > $book_closing_date) {
        errorreturn('Invalid Date format');
    }

    $transactiontype = trim($postdata['transactiontype']); // validate, it can be a receipt or payment or journal or contra, nothing else should eb allwed

    if ($transactiontype != 'receipt' && $transactiontype != 'payment' && $transactiontype != 'contra' and $transactiontype != "journal" &&  $transactiontype != "purchase" && $transactiontype != "sales" &&  $transactiontype != "inter_region_stock") {

        errorreturn('Invalid transaction type');
    }
    // $narration = ucwords(trim($postdata['narration']));
    $narration = (isset($postdata['narration']) and !empty($postdata['narration'])) ? ucwords(trim($postdata['narration'])) : null;

    $to_region = (isset($postdata['to_region']) and !empty($postdata['to_region'])) ? trim($postdata['to_region']) : null;
    $from_region = (isset($postdata['from_region']) and !empty($postdata['from_region'])) ? trim($postdata['from_region']) : null;

    // if transactiontype == purchase
    if ($transactiontype == "purchase" or $transactiontype == "sales") {

        $reference_number = (isset($postdata['reference_number']) and !empty($postdata['reference_number'])) ? ($postdata['reference_number']) : null;  // this is supposed to be supplier invoice number -
        $dispatch_id = (isset($postdata['dispatch_id']) and !empty($postdata['dispatch_id'])) ? ($postdata['dispatch_id']) : null; // this is supposed to be supplier_invoice_date - y-m-d - can not greater then date of trnactuon date

    } else {
        $reference_number = null;
        $dispatch_id = null;
    }

    $last_modified_by = null;

    $additionaldata = array();
    $additionaldata = ['ledger_parent_group', 'ledger_main_ledgerhead'];

    $transaction_record_rows = array();
    $filesattached = (isset($_FILES['filesattached']) and !empty($_FILES['filesattached'])) ? $_FILES['filesattached'] : null;
    $dispatch = (isset($postdata['dispatch']) and !empty($postdata['dispatch'])) ? ($postdata['dispatch']) : null;
    if (!is_null($dispatch)) {
    $dispatch = json_decode($dispatch, true);
    }else{
        $dispatch =  null;
    }
    //validating billing and shipping combination,
    // if ($billing_address != null or $shipping_address != null) {
    if ((is_array($billing_address) and is_array($shipping_address))  and ($billing_address != null and $shipping_address != null)) {

        // Combine both addresses into a single array

        if ($billing_address != null) {
            $values[] = $billing_address['id'];
        }

        if ($shipping_address != null) {
            $values[] = $shipping_address['id'];
        }

        // Convert the values into a comma-separated string
        $valueString = implode(',', $values);

        $sql_validate_ledger = "Select id from act_ledger_addresses where id IN ($valueString)";
        $sql_validate_ledger = $specific_db_conn->prepare($sql_validate_ledger);
        $sql_validate_ledger->execute();
        if (count($sql_validate_ledger->fetchAll()) != 1) {
            errorreturn("Unable to find Billing and Shipping Address.");
        }
    }

    // fetching book settings to identify if numbering is automatic or manual or automatic_override_manual
    $financial_year_startdate = $book_info['book_basic_info']['financial_year_startdate'];
    $sql = "Select transaction_numbering_system, prefix_financial_year, additional_transaction_prefix from act_book_settings where workspace_id = ? and company_id = ? and branch_id = ? and book_id = ?";
    $fetch = $specific_db_conn->prepare($sql);
    $fetch->execute(array($workspace_id, $company_id, $branch_id, $book_id));
    $result_settings = $fetch->fetchAll();
    if (count($result_settings) == 1) {
        $transaction_numbering_system = json_decode($result_settings[0]['transaction_numbering_system'], true);
        $prefix_financial_year_bool = $result_settings[0]['prefix_financial_year'];
        $additional_transaction_prefix = $result_settings[0]['additional_transaction_prefix'];
    } else {
        errorreturn('Kindly set the transaction numbering settings first.');
    }

    if (in_array($transactiontype, $transaction_numbering_system['manual'])) {
        // check for the presence of it
        $unique_id = trim($postdata['transaction_unique_id']);
        if (empty($unique_id)) {
            errorreturn('You cannot leave transaction number empty.');
        }
    } else {
        $unique_id = null;
    }

    require_once $base_path . 'modules/accounting/transaction_management/functions/get_transaction_uniqueid.php';

    if ($transactiontype == 'inter_region_stock') {
        //required file for stock transaction
        require_once $base_path . 'modules/accounting/transaction_management/transaction_record_classification/inter_region_stock.php';
    } else if ($transactiontype == 'receipt' or $transactiontype == 'payment' or $transactiontype == 'contra' or $transactiontype == "journal") {

        //required file for stock transaction
        require_once $base_path . 'modules/accounting/transaction_management/transaction_record_classification/basic_transaction.php';
    } else if ($transactiontype == "purchase") {

        require_once $base_path . 'modules/accounting/transaction_management/transaction_record_classification/purchase_transaction.php';
    } else if ($transactiontype == "sales") {

        require_once $base_path . 'modules/accounting/transaction_management/transaction_record_classification/sales_transaction.php';
    }
}
