<?php

// this file required Update_ledgerbalances already included by the parent file before calling this file.
function checkTransactionData($specific_db_conn, $transaction_id, $workspace_id, $company_id, $branch_id, $book_id, $new_transactiondata, $transaction_numbering_system)
{
    $existing_transaction_data_info = array();

    $res = $specific_db_conn->prepare("SELECT * FROM act_transactiondata WHERE id = ? and  workspace_id  =? and company_id=? and branch_id=? and book_id =?");
    $res->execute(array($transaction_id, $workspace_id, $company_id, $branch_id, $book_id));
    $row = $res->fetchAll();

    if (count($row) == 1) {
        $existing_transaction_data_info = array(
            'transactiontype' => $row[0]['transactiontype'], 'unique_id' => $row[0]['unique_id'], 'financial_year' => $row[0]['financial_year'], 'filesattached' => $row[0]['filesattached'], 'date' => $row[0]['date'], 'narration' => $row[0]['narration'], 'reference_number' => $row[0]['reference_number'], 'dispatch_id' => $row[0]['dispatch_id'], 'flexible_mode' => $row[0]['flexible_mode'], 'billing_address' => $row[0]['billing_address'], 'shipping_address' => $row[0]['shipping_address'], 'e_way_bill' => $row[0]['e_way_bill']
        );
        $differences = array_diff_assoc($existing_transaction_data_info, $new_transactiondata);

        if (empty($differences)) {
            return false;
        } else {
            return true;
        }
    } else {
        return true;
    }
}

function checkTransactionRecord($specific_db_conn, $transaction_id, $workspace_id, $company_id, $branch_id, $book_id, $transaction_record_rows)
{

    $transaction_unique_ids = array();
    $transaction_record_rows = array();
    $res = $specific_db_conn->prepare("SELECT * FROM act_transactionrecord WHERE transaction_id = ? and  workspace_id  =? and company_id=? and branch_id=? and book_id =?");
    $res->execute(array($transaction_id, $workspace_id, $company_id, $branch_id, $book_id));
    $result1 = $res->fetchAll();
    // $transaction_date = $result1[0]['date'];

    foreach ($result1 as $row) {
        $transaction_unique_ids[] = array('ledgerid' => $row['ledgerid'], 'amount' => $row['amount'], 'balancetype' => $row['balancetype']);
    }

    foreach ($transaction_record_rows as &$row_unset) {
        unset($row_unset['ledger_main_ledgerhead']);
        unset($row_unset['ledger_parent_group']);
        unset($row_unset['instrument_details']);
        unset($row_unset['denominations']);
    }

    $differences = array_diff_assoc($transaction_unique_ids, $transaction_record_rows);
    if (empty($differences)) {
        return false;
    } else {
        return true;
    }
}


function checkTransactionReference($specific_db_conn, $transaction_id, $workspace_id, $company_id, $branch_id, $book_id, $ledgerid, $instrument_details)
{

    if ($instrument_details != null) {
        $instrument_details = $instrument_details[0];
    }

    $sql = "SELECT * FROM  act_bankinstrument 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($workspace_id, $company_id, $branch_id, $book_id, $transaction_id, $ledgerid));
    $act_record = $stmt->fetchAll();
    if (count($act_record) == 1) {
        $bankinstrument_rows = array('instrument_number' => $act_record[0]['instrument_number'], 'instrument_type' =>  $act_record[0]['instrument_type'], 'date_instrument' =>  $act_record[0]['date_instrument'], 'date_transaction' =>  $act_record[0]['date_transaction']);
        $differences = array_diff_assoc($bankinstrument_rows, $instrument_details);
        if (empty($differences))
            return false;
        else
            return true;
    } else {
        if ($instrument_details == null)
            return false;
        else
            return true;
    }
}

function checkTransactionDenomination($specific_db_conn, $transaction_id, $workspace_id, $company_id, $branch_id, $book_id, $ledgerid, $denominations)
{

    if ($denominations != null)
        $denominations = $denominations[0];

    $sql = "SELECT denominations FROM  act_denominations 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($workspace_id, $company_id, $branch_id, $book_id, $transaction_id, $ledgerid));
    $act_record = $stmt->fetchAll();
    if (count($act_record) == 1) {

        $existing_denominations = $act_record[0]['denominations'];
        if (strpos($existing_denominations, "#") === 0) {
            $existing_denominations = substr($existing_denominations, 1);
        }
        $pairs = explode("#", $existing_denominations);

        $denominations_rows = array();
        foreach ($pairs as $pair) {
            list($key, $value) = explode(":", $pair);
            $denominations_rows[(int)$key] = (int)$value;
        }
        $differences = array_diff_assoc($denominations, $denominations_rows);

        if (empty($differences))
            return false;
        else

            return true;
    } else {
        if ($denominations == null)
            return false;
        else
            return true;
    }
}


