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


$Secret = $_REQUEST['Secret_Code'];
$Dealer_Code = $_COOKIE['O_Code'];

// Function to record cash transaction
function recordCashTransaction($Mainclass,$dealerCode, $date, $amount, $transactionId, $transactionType) {
    $lastBalanceStmt = $Mainclass->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->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->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->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();
}

// Check if Secret Code exists
$stmt = $Mainclass->dbh->prepare("SELECT COUNT(*) FROM gold_challan_master WHERE Secret_Code = ? AND Dealer_Code = ?");
$stmt->bind_param("ss", $Secret, $Dealer_Code);
$stmt->execute();
$stmt->bind_result($check_Secret_Code);
$stmt->fetch();
$stmt->close();

// Check if Status is Complete or Cancel
$stmt = $Mainclass->dbh->prepare("SELECT COUNT(*) FROM gold_challan_master WHERE Secret_Code = ? AND Dealer_Code = ? AND (Status = 'Complete' OR Status = 'Cancel')");
$stmt->bind_param("ss", $Secret, $Dealer_Code);
$stmt->execute();
$stmt->bind_result($check_Secret_Code_Status);
$stmt->fetch();
$stmt->close();

if ($check_Secret_Code > 0 && $check_Secret_Code_Status == 0) {
    // Get Challan Number
    $stmt = $Mainclass->dbh->prepare("SELECT Challan_No FROM gold_challan_master WHERE Secret_Code = ?");
	if (!$stmt) {
    die("Prepare failed: (" . $Mainclass->dbh->errno . ") " . $Mainclass->dbh->error);
}
    $stmt->bind_param("s", $Secret);
    $stmt->execute();
    $stmt->bind_result($Challan_No);
    $stmt->fetch();
    $stmt->close();

    // Check if GRN exists
    $stmt = $Mainclass->dbh->prepare("SELECT COUNT(*) FROM gold_grn_master WHERE Challan_No = ?");
	if (!$stmt) {
    die("Prepare failed: (" . $Mainclass->dbh->errno . ") " . $Mainclass->dbh->error);
    }
    $stmt->bind_param("s", $Challan_No);
    $stmt->execute();
    $stmt->bind_result($Check_GRN_No);
    $stmt->fetch();
    $stmt->close();

    if ($Check_GRN_No == 0) {
        $currentYr = date("y");
        $currentMonth = date("m");
        $currentYrFinacila = ($currentMonth < 4) ? ($currentYr - 1) : $currentYr;
        $FinalcialRange = $currentYrFinacila . "-" . ($currentYrFinacila + 1);

        // Generate GRN manually (you may replace this with actual logic)
        //$NEW_GRN = "GRN" . rand(1000, 9999);
		
		$NEW_GRN=$Mainclass->Generate_GRN($Dealer_Code,$FinalcialRange);

        $stmt = $Mainclass->dbh->prepare("INSERT INTO gold_grn_master (GRN_NO, Challan_No, Dealer_Code, Creation_Date, Financial_Year) VALUES (?, ?, ?, ?, ?)");
        $now = date("Y-m-d H:i:s");
        $stmt->bind_param("sssss", $NEW_GRN, $Challan_No, $Dealer_Code, $now, $FinalcialRange);
        $stmt->execute();
        $stmt->close();
    } else {
        $stmt = $Mainclass->dbh->prepare("SELECT GRN_NO FROM gold_grn_master WHERE Challan_No = ?");
        $stmt->bind_param("s", $Challan_No);
        $stmt->execute();
        $stmt->bind_result($NEW_GRN);
        $stmt->fetch();
        $stmt->close();
    }

    // Get all Challan Details
    $stmt =$Mainclass->dbh->prepare("SELECT SLN, Product_Code,Barcode, Quantity, Category_Code,Total_MRP,Total_Cost_Price,gold_purity,gold_wt,diamond_ct,solitaire_ct FROM gold_challan_details WHERE Challan_No = ?");
    $stmt->bind_param("s", $Challan_No);
    $stmt->execute();
    $result = $stmt->get_result();
    $DetailsList = [];
    while ($row = $result->fetch_assoc()) {
        $DetailsList[] = $row;
    }
    $stmt->close();

    // Update Receiving Start
    $now = date("Y-m-d H:i:s");
    $stmt = $Mainclass->dbh->prepare("UPDATE gold_challan_master SET Receiving_Start = ? WHERE Challan_No = ?");
    $stmt->bind_param("ss", $now, $Challan_No);
    $stmt->execute();
    $stmt->close();

    foreach ($DetailsList as $Details) {
        $SLN = $Details['SLN'];
        $Product_Code = $Details['Product_Code'];
		$Barcode = $Details['Barcode'];
        $Quantity = $Details['Quantity'];
        $Category_Code = $Details['Category_Code'];

        // Check if already received
        $stmt = $Mainclass->dbh->prepare("SELECT COUNT(*) FROM gold_challan_details WHERE SLN = ? AND Received = '0'");
        $stmt->bind_param("i", $SLN);
        $stmt->execute();
        $stmt->bind_result($Check_Received);
        $stmt->fetch();
        $stmt->close();

        if ($Check_Received > 0) {
            // Check if product exists in dealer stock
            $stmt = $Mainclass->dbh->prepare("SELECT COUNT(*) FROM dealer_gold_stock_master WHERE Product_Code = ? AND Dealer_Code = ?");
            $stmt->bind_param("ss", $Product_Code, $Dealer_Code);
            $stmt->execute();
            $stmt->bind_result($check_Product_Code);
            $stmt->fetch();
            $stmt->close();

            if ($check_Product_Code == 0) {
                // Insert into dealer_gold_stock_master
                $stmt = $Mainclass->dbh->prepare("INSERT INTO dealer_gold_stock_master (Dealer_Code, Product_Code,Barcode, Quantity, Category_Code,gold_purity,gold_wt,diamond_ct,solitaire_ct) VALUES (?, ?, ?, ?,?,?, ?, ?,?)");
                $stmt->bind_param("sssissddd", $Dealer_Code, $Product_Code, $Barcode,$Quantity, $Category_Code,$Details['gold_purity'],$Details['gold_wt'],$Details['diamond_ct'],$Details['solitaire_ct']);
                $stmt->execute();
                $stmt->close();

                // Insert into stock_transaction_master
                $today = date("Y-m-d");
                $stmt = $Mainclass->dbh->prepare("INSERT INTO  gold_stock_transaction_master(Challan_No, Date, Dealer_Code, Product_Code, Category_Code, Stock_In, Balance, Movement_Type,gold_purity,gold_wt,diamond_ct,solitaire_ct) VALUES (?, ?, ?, ?, ?, ?, ?, 'Transfer From HO',?, ?, ?, ?)");
                $stmt->bind_param("sssssiisddd", $Challan_No, $today, $Dealer_Code, $Product_Code, $Category_Code, $Quantity, $Quantity,$Details['gold_purity'],$Details['gold_wt'],$Details['diamond_ct'],$Details['solitaire_ct']);
                $stmt->execute();
                $stmt->close();
            }

            // Update gold_challan_details
            $stmt = $Mainclass->dbh->prepare("UPDATE gold_challan_details SET Received = '1', GRN_NO = ? WHERE SLN = ?");
            $stmt->bind_param("si", $NEW_GRN, $SLN);
            $stmt->execute();
            $stmt->close();
        }
		
		 $Tot_Price=$Details['Total_Cost_Price'];
		 $TotalMRP=$Details['Total_MRP'];
		
		$Total_Price=$Total_Price + $Tot_Price;
		$TotalMRPAmt=$TotalMRPAmt+$TotalMRP;
    }

    // Final update gold_challan_master
    $now = date("Y-m-d H:i:s");
    $stmt = $Mainclass->dbh->prepare("UPDATE gold_challan_master SET Status = 'Complete', GRN_NO = ?, Receiving_Date = ?, Receiving_End = ?,Total_MRP_Amount=?, Total_Challan_Amount=? WHERE Secret_Code = ? AND Dealer_Code = ?");
    $stmt->bind_param("sssddss", $NEW_GRN, $now, $now,$TotalMRPAmt,$Total_Price, $Secret, $Dealer_Code);
    $stmt->execute();
    $stmt->close();

    // Update indent_master
    $stmt = $Mainclass->dbh->prepare("UPDATE gold_indent_master SET Challan_Status = 'Received' WHERE Secret_Code = ? AND Dealer_Code = ?");
    $stmt->bind_param("ss", $Secret, $Dealer_Code);
    $stmt->execute();
    $stmt->close();
	
	$date = date('Y-m-d');
    $transactionType = "Stock Received From HO";
	$totalCostAmount=$Total_Price;
    recordCashTransaction($Mainclass->dbh, $dealerCode, $date, $totalCostAmount, $challanNo, $transactionType);

    $Error = '0';
} elseif ($check_Secret_Code == 0) {
    $Error = '1';
} elseif ($check_Secret_Code > 0 && $check_Secret_Code_Status > 0) {
    $Error = '2';
}

echo $Error . "*" . ($Challan_No ?? '');
$Mainclass->dbh->close();
exit();

?>