<?php

$credittotal = 0.00;


$creditrecord = $postdata['creditrecord'];
// Decoding the JSON string to an array
$creditrecord = json_decode($creditrecord, true);

foreach ($creditrecord as  $item) {

    $credittotal += str_replace(",", "", $item['amount']);
    $ledgerid = $item['ledgerid'];
    $ledger_detail = GetBasicLedgerDetail($specific_db_conn, $item['ledgerid'], $workspace_id, $company_id, $branch_id, $book_id, $additionaldata);

    if ($ledger_detail[1]['ledger_main_ledgerhead'] == 'Bank Account' or $ledger_detail[1]['ledger_main_ledgerhead'] == 'Cash-in-Hand' and (key_exists('denominations', $item) or key_exists('instrument_details', $item))) {

        // call validateBankInstrument 
        $additional_data = array();
        $additional_data = ['base_currency_formal_name'];

        $base_currency = GetBasicCurrencyFormalName($specific_db_conn, $workspace_id, $company_id, $branch_id, $additional_data);
        foreach ($base_currency as $currency) {
            //  print_r($currency);
            $base_currency_formal_name = $currency['base_currency_formal_name'];
        }


        if (key_exists('instrument_details', $item)) {

            $instrument_details = $item['instrument_details'];
            // Decoding the JSON string to an array
            // $instrument_details = json_decode($instrument_details, true);
            validateBankInstrument($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $instrument_details, $base_currency_formal_name, $ledgerid, $book_opening_date, $book_closing_date);
        } else {

            $instrument_details = null;
        }

        if (key_exists('denominations', $item)) {
            $denominations = $item['denominations'];
            // Decoding the JSON string to an array
            //$denominations = json_decode($denominations, true);
            validateDenominations($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $denominations, $base_currency_formal_name, $item['amount']);
        } else {
            $denominations = null;
        }
    } else {
        $instrument_details = null;
        $denominations = null;
    }
    // print_r($instrument_details);

    $transaction_record_rows[] = array(
        'ledgerid' => $item['ledgerid'], 'relative_amount' => - (floatval($item['amount'])),
        'ledger_main_ledgerhead' => $ledger_detail[1]['ledger_main_ledgerhead'], 'ledger_parent_group' => $ledger_detail[0]['ledger_parent_group'],
        'amount' => abs(floatval($item['amount'])), 'balancetype' => 'cr', 'instrument_details' => $instrument_details, 'denominations' => $denominations
    );

    validateTransactionTypeRecords($transactiontype, 'cr', $ledger_detail[1]['ledger_main_ledgerhead']);
}



$debitrecord = $postdata['debitrecord'];
// Decoding the JSON string to an array
$debitrecord = json_decode($debitrecord, true);

$debittotal = 0.00;
foreach ($debitrecord as $item) {

    $debittotal += $item['amount'];
    $ledgerid = $item['ledgerid'];
    $ledger_detail = GetBasicLedgerDetail($specific_db_conn, $item['ledgerid'], $workspace_id, $company_id, $branch_id, $book_id, $additionaldata);


    if ($ledger_detail[1]['ledger_main_ledgerhead'] == 'Bank Account'  or $ledger_detail[1]['ledger_main_ledgerhead'] == 'Cash-in-Hand' and (key_exists('instrument_details', $item) or
        key_exists('denominations', $item))) {
        // call validateBankInstrument 
        $additional_data = array();
        $additional_data = ['base_currency_formal_name'];

        $base_currency = GetBasicCurrencyFormalName($specific_db_conn, $workspace_id, $company_id, $branch_id, $additional_data);
        foreach ($base_currency as $currency) {
            $base_currency_formal_name = $currency['base_currency_formal_name'];
        }

        if (key_exists('instrument_details', $item)) {

            $instrument_details = $item['instrument_details'];
            // Decoding the JSON string to an array
            // $instrument_details = json_decode($instrument_details, true);
            validateBankInstrument($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $instrument_details, $base_currency_formal_name, $ledgerid, $book_opening_date, $book_closing_date);
        } else {

            $instrument_details = null;
        }

        if (key_exists('denominations', $item)) {

            $denominations = $item['denominations'];
            // Decoding the JSON string to an array
            //$denominations = json_decode($denominations, true);
            validateDenominations($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $denominations, $base_currency_formal_name, $item['amount']);
        } else {
            $denominations = null;
        }
        // print_r($instrument_details);die();



    } else {
        $instrument_details = null;
        $denominations = null;
    }



    $transaction_record_rows[] = array(
        'ledgerid' => $item['ledgerid'], 'relative_amount' => floatval($item['amount']),
        'ledger_main_ledgerhead' => $ledger_detail[1]['ledger_main_ledgerhead'],
        'ledger_parent_group' => $ledger_detail[0]['ledger_parent_group'], 'amount' => abs(floatval($item['amount'])), 'balancetype' => 'dr',
        'instrument_details' => $instrument_details, 'denominations' => $denominations
    );



    validateTransactionTypeRecords($transactiontype, 'dr', $ledger_detail[1]['ledger_main_ledgerhead']);
}

