<?php
session_start();
header('Content-Type: application/json');
include_once('../../includes/config.php');

// Check authentication
if (!isset($_SESSION['uid'])) {
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit();
}

$response = ['success' => false, 'message' => ''];

// Get JSON data
$jsonData = file_get_contents('php://input');
$data = json_decode($jsonData, true);

if ($data) {
    // Start transaction
    mysqli_begin_transaction($con);
    
    try {
        $invoiceNumber = mysqli_real_escape_string($con, $data['invoiceNumber']);
        $supplierId = intval($data['supplierId']);
        $purchaseDate = mysqli_real_escape_string($con, $data['purchaseDate']);
        $purchaseType = isset($data['purchaseType']) ? mysqli_real_escape_string($con, $data['purchaseType']) : 'GST';
        $purchaseInvoiceNumber = isset($data['purchaseInvoiceNumber']) ? mysqli_real_escape_string($con, $data['purchaseInvoiceNumber']) : '';
        $purchaseInvoiceDate = isset($data['purchaseInvoiceDate']) ? mysqli_real_escape_string($con, $data['purchaseInvoiceDate']) : NULL;
        $subTotal = floatval($data['subTotal']);
        $freightAmount = isset($data['freightAmount']) ? floatval($data['freightAmount']) : 0;
        $transportName = isset($data['transportName']) ? mysqli_real_escape_string($con, $data['transportName']) : '';
        $vehicleNumber = isset($data['vehicleNumber']) ? mysqli_real_escape_string($con, $data['vehicleNumber']) : '';
        $transportGSTPercent = isset($data['transportGSTPercent']) ? floatval($data['transportGSTPercent']) : 0;
        $transportGSTType = isset($data['transportGSTType']) ? mysqli_real_escape_string($con, $data['transportGSTType']) : 'inclusive';
        $transportGSTAmount = isset($data['transportGSTAmount']) ? floatval($data['transportGSTAmount']) : 0;
        $roundOffAmount = isset($data['roundOffAmount']) ? floatval($data['roundOffAmount']) : 0;
        $totalAmount = floatval($data['totalAmount']);
        $finalAmount = isset($data['finalAmount']) ? floatval($data['finalAmount']) : $totalAmount;
        $billDiscount = isset($data['billDiscount']) ? floatval($data['billDiscount']) : 0;
        $billDiscountType = isset($data['billDiscountType']) ? mysqli_real_escape_string($con, $data['billDiscountType']) : 'PERCENTAGE';
        $discountAmount = isset($data['discountAmount']) ? floatval($data['discountAmount']) : 0;
        $paymentMode = mysqli_real_escape_string($con, $data['paymentMode']);
        $paymentAmount = isset($data['paymentAmount']) ? floatval($data['paymentAmount']) : 0;
        $paymentStatus = isset($data['paymentStatus']) ? mysqli_real_escape_string($con, $data['paymentStatus']) : 'Paid';
        $cashAmount = isset($data['cashAmount']) ? floatval($data['cashAmount']) : 0;
        $upiAmount = isset($data['upiAmount']) ? floatval($data['upiAmount']) : 0;
        $creditAmount = isset($data['creditAmount']) ? floatval($data['creditAmount']) : 0;
        $referenceNumber = isset($data['referenceNumber']) ? mysqli_real_escape_string($con, $data['referenceNumber']) : '';
        $notes = isset($data['notes']) ? mysqli_real_escape_string($con, $data['notes']) : '';
        $userId = intval($data['userId']);
        $editingPurchaseId = isset($data['editingPurchaseId']) ? intval($data['editingPurchaseId']) : 0;
        
        // Supplier invoice details
        $supplierInvoiceNumber = isset($data['supplierInvoiceNumber']) ? mysqli_real_escape_string($con, $data['supplierInvoiceNumber']) : '';
        $supplierInvoiceDate = isset($data['supplierInvoiceDate']) ? mysqli_real_escape_string($con, $data['supplierInvoiceDate']) : NULL;
        
        // Detect if this is a PURCHASE RETURN
        $isReturn = (strpos($purchaseType, '-PURCHASE-RETURN') !== false);
        
        if ($editingPurchaseId > 0) {
            // EDIT MODE - Update existing purchase
            
            // Get old purchase data to reverse supplier account
            $oldPurchaseQuery = "SELECT SupplierID, FinalAmount, InvoiceNumber, PaymentAmount FROM tblpurchases WHERE ID = $editingPurchaseId";
            $oldPurchaseResult = mysqli_query($con, $oldPurchaseQuery);
            if (!$oldPurchaseResult || mysqli_num_rows($oldPurchaseResult) == 0) {
                throw new Exception('Purchase record not found for editing');
            }
            $oldPurchase = mysqli_fetch_assoc($oldPurchaseResult);
            $oldSupplierId = $oldPurchase['SupplierID'];
            $oldFinalAmount = floatval($oldPurchase['FinalAmount']);
            $oldPaymentAmount = floatval($oldPurchase['PaymentAmount']);
            $oldInvoiceNumber = $oldPurchase['InvoiceNumber'];
            
            // Get old purchase details to reverse stock
            $oldDetailsQuery = "SELECT ProductID, Quantity FROM tblpurchases_details WHERE PurchaseID = $editingPurchaseId";
            $oldDetailsResult = mysqli_query($con, $oldDetailsQuery);
            $oldItems = [];
            while ($row = mysqli_fetch_assoc($oldDetailsResult)) {
                $oldItems[$row['ProductID']] = floatval($row['Quantity']);
            }
            
            // Reverse stock for old items
            // For PURCHASES: DECREASE stock (we're removing the old purchase entry)
            // For PURCHASE RETURNS: INCREASE stock (we're removing the old return entry)
            foreach ($oldItems as $productId => $quantity) {
                $oldStockOperation = $isReturn ? '+' : '-';
                $reverseStockSql = "UPDATE tblitems SET CurrentStock = CurrentStock $oldStockOperation $quantity WHERE ID = $productId";
                if (!mysqli_query($con, $reverseStockSql)) {
                    throw new Exception('Error reversing stock for product ID ' . $productId . ': ' . mysqli_error($con));
                }
            }
            
            // Delete old purchase details
            $deleteSql = "DELETE FROM tblpurchases_details WHERE PurchaseID = $editingPurchaseId";
            if (!mysqli_query($con, $deleteSql)) {
                throw new Exception('Error deleting old purchase details: ' . mysqli_error($con));
            }
            
            // Delete old GST details if exists
            $deleteGSTSql = "DELETE FROM tblpurchases_gst_details WHERE PurchaseID = $editingPurchaseId";
            mysqli_query($con, $deleteGSTSql);
            
            // Get and delete old payment entries (to reverse supplier balance properly)
            $oldPaymentRef = 'PAY-' . $oldInvoiceNumber;
            $oldPaymentQuery = "SELECT Amount FROM tblsupplier_accounts 
                               WHERE InvoiceNumber = '$oldPaymentRef' AND SupplierID = $oldSupplierId AND TransactionType = 'Debit'";
            $oldPaymentResult = mysqli_query($con, $oldPaymentQuery);
            
            if ($oldPaymentResult && mysqli_num_rows($oldPaymentResult) > 0) {
                $oldPaymentRow = mysqli_fetch_assoc($oldPaymentResult);
                $oldPaymentAmountFromAccount = floatval($oldPaymentRow['Amount']);
                
                // Delete the old payment entry
                $deleteOldPaymentSql = "DELETE FROM tblsupplier_accounts 
                                       WHERE InvoiceNumber = '$oldPaymentRef' AND SupplierID = $oldSupplierId AND TransactionType = 'Debit'";
                mysqli_query($con, $deleteOldPaymentSql);
                
                // Reverse the payment effect on supplier balance (add back the payment since we paid before)
                if ($oldPaymentAmountFromAccount > 0) {
                    $reversePaymentBalanceSql = "UPDATE tblsuppliers SET 
                                                OutstandingBalance = OutstandingBalance + $oldPaymentAmountFromAccount
                                                WHERE ID = $oldSupplierId";
                    mysqli_query($con, $reversePaymentBalanceSql);
                }
            }
            
            // Update purchase master
            $purchaseSql = "UPDATE tblpurchases SET
                        SupplierID = $supplierId,
                        PurchaseDate = '$purchaseDate',
                        PurchaseType = '$purchaseType',
                        PurchaseInvoiceNumber = " . ($purchaseInvoiceNumber ? "'$purchaseInvoiceNumber'" : "NULL") . ",
                        PurchaseInvoiceDate = " . ($purchaseInvoiceDate ? "'$purchaseInvoiceDate'" : "NULL") . ",
                        SubTotal = $subTotal,
                        FreightAmount = $freightAmount,
                        TransportName = '$transportName',
                        VehicleNumber = '$vehicleNumber',
                        TransportGSTPercent = $transportGSTPercent,
                        TransportGSTType = '$transportGSTType',
                        TransportGSTAmount = $transportGSTAmount,
                        BillDiscount = $billDiscount,
                        BillDiscountType = '$billDiscountType',
                        DiscountAmount = $discountAmount,
                        RoundOffAmount = $roundOffAmount,
                        TotalAmount = $totalAmount,
                        FinalAmount = $finalAmount,
                        PaymentMode = '$paymentMode',
                        PaymentAmount = $paymentAmount,
                        PaymentStatus = '$paymentStatus',
                        CashAmount = $cashAmount,
                        UpiAmount = $upiAmount,
                        CreditAmount = $creditAmount,
                        ReferenceNumber = '$referenceNumber',
                        Notes = '$notes',
                        SupplierInvoiceNumber = " . ($supplierInvoiceNumber ? "'$supplierInvoiceNumber'" : "NULL") . ",
                        SupplierInvoiceDate = " . ($supplierInvoiceDate ? "'$supplierInvoiceDate'" : "NULL") . "
                        WHERE ID = $editingPurchaseId";
            
            if (!mysqli_query($con, $purchaseSql)) {
                throw new Exception('Error updating purchase: ' . mysqli_error($con));
            }
            
            $purchaseId = $editingPurchaseId;
            
            // Reverse old supplier account entry and create new one
            // Transaction types:
            // For PURCHASES: Credit (we owe supplier)
            // For RETURNS: Debit (supplier owes us / we get credit back)
            $transactionType = $isReturn ? 'Debit' : 'Credit';
            $description = $isReturn ? 'Purchase Return' : 'Purchase Bill';
            
            if ($oldSupplierId == $supplierId) {
                // Same supplier - check if amount changed
                $amountDifference = $finalAmount - $oldFinalAmount;
                
                if ($amountDifference != 0) {
                    // Update the account entry with new amount
                    $accountUpdateSql = "UPDATE tblsupplier_accounts SET
                                        Amount = $finalAmount,
                                        BalanceAmount = $finalAmount,
                                        TransactionDate = '$purchaseDate',
                                        PaymentMode = '$paymentMode',
                                        TransactionType = '$transactionType',
                                        Description = '$description'
                                        WHERE InvoiceNumber = '$oldInvoiceNumber' AND SupplierID = $oldSupplierId";
                    
                    if (!mysqli_query($con, $accountUpdateSql)) {
                        throw new Exception('Error updating supplier account: ' . mysqli_error($con));
                    }
                    
                    // Update supplier's outstanding balance
                    // For PURCHASES: If amount increased, add the difference (we owe more)
                    // For RETURNS: If amount increased, subtract the difference (they owe us more)
                    $balanceModifier = $isReturn ? '-' : '+';
                    $updateBalanceSql = "UPDATE tblsuppliers SET 
                                        OutstandingBalance = OutstandingBalance $balanceModifier ($amountDifference)
                                        WHERE ID = $supplierId";
                    
                    if (!mysqli_query($con, $updateBalanceSql)) {
                        throw new Exception('Error updating supplier balance: ' . mysqli_error($con));
                    }
                } else {
                    // Amount same, just update date and transaction details if changed
                    $accountUpdateSql = "UPDATE tblsupplier_accounts SET
                                        TransactionDate = '$purchaseDate',
                                        PaymentMode = '$paymentMode',
                                        TransactionType = '$transactionType',
                                        Description = '$description'
                                        WHERE InvoiceNumber = '$oldInvoiceNumber' AND SupplierID = $oldSupplierId";
                    mysqli_query($con, $accountUpdateSql);
                }
            } else {
                // Different supplier - remove from old supplier, add to new supplier
                
                // Delete old supplier account entry
                $deleteAccountSql = "DELETE FROM tblsupplier_accounts
                                    WHERE InvoiceNumber = '$oldInvoiceNumber' AND SupplierID = $oldSupplierId";
                
                if (!mysqli_query($con, $deleteAccountSql)) {
                    throw new Exception('Error deleting old supplier account: ' . mysqli_error($con));
                }
                
                // Decrease old supplier's outstanding balance (reverse the old transaction)
                // For old PURCHASES: Subtract the amount (reduce what we owe)
                // For old RETURNS: Add the amount (reduce what they owe us)
                $oldBalanceModifier = $isReturn ? '+' : '-';
                $updateOldSupplierSql = "UPDATE tblsuppliers SET 
                                        OutstandingBalance = OutstandingBalance $oldBalanceModifier $oldFinalAmount
                                        WHERE ID = $oldSupplierId";
                
                if (!mysqli_query($con, $updateOldSupplierSql)) {
                    throw new Exception('Error updating old supplier balance: ' . mysqli_error($con));
                }
                
                // Add to new supplier account
                // For PURCHASES: Credit (we owe them)
                // For RETURNS: Debit (they owe us)
                $accountSql = "INSERT INTO tblsupplier_accounts
                              (SupplierID, InvoiceNumber, TransactionType, TransactionDate, Amount, BalanceAmount, Description, PaymentMode, AddedBy)
                              VALUES
                              ($supplierId, '$invoiceNumber', '$transactionType', '$purchaseDate', $finalAmount, $finalAmount, '$description', '$paymentMode', $userId)";
                
                if (!mysqli_query($con, $accountSql)) {
                    throw new Exception('Error inserting new supplier account: ' . mysqli_error($con));
                }
                
                // Increase new supplier's outstanding balance
                // For PURCHASES: Add amount (we owe more)
                // For RETURNS: Subtract amount (they owe us / we get credit)
                $newBalanceModifier = $isReturn ? '-' : '+';
                $updateNewSupplierSql = "UPDATE tblsuppliers SET 
                                        OutstandingBalance = OutstandingBalance $newBalanceModifier $finalAmount
                                        WHERE ID = $supplierId";
                
                if (!mysqli_query($con, $updateNewSupplierSql)) {
                    throw new Exception('Error updating new supplier balance: ' . mysqli_error($con));
                }
            }
            
        } else {
            // NEW PURCHASE MODE - Insert new purchase
            
            // Insert purchase master
            $purchaseSql = "INSERT INTO tblpurchases
                        (InvoiceNumber, PurchaseType, SupplierID, PurchaseDate, PurchaseInvoiceNumber, PurchaseInvoiceDate,
                         SubTotal, FreightAmount, TransportName, VehicleNumber,
                         TransportGSTPercent, TransportGSTType, TransportGSTAmount, BillDiscount, BillDiscountType, DiscountAmount,
                         RoundOffAmount, TotalAmount, FinalAmount, PaymentMode, PaymentAmount, PaymentStatus,
                         CashAmount, UpiAmount, CreditAmount, ReferenceNumber, Notes, SupplierInvoiceNumber, SupplierInvoiceDate, AddedBy)
                        VALUES
                        ('$invoiceNumber', '$purchaseType', $supplierId, '$purchaseDate',
                         " . ($purchaseInvoiceNumber ? "'$purchaseInvoiceNumber'" : "NULL") . ",
                         " . ($purchaseInvoiceDate ? "'$purchaseInvoiceDate'" : "NULL") . ",
                         $subTotal, $freightAmount, '$transportName', '$vehicleNumber',
                         $transportGSTPercent, '$transportGSTType', $transportGSTAmount, $billDiscount, '$billDiscountType', $discountAmount,
                         $roundOffAmount, $totalAmount, $finalAmount, '$paymentMode', $paymentAmount, '$paymentStatus',
                         $cashAmount, $upiAmount, $creditAmount, '$referenceNumber', '$notes',
                         " . ($supplierInvoiceNumber ? "'$supplierInvoiceNumber'" : "NULL") . ",
                         " . ($supplierInvoiceDate ? "'$supplierInvoiceDate'" : "NULL") . ", $userId)";
            
            if (!mysqli_query($con, $purchaseSql)) {
                throw new Exception('Error inserting purchase: ' . mysqli_error($con));
            }
            
            $purchaseId = mysqli_insert_id($con);
            
            // Add to supplier account
            // For PURCHASES: Credit (we owe the supplier)
            // For RETURNS: Debit (supplier owes us / we get credit back)
            $transactionType = $isReturn ? 'Debit' : 'Credit';
            $description = $isReturn ? 'Purchase Return' : 'Purchase Bill';
            
            $accountSql = "INSERT INTO tblsupplier_accounts
                          (SupplierID, InvoiceNumber, TransactionType, TransactionDate, Amount, BalanceAmount, Description, PaymentMode, AddedBy)
                          VALUES
                          ($supplierId, '$invoiceNumber', '$transactionType', '$purchaseDate', $finalAmount, $finalAmount, '$description', '$paymentMode', $userId)";
            
            if (!mysqli_query($con, $accountSql)) {
                throw new Exception('Error inserting supplier account: ' . mysqli_error($con));
            }
            
            // Update supplier's outstanding balance
            // For PURCHASES: Increase by purchase amount (we owe more)
            // For RETURNS: Decrease by return amount (they owe us / we get credit)
            $balanceModifier = $isReturn ? '-' : '+';
            $updateSupplierBalanceSql = "UPDATE tblsuppliers SET 
                                        OutstandingBalance = OutstandingBalance $balanceModifier $finalAmount
                                        WHERE ID = $supplierId";
            
            if (!mysqli_query($con, $updateSupplierBalanceSql)) {
                throw new Exception('Error updating supplier outstanding balance: ' . mysqli_error($con));
            }
        }
        
        // Insert purchase details (common for both new and edit)
        foreach ($data['items'] as $item) {
            $productId = intval($item['productId']);
            $productCode = mysqli_real_escape_string($con, $item['productCode']);
            $productName = mysqli_real_escape_string($con, $item['productName']);
            $rate = floatval($item['rate']);
            $mrp = isset($item['mrp']) ? floatval($item['mrp']) : 0;
            $quantity = floatval($item['quantity']);
            $amount = floatval($item['amount']);
            
            // Discount fields
            $discount = isset($item['discount']) ? floatval($item['discount']) : 0;
            $discountType = isset($item['discountType']) ? mysqli_real_escape_string($con, $item['discountType']) : 'PERCENTAGE';
            
            // Calculate discount amount based on type
            $itemDiscountAmount = 0;
            if ($discount > 0) {
                if ($discountType === 'PERCENTAGE') {
                    $itemDiscountAmount = ($rate * $quantity * $discount) / 100;
                } else {
                    $itemDiscountAmount = $discount;
                }
            }
            
            // Calculate final rate and final total
            $itemSubtotal = $rate * $quantity;
            $finalTotal = $itemSubtotal - $itemDiscountAmount;
            $finalRate = $quantity > 0 ? ($finalTotal / $quantity) : $rate;
            
            // If ProductID is 0 or missing, fetch it from items table
            if ($productId == 0) {
                $productQuery = "SELECT ID FROM tblitems WHERE ItemCode = '$productCode' LIMIT 1";
                $productResult = mysqli_query($con, $productQuery);
                if ($productResult && mysqli_num_rows($productResult) > 0) {
                    $productRow = mysqli_fetch_assoc($productResult);
                    $productId = intval($productRow['ID']);
                }
            }
            
            // Insert purchase detail
            $detailSql = "INSERT INTO tblpurchases_details
                         (PurchaseID, ProductID, ProductCode, ProductName, Rate, MRP, Quantity,
                          Discount, DiscountType, DiscountAmount, FinalRate, FinalTotal, Amount)
                         VALUES
                         ($purchaseId, $productId, '$productCode', '$productName', $rate, $mrp, $quantity,
                          $discount, '$discountType', $itemDiscountAmount, $finalRate, $finalTotal, $amount)";
            
            if (!mysqli_query($con, $detailSql)) {
                throw new Exception('Error inserting purchase detail: ' . mysqli_error($con));
            }
            
            // IMPORTANT: Update stock based on purchase type
            // For PURCHASES: INCREASE stock (goods coming in)
            // For PURCHASE RETURNS: DECREASE stock (goods going back)
            if ($productId > 0 && $quantity > 0) {
                $stockOperation = $isReturn ? '-' : '+';
                $updateStockSql = "UPDATE tblitems SET CurrentStock = CurrentStock $stockOperation $quantity WHERE ID = $productId";
                if (!mysqli_query($con, $updateStockSql)) {
                    throw new Exception('Error updating stock for product ID ' . $productId . ': ' . mysqli_error($con));
                }
            }
            
            // Insert GST details if purchase type is GST
            if ($purchaseType === 'GST' && isset($item['gstDetails'])) {
                $gstDetails = $item['gstDetails'];
                $hsnCode = isset($gstDetails['hsnCode']) ? mysqli_real_escape_string($con, $gstDetails['hsnCode']) : '';
                $taxableAmount = isset($gstDetails['taxableAmount']) ? floatval($gstDetails['taxableAmount']) : $finalTotal;
                $taxPercentage = isset($gstDetails['taxPercentage']) ? floatval($gstDetails['taxPercentage']) : 0;
                $taxType = isset($gstDetails['taxType']) ? mysqli_real_escape_string($con, $gstDetails['taxType']) : 'INTRA';
                $cgstPercent = isset($gstDetails['cgstPercent']) ? floatval($gstDetails['cgstPercent']) : 0;
                $cgstAmount = isset($gstDetails['cgstAmount']) ? floatval($gstDetails['cgstAmount']) : 0;
                $sgstPercent = isset($gstDetails['sgstPercent']) ? floatval($gstDetails['sgstPercent']) : 0;
                $sgstAmount = isset($gstDetails['sgstAmount']) ? floatval($gstDetails['sgstAmount']) : 0;
                $igstPercent = isset($gstDetails['igstPercent']) ? floatval($gstDetails['igstPercent']) : 0;
                $igstAmount = isset($gstDetails['igstAmount']) ? floatval($gstDetails['igstAmount']) : 0;
                $totalTaxAmount = $cgstAmount + $sgstAmount + $igstAmount;
                $gstFinalAmount = $taxableAmount + $totalTaxAmount;
                
                $gstSql = "INSERT INTO tblpurchases_gst_details
                          (PurchaseID, InvoiceNumber, ProductID, ProductCode, ProductName, HSNCode, Rate, Quantity,
                           DiscountAmount, TaxableAmount, TaxPercentage, TaxType,
                           CGSTPercent, CGSTAmount, SGSTPercent, SGSTAmount, IGSTPercent, IGSTAmount,
                           TotalTaxAmount, FinalAmount)
                          VALUES
                          ($purchaseId, '$invoiceNumber', $productId, '$productCode', '$productName', '$hsnCode', $rate, $quantity,
                           $itemDiscountAmount, $taxableAmount, $taxPercentage, '$taxType',
                           $cgstPercent, $cgstAmount, $sgstPercent, $sgstAmount, $igstPercent, $igstAmount,
                           $totalTaxAmount, $gstFinalAmount)";
                
                mysqli_query($con, $gstSql); // Don't throw error if GST insert fails
            }
        }
        
        // Handle payment if amount is provided
        if ($paymentAmount > 0) {
            // Generate payment reference number
            $paymentRef = 'PAY-' . $invoiceNumber;
            
            // Insert payment into supplier account
            // For PURCHASES: Debit (we paid the supplier - reducing what we owe)
            // For RETURNS: Credit (supplier paid us back - reducing what they owe us)
            $paymentTransactionType = $isReturn ? 'Credit' : 'Debit';
            $paymentDescription = $isReturn ? 'Refund for Purchase Return' : 'Payment for Purchase';
            
            $paymentAccountSql = "INSERT INTO tblsupplier_accounts
                                  (SupplierID, InvoiceNumber, TransactionType, TransactionDate, Amount, BalanceAmount,
                                   Description, PaymentMode, ReferenceNumber, AddedBy)
                                  VALUES
                                  ($supplierId, '$paymentRef', '$paymentTransactionType', '$purchaseDate', $paymentAmount, $paymentAmount,
                                   '$paymentDescription $invoiceNumber', '$paymentMode', '$invoiceNumber', $userId)";
            
            if (!mysqli_query($con, $paymentAccountSql)) {
                throw new Exception('Error inserting payment account: ' . mysqli_error($con));
            }
            
            // Update supplier's outstanding balance
            // For PURCHASES: Decrease by payment amount (we paid them)
            // For RETURNS: Increase by payment amount (they paid us back)
            $paymentBalanceModifier = $isReturn ? '+' : '-';
            $updateSupplierBalancePaymentSql = "UPDATE tblsuppliers SET 
                                                OutstandingBalance = OutstandingBalance $paymentBalanceModifier $paymentAmount
                                                WHERE ID = $supplierId";
            
            if (!mysqli_query($con, $updateSupplierBalancePaymentSql)) {
                throw new Exception('Error updating supplier balance for payment: ' . mysqli_error($con));
            }
        }
        
        // Commit transaction
        mysqli_commit($con);
        
        $response['success'] = true;
        $response['message'] = ($editingPurchaseId > 0 ? 'Purchase updated' : 'Purchase saved') . ' successfully';
        $response['purchaseId'] = $purchaseId;
        $response['saleId'] = $purchaseId; // For compatibility with frontend JS expecting saleId
        $response['invoiceNumber'] = $invoiceNumber;
        
    } catch (Exception $e) {
        // Rollback transaction
        mysqli_rollback($con);
        $response['message'] = 'Database Error: ' . $e->getMessage();
        $response['debug'] = [
            'invoice' => isset($invoiceNumber) ? $invoiceNumber : 'N/A',
            'supplierId' => isset($supplierId) ? $supplierId : 'N/A',
            'editMode' => isset($editingPurchaseId) ? $editingPurchaseId : 0
        ];
    }
} else {
    $response['message'] = 'Invalid data received or JSON decode failed';
    $response['debug'] = $jsonData;
}

echo json_encode($response);
?>
