<?php
include('db_connection.php');
$Mainclass=new DB_Controller();



$Secret = $_REQUEST['Secret_Code'];
$Dealer_Code = "HM";

// Function to record cash transaction
function recordCashTransaction($Mainclass,$dealerCode, $date, $amount, $transactionId, $transactionType) {
    $lastBalanceStmt = $Mainclass->dbh->prepare("SELECT Balance FROM gold_cash_movement_master WHERE Dealer_Code = ? ORDER BY SLN DESC LIMIT 1");
    $lastBalanceStmt->bind_param("s", $dealerCode);
    $lastBalanceStmt->execute();
    $lastBalanceResult = $lastBalanceStmt->get_result()->fetch_assoc();
    $lastBalanceStmt->close();
    $finalBalance = $lastBalanceResult ? $lastBalanceResult['Balance'] : 0;
	
	
	$lastBalanceStmt_p = $Mainclass->dbh->prepare("SELECT Balance FROM cash_movement_master WHERE Dealer_Code = ? ORDER BY SLN DESC LIMIT 1");
    $lastBalanceStmt_p->bind_param("s", $dealerCode);
    $lastBalanceStmt_p->execute();
    $lastBalanceResult_p = $lastBalanceStmt_p->get_result()->fetch_assoc();
    $lastBalanceStmt_p->close();
    $finalBalance_p = $lastBalanceResult_p ? $lastBalanceResult_p['Balance'] : 0;
	
	
	
	

    $cashStatus = 1;
    $insertTransactionStmt = $Mainclass->dbh->prepare("INSERT INTO gold_cash_movement_master (Dealer_Code, Date, Cash_Out, Transaction_Id, Transaction_Type, Balance, Status) VALUES (?, ?, ?, ?, ?, ?, ?)");
    $insertTransactionStmt->bind_param("ssssssi", $dealerCode, $date, $amount, $transactionId, $transactionType, $finalBalance, $cashStatus);
    $insertTransactionStmt->execute();
    $insertTransactionStmt->close();
	
	
	$insertTransactionStmt1 = $Mainclass->dbh->prepare("INSERT INTO cash_movement_master (Dealer_Code, Date, Cash_Out, Transaction_Id, Transaction_Type, Balance, Status) VALUES (?, ?, ?, ?, ?, ?, ?)");
    $insertTransactionStmt1->bind_param("ssssssi", $dealerCode, $date, $amount, $transactionId, $transactionType, $finalBalance_p, $cashStatus);
    $insertTransactionStmt1->execute();
    $insertTransactionStmt1->close();
}

recordCashTransaction($Mainclass, $dealerCode, $date, $totalCostAmount, $challanNo, $transactionType);

?>