<?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 sale ID
$saleId = isset($_POST['saleId']) ? intval($_POST['saleId']) : 0;

if ($saleId <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid sale ID']);
    exit();
}

try {
    // Start transaction
    mysqli_begin_transaction($con);
    
    // Get sale details before deletion
    $saleQuery = "SELECT s.*, c.CurrentBalance 
                  FROM tblsales s 
                  LEFT JOIN tblcustomers c ON s.CustomerID = c.ID 
                  WHERE s.ID = $saleId";
    $saleResult = mysqli_query($con, $saleQuery);
    
    if (!$saleResult || mysqli_num_rows($saleResult) == 0) {
        throw new Exception('Sale not found');
    }
    
    $sale = mysqli_fetch_assoc($saleResult);
    $customerId = $sale['CustomerID'];
    $invoiceNumber = $sale['InvoiceNumber'];
    $salesType = isset($sale['SalesType']) ? $sale['SalesType'] : 'GST';
    $totalAmount = floatval($sale['TotalAmount']);
    $paymentAmount = isset($sale['PaymentAmount']) ? floatval($sale['PaymentAmount']) : 0;
    
    // Determine if this was a return transaction
    $isReturn = (strpos($salesType, '-RETURN') !== false);
    
    // Get sale items to reverse stock
    $itemsQuery = "SELECT ProductID, Quantity FROM tblsales_details WHERE SaleID = $saleId";
    $itemsResult = mysqli_query($con, $itemsQuery);
    $items = [];
    while ($row = mysqli_fetch_assoc($itemsResult)) {
        $items[$row['ProductID']] = floatval($row['Quantity']);
    }
    
    // Reverse stock for all items
    // For SALES deletion: INCREASE stock (goods come back)
    // For RETURN deletion: DECREASE stock (reverse the return, goods go out again)
    foreach ($items as $productId => $quantity) {
        $stockOperation = $isReturn ? '-' : '+';
        $reverseStockSql = "UPDATE tblitems 
                           SET CurrentStock = CurrentStock $stockOperation $quantity 
                           WHERE ID = $productId";
        if (!mysqli_query($con, $reverseStockSql)) {
            throw new Exception('Error reversing stock for product ID ' . $productId . ': ' . mysqli_error($con));
        }
    }
    
    // Reverse loyalty points earned from this sale
    $pointsQuery = "SELECT Points FROM tblcustomer_loyalty_points 
                   WHERE SaleID = $saleId AND CustomerID = $customerId AND TransactionType = 'EARNED'";
    $pointsResult = mysqli_query($con, $pointsQuery);
    if ($pointsResult && mysqli_num_rows($pointsResult) > 0) {
        $pointsRow = mysqli_fetch_assoc($pointsResult);
        $pointsEarned = floatval($pointsRow['Points']);
        
        if ($pointsEarned > 0) {
            // Deduct the earned points from customer
            $reversePointsSql = "UPDATE tblcustomers 
                                SET LoyaltyPoints = LoyaltyPoints - $pointsEarned,
                                    TotalPointsEarned = TotalPointsEarned - $pointsEarned
                                WHERE ID = $customerId";
            mysqli_query($con, $reversePointsSql);
        }
    }
    
    // Reverse points redemption if any
    $redemptionQuery = "SELECT Points FROM tblcustomer_loyalty_points 
                       WHERE SaleID = $saleId AND CustomerID = $customerId AND TransactionType = 'REDEEMED'";
    $redemptionResult = mysqli_query($con, $redemptionQuery);
    if ($redemptionResult && mysqli_num_rows($redemptionResult) > 0) {
        $redemptionRow = mysqli_fetch_assoc($redemptionResult);
        $pointsRedeemed = floatval($redemptionRow['Points']);
        
        if ($pointsRedeemed > 0) {
            // Add back the redeemed points to customer
            $reverseRedemptionSql = "UPDATE tblcustomers 
                                    SET LoyaltyPoints = LoyaltyPoints + $pointsRedeemed,
                                        TotalPointsRedeemed = TotalPointsRedeemed - $pointsRedeemed
                                    WHERE ID = $customerId";
            mysqli_query($con, $reverseRedemptionSql);
        }
    }
    
    // Delete loyalty points transactions
    $deletePointsSql = "DELETE FROM tblcustomer_loyalty_points WHERE SaleID = $saleId AND CustomerID = $customerId";
    mysqli_query($con, $deletePointsSql);
    
    // Delete GST details if exists
    $deleteGSTSql = "DELETE FROM tblsales_gst_details WHERE SaleID = $saleId";
    mysqli_query($con, $deleteGSTSql);
    
    // Delete sale details
    $deleteDetailsSql = "DELETE FROM tblsales_details WHERE SaleID = $saleId";
    if (!mysqli_query($con, $deleteDetailsSql)) {
        throw new Exception('Error deleting sale details: ' . mysqli_error($con));
    }
    
    // Delete customer account entries (both sale entry and payment if any)
    // Delete main sale entry (பற்று)
    $deleteAccountSql = "DELETE FROM tblcustomer_accounts 
                         WHERE InvoiceNumber = '$invoiceNumber' AND CustomerID = $customerId";
    if (!mysqli_query($con, $deleteAccountSql)) {
        throw new Exception('Error deleting customer account: ' . mysqli_error($con));
    }
    
    // Delete payment entry if exists (வரவு)
    $paymentRef = 'PAY-' . $invoiceNumber;
    $deletePaymentSql = "DELETE FROM tblcustomer_accounts 
                         WHERE InvoiceNumber = '$paymentRef' AND CustomerID = $customerId";
    mysqli_query($con, $deletePaymentSql); // Don't throw error if no payment exists
    
    // Adjust customer balance
    // For SALES deletion: Reverse the sale entry (Debit) - subtract the amount
    //                     Reverse the payment entry (Credit) - add back the payment
    // For RETURN deletion: Reverse the return entry (Credit) - add the amount
    //                      Reverse the payment entry (Debit) - subtract the payment
    
    if ($isReturn) {
        // Return was Credit to customer, reverse it by adding back
        $balanceAdjustment = $totalAmount - $paymentAmount;
    } else {
        // Sale was Debit to customer, reverse it by subtracting
        $balanceAdjustment = -$totalAmount + $paymentAmount;
    }
    
    $updateBalanceSql = "UPDATE tblcustomers 
                         SET CurrentBalance = CurrentBalance + $balanceAdjustment 
                         WHERE ID = $customerId";
    
    if (!mysqli_query($con, $updateBalanceSql)) {
        throw new Exception('Error updating customer balance: ' . mysqli_error($con));
    }
    
    // Delete sale master record
    $deleteSaleSql = "DELETE FROM tblsales WHERE ID = $saleId";
    if (!mysqli_query($con, $deleteSaleSql)) {
        throw new Exception('Error deleting sale: ' . mysqli_error($con));
    }
    
    // Commit transaction
    mysqli_commit($con);
    
    $response['success'] = true;
    $response['message'] = 'Sale deleted successfully';
    $response['invoiceNumber'] = $invoiceNumber;
    
} catch (Exception $e) {
    // Rollback transaction
    mysqli_rollback($con);
    $response['message'] = 'Error: ' . $e->getMessage();
}

echo json_encode($response);
?>
