<?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 purchase information first
    $billQuery = "SELECT p.*, s.SupplierName 
                  FROM tblpurchases p 
                  LEFT JOIN tblsuppliers s ON p.SupplierID = s.ID 
                  WHERE p.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('Purchase not found');
    }
    
    $bill = mysqli_fetch_assoc($billResult);
    $supplierId = $bill['SupplierID'];
    $invoiceNumber = mysqli_real_escape_string($con, $bill['InvoiceNumber']);
    $totalAmount = floatval($bill['FinalAmount']);
    
    // ========== 1. REVERSE STOCK FOR PURCHASE ITEMS ==========
    $itemsQuery = "SELECT ProductID, Quantity FROM tblpurchases_details WHERE PurchaseID = $billId";
    $itemsResult = mysqli_query($con, $itemsQuery);
    
    if (!$itemsResult) {
        throw new Exception('Error fetching items: ' . mysqli_error($con));
    }
    
    // Decrease stock because we're removing a purchase
    while ($item = mysqli_fetch_assoc($itemsResult)) {
        $productId = intval($item['ProductID']);
        $quantity = floatval($item['Quantity']);
        
        if ($productId > 0 && $quantity > 0) {
            $updateStockQuery = "UPDATE tblitems 
                                SET CurrentStock = CurrentStock - $quantity 
                                WHERE ID = $productId";
            if (!mysqli_query($con, $updateStockQuery)) {
                throw new Exception('Error updating stock for product ID ' . $productId . ': ' . mysqli_error($con));
            }
        }
    }
    
    // ========== 2. DELETE PURCHASE DETAILS ==========
    $deletePurchaseDetailsQuery = "DELETE FROM tblpurchases_details WHERE PurchaseID = $billId";
    if (!mysqli_query($con, $deletePurchaseDetailsQuery)) {
        throw new Exception('Error deleting purchase details: ' . mysqli_error($con));
    }
    $deletedItems = mysqli_affected_rows($con);
    
    // ========== 3. DELETE GST DETAILS ==========
    $tablesQuery = "SHOW TABLES LIKE 'tblpurchases_gst_details'";
    $tablesResult = mysqli_query($con, $tablesQuery);
    $deletedGST = 0;
    
    if ($tablesResult && mysqli_num_rows($tablesResult) > 0) {
        $deleteGSTQuery = "DELETE FROM tblpurchases_gst_details WHERE PurchaseID = $billId";
        if (!mysqli_query($con, $deleteGSTQuery)) {
            throw new Exception('Error deleting GST details: ' . mysqli_error($con));
        }
        $deletedGST = mysqli_affected_rows($con);
    }
    
    // ========== 4. DELETE SUPPLIER ACCOUNT TRANSACTIONS ==========
    // Delete all account transactions for this bill
    $deleteAccountQuery = "DELETE FROM tblsupplier_accounts 
                           WHERE (InvoiceNumber = '$invoiceNumber' 
                                  OR InvoiceNumber LIKE 'PAY-$invoiceNumber%')";
    if (!mysqli_query($con, $deleteAccountQuery)) {
        throw new Exception('Error deleting account transactions: ' . mysqli_error($con));
    }
    $deletedAccountRecords = mysqli_affected_rows($con);
    
    // ========== 5. DELETE PURCHASE MASTER RECORD ==========
    $deletePurchaseQuery = "DELETE FROM tblpurchases WHERE ID = $billId";
    if (!mysqli_query($con, $deletePurchaseQuery)) {
        throw new Exception('Error deleting purchase record: ' . mysqli_error($con));
    }
    
    // Commit transaction
    mysqli_commit($con);
    
    // Clear any buffered output before sending JSON
    ob_clean();
    
    echo json_encode([
        'success' => true,
        'message' => 'Purchase deleted successfully',
        'deletedRecords' => [
            'saleItems' => $deletedItems,
            'gstRecords' => $deletedGST,
            'accountTransactions' => $deletedAccountRecords,
            'loyaltyTransactions' => 0
        ],
        'customerAdjustments' => [
            'balanceChange' => 0,
            'pointsChange' => 0
        ],
        'deletedBill' => [
            'invoiceNumber' => $invoiceNumber,
            'customerName' => $bill['SupplierName'],
            '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);
?>