function checkStockTransaction($specific_db_conn, $transaction_id, $workspace_id, $company_id, $branch_id, $book_id, $stock_record)
{

    if ($stock_record != null)
        $stock_record = $stock_record[0];

    $sql = "SELECT * FROM   inventory_stocktransaction WHERE workspace_id = ? and company_id =? and branch_id =? and book_id =? and transaction_id=?";
    $stmt = $specific_db_conn->prepare($sql);
    $stmt->execute(array($workspace_id, $company_id, $branch_id, $book_id, $transaction_id));
    $act_record = $stmt->fetchAll();
    if (count($act_record) == 1) {
        $stock_rows = array(
            'stock_id' => $act_record[0]['stock_id'], 'qty' =>  $act_record[0]['qty'],
            'per_price' =>  $act_record[0]['per_price'], 'total_amount' =>  $act_record[0]['total_amount'], 'unit_id' =>  $act_record[0]['unit_id'], 'date' =>  $act_record[0]['date'], 'description' =>  $act_record[0]['description']
        );
        $differences = array_diff_assoc($stock_rows, $stock_record);
        if (empty($differences))
            return false;
        else
            return true;
    } else {
        if ($stock_record == null)
            return false;
        else
            return true;
    }
}


function checkStockClassification($specific_db_conn, $transaction_id, $workspace_id, $company_id, $branch_id, $book_id, $stock_record)
{

    if ($stock_record != null)
        $stock_record = $stock_record[0]['ledger_entries'];

    $sql = "SELECT * FROM    inventory_stock_classification WHERE workspace_id = ? and company_id =? and branch_id =? and book_id =? and transaction_id=?";
    $stmt = $specific_db_conn->prepare($sql);
    $stmt->execute(array($workspace_id, $company_id, $branch_id, $book_id, $transaction_id));
    $act_record = $stmt->fetchAll();
    if (count($act_record) == 1) {
        $stock_rows = array(
            'inventory_transaction_stockid' => $act_record[0]['inventory_transaction_stockid'], 'transaction_id' =>  $act_record[0]['transaction_id'],
            'ledgerid' =>  $act_record[0]['ledgerid'], 'percentage' =>  $act_record[0]['percentage'], 'total_amount' =>  $act_record[0]['total_amount'], 'adjusted_type' =>  $act_record[0]['adjusted_type'], 'sequence' =>  $act_record[0]['sequence'], 'is_add' =>  $act_record[0]['is_add']
        );
        $differences = array_diff_assoc($stock_rows, $stock_record);
        if (empty($differences))
            return false;
        else
            return true;
    } else {
        if ($stock_record == null)
            return false;
        else
            return true;
    }
}

function checkBatchDetails($specific_db_conn, $transaction_id, $workspace_id, $company_id, $branch_id, $book_id, $stock_record)
{

    if ($stock_record != null)
        $batch_details = $stock_record[0]['batch_details'];

    $sql = "SELECT * FROM    inventory_batch_details WHERE workspace_id = ? and company_id =? and branch_id =? and book_id =? and transaction_id=?";
    $stmt = $specific_db_conn->prepare($sql);
    $stmt->execute(array($workspace_id, $company_id, $branch_id, $book_id, $transaction_id));
    $act_record = $stmt->fetchAll();
    if (count($act_record) == 1) {
        $stock_rows = array(
            'stock_barcode_uin' =>  $act_record[0]['stock_barcode_uin'], 'transaction_id' =>  $act_record[0]['transaction_id'],
            'date' =>  $act_record[0]['date'], 'type' =>  $act_record[0]['type'], 'rate' =>  $act_record[0]['rate'], 'qty' =>  $act_record[0]['qty'],
            'expiry' =>  $act_record[0]['expiry'], 'mfg_date' =>  $act_record[0]['mfg_date'], 'amount' =>  $act_record[0]['amount'], 'remarks' => $act_record[0]['remarks']
        );
        $differences = array_diff_assoc($stock_rows, $batch_details);
        if (empty($differences))
            return false;
        else
            return true;
    } else {
        if ($stock_record == null)
            return false;
        else
            return true;
    }
}
function checkDispatch($specific_db_conn, $transaction_id, $workspace_id, $company_id, $branch_id, $book_id, $dispatch)
{

    if ($dispatch != null)
        $dispatch = $dispatch[0]['dispatch'];

    $sql = "SELECT * FROM  act_dispatch_info WHERE workspace_id = ? and company_id =? and branch_id =? and book_id =? and transaction_id=?";
    $stmt = $specific_db_conn->prepare($sql);
    $stmt->execute(array($workspace_id, $company_id, $branch_id, $book_id, $transaction_id));
    $act_record = $stmt->fetchAll();
    if (count($act_record) == 1) {
        $stock_rows = array(
            'doc_no' => $act_record[0]['doc_no'], 'delivery_note' => $act_record[0]['delivery_note'], 'destination' =>  $act_record[0]['destination'],
            'carrier_name' =>  $act_record[0]['carrier_name'], 'bill_of_lading' =>  $act_record[0]['bill_of_lading'],
            'dispatch_date' =>  $act_record[0]['dispatch_date'], 'motor' =>  $act_record[0]['motor']
        );
        $differences = array_diff_assoc($stock_rows, $dispatch);
        if (empty($differences))
            return false;
        else
            return true;
    } else {
        if ($dispatch == null)
            return false;
        else
            return true;
    }
}