if ($credittotal != $debittotal) {

    errorreturn('Credit and Debit total do not match.');
}


// Set the isolation level to READ COMMITTED
$specific_db_conn->exec("SET TRANSACTION ISOLATION LEVEL READ COMMITTED");

// Begin a transaction
$specific_db_conn->beginTransaction();

$allUpdatesSuccessful = true;
try {

    $result =  InsertTransactionData($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $transactiontype, $date, $username, null, $last_modified_by, $narration, $userid, $reference_number, $dispatch_id, $billing_address, $shipping_address, $e_way_bill, $prefix_financial_year_bool, $financial_year_startdate, $transaction_numbering_system, $unique_id, $additional_transaction_prefix);
    // print_r($result);die();
    $unique_id = $result['unique_id'];
    $transaction_id = $result['transaction_id'];

    //prepare query for transaction record insert
    $sql = "INSERT INTO act_transactionrecord(workspace_id,company_id,branch_id,book_id,transaction_id,ledgerid,main_ledgerhead,parent_ledgerhead,amount,balancetype,date) VALUES(?,?,?,?,?,?,?,?,?,?,?)";
    $insert_into_transactionrecord =  $specific_db_conn->prepare($sql);

    foreach ($transaction_record_rows as $row1) {

        $ledgerid = $row1['ledgerid'];
        $main_ledgerhead = $row1['ledger_main_ledgerhead'];
        $parent_ledgerhead = $row1['ledger_parent_group'];
        $amount = $row1['amount'];
        $relative_amount = $row1['relative_amount'];
        $balancetype = $row1['balancetype'];

        $insert_into_transactionrecord->execute(array($workspace_id, $company_id, $branch_id, $book_id, $transaction_id, $ledgerid, $main_ledgerhead, $parent_ledgerhead, $amount, $balancetype, $date));

        // use update ledgerbalance here

        UpdateLedgerBalance($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $ledgerid, $relative_amount, $date, $main_ledgerhead, $parent_ledgerhead, 1);


        $instrument_details = $row1['instrument_details'];
        $denominations = $row1['denominations'];
        if ($row1['instrument_details'] != null) {

            $temp_instrument_bank = AddBankInstrument($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $instrument_details, $ledgerid, $amount, $balancetype, $transactiontype, $date, $transaction_id);
            if ($temp_instrument_bank == false) {
                $specific_db_conn->rollBack();
                errorreturn('Unable to save transaction. Kindly try again later.');
            }
            $sql = "Update act_transactionrecord set reference_id = ? where   workspace_id = ? and company_id =? and branch_id=? and book_id =? and transaction_id= ?  and ledgerid =? ";
            $stmt = $specific_db_conn->prepare($sql);
            $stmt->execute(array($temp_instrument_bank, $workspace_id, $company_id, $branch_id, $book_id, $transaction_id, $ledgerid));
        }

        if ($row1['denominations'] != null) {
            $denominations_id = addDenominations($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $denominations, $ledgerid, $balancetype, $transaction_id, $amount);
            if ($denominations_id == false) {
                $specific_db_conn->rollBack();
                errorreturn('Unable to save transaction. Kindly try again later.');
            }
            $sql = "Update act_transactionrecord set reference_id = ? where   workspace_id = ? and company_id =? and branch_id=? and book_id =? and transaction_id= ? and ledgerid =? ";
            $stmt = $specific_db_conn->prepare($sql);
            $stmt->execute(array($denominations_id, $workspace_id, $company_id, $branch_id, $book_id, $transaction_id, $ledgerid));
        }
    }

    $transactionrecord_id = $specific_db_conn->lastInsertId();

    if ($filesattached == null) {

        $filesattached = null;
    } else {
        $currentYear = date('Y');
        $currentMonth = date('n');
        $currentDay =  date('d');


        $directoryPathMain = "user_uploads/" .  'workspace_'  . $workspace_id . "/" . 'company_' .  $company_id . "/" . 'branch_' .  $branch_id . "/" . 'book_' .  $book_id . "/transaction_attachments/" . $currentYear . "/" . $currentMonth . "/";
        $originalFileName = $_FILES['filesattached']['name'];
        $fileTmpName = $_FILES['filesattached']["tmp_name"];
        $fileSize = $_FILES['filesattached']["size"];
        $fileType = $_FILES['filesattached']["type"];
        $fileError = $_FILES['filesattached']["error"];
        $file_extension = strtolower(pathinfo($_FILES['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 = 2; // Maximum file size (2MB)

        checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
        awsS3UserUploadTransactionInsert($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $userid, $username, $size, $file_extension, $filesattached, $directoryPathMain, $transaction_id, $originalFileName);
    }

    $specific_db_conn->commit();

    $unique_id = getTransactionUniqueId($additional_transaction_prefix, $transaction_numbering_system, $unique_id, $transactiontype, $prefix_financial_year_bool, $date, $financial_year_startdate);

    successreturn(array('transaction_id' => $transaction_id, 'transaction_unique_id' =>  $unique_id, 'successmsg' => "Transaction saved successfully."));
} catch (Exception $e) {
    $specific_db_conn->rollBack();
    errorreturn("Error : " . $e->getMessage());
}
