<?php
function 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)
{

    $instrument_number = (isset($instrument_details[0]['instrument_number']) and !empty($instrument_details[0]['instrument_number'])) ? trim($instrument_details[0]['instrument_number']) : null;
    $date_instrument = (isset($instrument_details[0]['date_instrument']) and !empty($instrument_details[0]['date_instrument'])) ? trim($instrument_details[0]['date_instrument']) : null;

    if ($date_instrument != null) {
        if (!strtotime($date_instrument) or $date_instrument < $book_opening_date) {
            // echo $mindate,$book_opening_date;die();
            errorreturn('Instrument date  cannot be less than book opening date');
        }

        if (!strtotime($date_instrument) or $date_instrument > $book_closing_date) {

            errorreturn('Instrument date cannot be less than book closing date');
        }
    }

    $instrument_type = (isset($instrument_details[0]['instrument_type']) and !empty($instrument_details[0]['instrument_type'])) ? trim($instrument_details[0]['instrument_type']) : null;

    $allowedType = ['Cheque', 'Bank Draft', 'NEFT', 'RTGS', 'UPI'];

    if ($instrument_type != null) {
        // Validate if the input is a valid instrument type
        if (!in_array($instrument_type, $allowedType)) {
            errorreturn("Invalid input. Please select a Instrument Type.");
        }
    }

    if ($instrument_number != null and $instrument_type !=  null) {
        $res = $specific_db_conn->prepare("SELECT id FROM act_bankinstrument WHERE workspace_id  =? and company_id=? and branch_id=? and book_id =? and ledgerid !=? and instrument_number = ? and instrument_type =? ");
        $res->execute(array($workspace_id, $company_id, $branch_id, $book_id, $ledgerid, $instrument_number, $instrument_type));
        $result = $res->fetchAll();

        if (count($result) >= 1) {
            errorreturn("Bank Instrument and Number already exist");
        }
    }
}

function validateDenominations($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $denominations, $base_currency_formal_name, $amount)
{

    $denominations = (isset($denominations[0]) and !empty($denominations[0])) ? $denominations[0] : null;

    if ($denominations == '' or empty($denominations) or !is_array($denominations)) {

        $denominations = null;
    } else if ($denominations != null) {

        // validate that each key received in denominations should be present in the element string of denominatinos in gloabl currency
        $arrraykeys = array_keys($denominations);
        $allowed_denominationkeys = currency_denoniminations($base_currency_formal_name);
        // print_r($allowed_denominationkeys);
        foreach ($arrraykeys as $input) {
            //print_r ($allowed_denominationkeys);die();
            if (!in_array($input, $allowed_denominationkeys)) {

                // errorreturn invalid denomination 
                errorreturn("Please Enter Valid Currency");
            }
        }

        // iske baad each key ki value check krlo ki decimals na ho and negative bhi na ho
        if (is_float($allowed_denominationkeys) != $allowed_denominationkeys and $allowed_denominationkeys < 0) {
            errorreturn("convert number to words only accepts numbers");
        }

        $totalAmount = 0;
        //print_R($denominations);die();

        // Loop through the "denominations" array and calculate the total amount
        foreach ($denominations as $notes => $keys) {
            $denominationAmount = (int)$notes; // Convert the denomination (key) to an integer
            $quantity = (int)$keys; // Convert the quantity (value) to an integer
            $totalAmount += $denominationAmount * $quantity;
        }
        // Check if the total amount matches the expected amount
        if ($totalAmount === $amount) {
            //echo "The total amount matches the expected amount: " . $expectedAmount;
            return true;
        } else {
            errorreturn("The total amount does not match the expected amount. Expected: " . $amount . ", Actual: " . $totalAmount);
        }
    }
}

function addDenominations($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $denominations, $ledgerid, $balancetype, $transaction_id, $amount)
{
    // $denominations = (isset($denominations[0]['denominations']) and !empty($denominations[0]['denominations'])) ? $denominations[0]['denominations'] : null;

    if ($denominations == '' or !is_array($denominations)) {

        $data_denominations = null;
    } else {

        $result = '';

        foreach ($denominations[0] as $key => $value) {
            $result .= "#{$key}:{$value},";
        }
        // Remove the trailing comma
        $result = rtrim($result, ',');
        $data_denominations = $result;
    }

    if ($balancetype == 'dr') {

        $amount =  abs($amount);
    }

    if ($balancetype == 'cr') {

        $amount = abs($amount);
    }
    try {
        $sql = "INSERT INTO  act_denominations(workspace_id,company_id,branch_id,book_id,ledgerid,balancetype,transaction_id,denominations,amount)
                    VALUES(?,?,?,?,?,?,?,?,?)";
        $stmt =  $specific_db_conn->prepare($sql);
        $stmt->execute(array($workspace_id, $company_id, $branch_id, $book_id, $ledgerid, $balancetype, $transaction_id, $data_denominations, $amount));

        $denominations_id = $specific_db_conn->lastInsertId();

        return $denominations_id;
    } catch (Exception $e) {
        return false;
    }
}

function AddBankInstrument($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $instrument_details, $ledgerid, $amount, $balancetype, $transactiontype, $date, $transaction_id)
{
    // print_r($instrument_details);die();
    $instrument_number = (isset($instrument_details[0]['instrument_number']) and !empty($instrument_details[0]['instrument_number'])) ? trim($instrument_details[0]['instrument_number']) : null;
    $date_instrument = (isset($instrument_details[0]['date_instrument']) and !empty($instrument_details[0]['date_instrument'])) ? trim($instrument_details[0]['date_instrument']) : null;

    $instrument_type = (isset($instrument_details[0]['instrument_type']) and !empty($instrument_details[0]['instrument_type'])) ? trim($instrument_details[0]['instrument_type']) : null;



    try {
        $sql = "INSERT INTO act_bankinstrument(workspace_id,company_id,branch_id,book_id,ledgerid,balancetype,transactiontype,instrument_number,instrument_type,transaction_id,date_instrument, date_transaction)
                    VALUES(?,?,?,?,?,?,?,?,?,?,?,?)";
        $stmt =  $specific_db_conn->prepare($sql);
        $stmt->execute(array($workspace_id, $company_id, $branch_id, $book_id, $ledgerid, $balancetype, $transactiontype, $instrument_number, $instrument_type, $transaction_id, $date_instrument, $date));

        $bankinstrument_id = $specific_db_conn->lastInsertId();

        return $bankinstrument_id;
    } catch (Exception $e) {
        return false;
    }
}