function DeleteTransaction($specific_db_conn, $transaction_id, $workspace_id, $company_id, $branch_id, $book_id) // this deleted the whole transaction
{

    $delete_transaction = deleteOnlyTransactionRecords($specific_db_conn, $transaction_id, $workspace_id, $company_id, $branch_id, $book_id);

    if ($delete_transaction == true) {
        $sql = "DELETE FROM act_transactiondata WHERE id=? and workspace_id = ? and company_id =? and branch_id =? and book_id =? ";
        $stmt = $specific_db_conn->prepare($sql);
        $stmt->execute(array($transaction_id, $workspace_id, $company_id, $branch_id, $book_id));
        $transaction = $stmt->rowCount();
        if ($transaction == 1) {
            return true;
        } else {
            return false;
        }
    }
}

function deleteOnlyTransactionRecords($specific_db_conn, $transaction_id, $workspace_id, $company_id, $branch_id, $book_id)
{

    $transaction_unique_ids = array();
    $res = $specific_db_conn->prepare("SELECT * FROM act_transactionrecord WHERE transaction_id = ? and  workspace_id  =? and company_id=? and branch_id=? and book_id =?");
    $res->execute(array($transaction_id, $workspace_id, $company_id, $branch_id, $book_id));
    $result1 = $res->fetchAll();

    if (count($result1) >= 1) {
        $transaction_date = $result1[0]['date'];

        foreach ($result1 as $row) {
            $transaction_unique_ids[] = array(
                'ledgerid' => $row['ledgerid'], 'transaction_id' => $row['transaction_id'], 'amount' => $row['amount'], 'balancetype' => $row['balancetype'], 'main_ledgerhead' => $row['main_ledgerhead'], 'parent_ledgerhead' => $row['parent_ledgerhead'], 'reference_id' => $row['reference_id']
            );
        }

        foreach ($transaction_unique_ids as $row1) {
            //print_r($row1);die();
            $balancetype = $row1['balancetype'];
            $ledgerid = $row1['ledgerid'];
            $amount = $row1['amount'];
            $main_ledgerhead = $row1['main_ledgerhead'];
            $parent_ledgerhead = $row1['parent_ledgerhead'];
            $diff = ($balancetype == 'dr') ? -$amount : $amount;
            $reference_id = $row1['reference_id'];
            //include file updateledgerbalances
            UpdateLedgerBalance($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $ledgerid, $diff, $transaction_date, $main_ledgerhead, $parent_ledgerhead);
        }

        $sql = "DELETE FROM act_bankinstrument WHERE workspace_id = ? and company_id =? and branch_id =? and book_id =? and  transaction_id=? ";
        $stmt = $specific_db_conn->prepare($sql);
        $stmt->execute(array($workspace_id, $company_id, $branch_id, $book_id, $transaction_id));

        $sql = "DELETE FROM act_denominations WHERE workspace_id = ? and company_id =? and branch_id =? and book_id =? and  transaction_id=? ";
        $stmt = $specific_db_conn->prepare($sql);
        $stmt->execute(array($workspace_id, $company_id, $branch_id, $book_id, $transaction_id));


        // select boolean_inventory fr this specific stock id
        $sql_stock = "Select boolean_inventory from inventory_stockdetails where id = ? and workspace_id = ? and company_id =? and branch_id =? and book_id =?";
        $stmt_stock = $specific_db_conn->prepare($sql_stock);

        // preparing query to update stock details qty
        $sql_update_stockdetails_qty = "Update inventory_stockdetails set current_qty = current_qty + ? where id = ? and workspace_id = ? and company_id = ? and branch_id = ? and book_id = ? ";
        $update_stockdetails_qty = $specific_db_conn->prepare($sql_update_stockdetails_qty);

        $sql_update_stockdetails_balance_and_qty = "Update inventory_stockdetails set current_qty = current_qty + ?, current_balance = current_balance + ? where id = ? and workspace_id = ? and company_id = ? and branch_id = ? and book_id = ?";
        $update_stockdetails_balance_and_qty = $specific_db_conn->prepare($sql_update_stockdetails_balance_and_qty);

        $sql_delete_stocktransaction = "DELETE FROM inventory_stocktransaction WHERE transaction_id=? and workspace_id = ? and company_id =? and branch_id =? and book_id =? ";
        $delete_stocktransaction = $specific_db_conn->prepare($sql_delete_stocktransaction);
        // fetch the quantity
        $sql = "Select qty, stock_id, total_amount, type from inventory_stocktransaction where transaction_id=? and workspace_id = ? and company_id =? and branch_id =? and book_id =?";
        $stmt = $specific_db_conn->prepare($sql);
        $stmt->execute(array($transaction_id, $workspace_id, $company_id, $branch_id, $book_id));
        foreach ($stmt->fetchAll() as $temp_stock_record) {

            if ($temp_stock_record['type'] == 'purchase') {
                $difference_stock = -$temp_stock_record['qty'];
            } else if ($temp_stock_record['type'] == 'sales') {
                $difference_stock = abs($temp_stock_record['qty']);
            }
            $stmt_stock->execute(array($temp_stock_record['stock_id'], $workspace_id, $company_id, $branch_id, $book_id));
            $result_stocks = $stmt_stock->fetchAll();

            if ($result_stocks[0]['boolean_inventory'] == 1) {
                // update only qty 
                $update_stockdetails_qty->execute(array($difference_stock, $temp_stock_record['stock_id'], $workspace_id, $company_id, $branch_id, $book_id));
            } else {
                if ($temp_stock_record['type'] == 'sales') {
                    $difference_stock = 1;
                    $difference_in_stock_balance = $temp_stock_record['total_amount'];
                } else {
                    $difference_stock = -1;
                    $difference_in_stock_balance = -$temp_stock_record['total_amount'];
                }
                // // echo $difference_stock,$difference_in_stock_balance;
                $update_stockdetails_balance_and_qty->execute(array($difference_stock, $difference_in_stock_balance, $temp_stock_record['stock_id'], $workspace_id, $company_id, $branch_id, $book_id));
            }
            // update stock details
            // delete from inventory_stocktransaction
            $delete_stocktransaction->execute(array($transaction_id, $workspace_id, $company_id, $branch_id, $book_id));
            //}
        }
        $sql_delete_batchdetails = "DELETE FROM inventory_batch_details WHERE transaction_id=? and workspace_id = ? and company_id =? and branch_id =? and book_id =? ";
        $delete_batchdetails = $specific_db_conn->prepare($sql_delete_batchdetails);
        $delete_batchdetails->execute(array($transaction_id, $workspace_id, $company_id, $branch_id, $book_id));

        $sql = "DELETE FROM  inventory_stock_classification WHERE transaction_id=? and workspace_id = ? and company_id =? and branch_id =? and book_id =? ";
        $stmt = $specific_db_conn->prepare($sql);
        $stmt->execute(array($transaction_id, $workspace_id, $company_id, $branch_id, $book_id));
        //delete dispatch info if it is true
        $sql = "DELETE FROM  act_dispatch_info WHERE transaction_id=? and workspace_id = ? and company_id =? and branch_id =? and book_id =? ";
        $stmt = $specific_db_conn->prepare($sql);
        $stmt->execute(array($transaction_id, $workspace_id, $company_id, $branch_id, $book_id));

        $sql = "DELETE FROM act_transactionrecord WHERE transaction_id=? and workspace_id = ? and company_id =? and branch_id =? and book_id =? ";
        $stmt_count = $specific_db_conn->prepare($sql);
        $stmt_count->execute(array($transaction_id, $workspace_id, $company_id, $branch_id, $book_id));
        $act_group = $stmt_count->rowCount();
        if ($act_group >= 1) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}
