<?php
/**
 * API: Delete Bill
 * Permanently deletes a bill and all related data
 */

// Start output buffering to catch any stray output
ob_start();

session_start();

// Suppress errors for clean JSON output
define('SUPPRESS_ERRORS', true);

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

// Check if database connection exists
if (!isset($con) || !$con) {
    ob_clean();
    echo json_encode(['success' => false, 'message' => 'Database connection failed']);
    ob_end_flush();
    exit();
}

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

// Get POST data
$data = json_decode(file_get_contents('php://input'), true);
$billId = isset($data['billId']) ? intval($data['billId']) : 0;
$confirmation = isset($data['confirmation']) ? trim($data['confirmation']) : '';

if ($billId <= 0) {
    ob_clean();
    echo json_encode(['success' => false, 'message' => 'Invalid bill ID']);
    ob_end_flush();
    exit();
}

if ($confirmation !== 'DELETE') {
    ob_clean();
    echo json_encode(['success' => false, 'message' => 'Confirmation text does not match']);
    ob_end_flush();
    exit();
}

try {
    // Start transaction
    mysqli_begin_transaction($con);
    
    // Get bill information first
    $billQuery = "SELECT s.*, c.CustomerName 
                  FROM tblsales s 
                  LEFT JOIN tblcustomers c ON s.CustomerID = c.ID 
                  WHERE s.ID = $billId";
    $billResult = mysqli_query($con, $billQuery);
    
    if (!$billResult) {
        throw new Exception('Query failed: ' . mysqli_error($con));
    }
    
    if (mysqli_num_rows($billResult) == 0) {
        throw new Exception('Bill not found');
    }
    
    $bill = mysqli_fetch_assoc($billResult);
    $customerId = $bill['CustomerID'];
    $salesType = isset($bill['SalesType']) ? $bill['SalesType'] : '';
    $isQuotation = strcasecmp($salesType, 'QUOTATION') === 0;
    $invoiceNumber = mysqli_real_escape_string($con, $bill['InvoiceNumber']);
    $totalAmount = floatval($bill['FinalAmount']);
    
    // ========== 1. DELETE SALE DETAILS ==========
    $deleteSaleDetailsQuery = "DELETE FROM tblsales_details WHERE SaleID = $billId";
    if (!mysqli_query($con, $deleteSaleDetailsQuery)) {
        throw new Exception('Error deleting sale details: ' . mysqli_error($con));
    }
    $deletedItems = mysqli_affected_rows($con);
    
    // ========== 2. DELETE GST DETAILS ==========
    // Check if table exists first
    $tablesQuery = "SHOW TABLES LIKE 'tblsales_gst_details'";
    $tablesResult = mysqli_query($con, $tablesQuery);
    $deletedGST = 0;
    
    if ($tablesResult && mysqli_num_rows($tablesResult) > 0) {
        $deleteGSTQuery = "DELETE FROM tblsales_gst_details WHERE SaleID = $billId";
        if (!mysqli_query($con, $deleteGSTQuery)) {
            throw new Exception('Error deleting GST details: ' . mysqli_error($con));
        }
        $deletedGST = mysqli_affected_rows($con);
    }
    
    // ========== 3. REVERSE CUSTOMER ACCOUNT TRANSACTIONS ==========
    // Get all account transactions for this bill
    $balanceAdjustment = 0;
    $deletedAccountRecords = 0;

    if (!$isQuotation) {
        $accountQuery = "SELECT * FROM tblcustomer_accounts 
                         WHERE (InvoiceNumber = '$invoiceNumber' 
                                OR InvoiceNumber LIKE 'PAY-$invoiceNumber%')
                         ORDER BY ID";
        $accountResult = mysqli_query($con, $accountQuery);

        while ($accountResult && $trans = mysqli_fetch_assoc($accountResult)) {
            $transAmount = floatval($trans['Amount']);

            if ($trans['TransactionType'] == 'Debit') {
                $balanceAdjustment -= $transAmount;
            } else {
                $balanceAdjustment += $transAmount;
            }

            $deletedAccountRecords++;
        }

        $deleteAccountQuery = "DELETE FROM tblcustomer_accounts 
                               WHERE (InvoiceNumber = '$invoiceNumber' 
                                      OR InvoiceNumber LIKE 'PAY-$invoiceNumber%')";
        if (!mysqli_query($con, $deleteAccountQuery)) {
            throw new Exception('Error deleting account transactions: ' . mysqli_error($con));
        }

        if ($balanceAdjustment != 0) {
            $updateBalanceQuery = "UPDATE tblcustomers 
                                   SET CurrentBalance = CurrentBalance + ($balanceAdjustment) 
                                   WHERE ID = $customerId";
            if (!mysqli_query($con, $updateBalanceQuery)) {
                throw new Exception('Error updating customer balance: ' . mysqli_error($con));
            }
        }
    }
    
    // ========== 4. REVERSE LOYALTY POINTS ==========
    // Get loyalty transactions for this bill
    $pointsAdjustment = 0;
    $deletedLoyaltyRecords = 0;

    if (!$isQuotation) {
        $loyaltyQuery = "SELECT * FROM tblcustomer_loyalty_points WHERE SaleID = $billId";
        $loyaltyResult = mysqli_query($con, $loyaltyQuery);

        while ($loyaltyResult && $trans = mysqli_fetch_assoc($loyaltyResult)) {
            $points = floatval($trans['Points']);

            if ($trans['TransactionType'] == 'EARNED') {
                $pointsAdjustment -= $points;
            } else if ($trans['TransactionType'] == 'REDEEMED') {
                $pointsAdjustment += $points;
            }

            $deletedLoyaltyRecords++;
        }

        $deleteLoyaltyQuery = "DELETE FROM tblcustomer_loyalty_points WHERE SaleID = $billId";
        if (!mysqli_query($con, $deleteLoyaltyQuery)) {
            throw new Exception('Error deleting loyalty transactions: ' . mysqli_error($con));
        }

        if ($pointsAdjustment != 0) {
            $updatePointsQuery = "UPDATE tblcustomers 
                                  SET LoyaltyPoints = LoyaltyPoints + ($pointsAdjustment)";

            $earnedAdjustment = 0;
            $redeemedAdjustment = 0;

            if ($loyaltyResult) {
                mysqli_data_seek($loyaltyResult, 0);
                while ($trans = mysqli_fetch_assoc($loyaltyResult)) {
                    $points = floatval($trans['Points']);
                    if ($trans['TransactionType'] == 'EARNED') {
                        $earnedAdjustment -= $points;
                    } else if ($trans['TransactionType'] == 'REDEEMED') {
                        $redeemedAdjustment -= $points;
                    }
                }
            }

            if ($earnedAdjustment != 0) {
                $updatePointsQuery .= ", TotalPointsEarned = TotalPointsEarned + ($earnedAdjustment)";
            }

            if ($redeemedAdjustment != 0) {
                $updatePointsQuery .= ", TotalPointsRedeemed = TotalPointsRedeemed + ($redeemedAdjustment)";
            }

            $updatePointsQuery .= " WHERE ID = $customerId";

            if (!mysqli_query($con, $updatePointsQuery)) {
                throw new Exception('Error updating customer loyalty points: ' . mysqli_error($con));
            }
        }
    }
    
    // ========== 5. DELETE SALE MASTER RECORD ==========
    $deleteSaleQuery = "DELETE FROM tblsales WHERE ID = $billId";
    if (!mysqli_query($con, $deleteSaleQuery)) {
        throw new Exception('Error deleting sale record: ' . mysqli_error($con));
    }
    
    // Commit transaction
    mysqli_commit($con);
    
    // Clear any buffered output before sending JSON
    ob_clean();
    
    echo json_encode([
        'success' => true,
        'message' => 'Bill deleted successfully',
        'deletedRecords' => [
            'saleItems' => $deletedItems,
            'gstRecords' => $deletedGST,
            'accountTransactions' => $deletedAccountRecords,
            'loyaltyTransactions' => $deletedLoyaltyRecords
        ],
        'customerAdjustments' => [
            'balanceChange' => $balanceAdjustment,
            'pointsChange' => $pointsAdjustment
        ],
        'deletedBill' => [
            'invoiceNumber' => $invoiceNumber,
            'customerName' => $bill['CustomerName'],
            'amount' => $totalAmount
        ]
    ]);
    
} catch (Exception $e) {
    // Rollback on error
    mysqli_rollback($con);
    
    // Clear any buffered output
    ob_clean();
    
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}

// Clear buffer and send output
ob_end_flush();
mysqli_close($con);
?>
