<?php
/**
 * API: Get Bill Delete Details
 * Retrieves all related data for a bill before deletion
 */

// 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();
}

$billId = isset($_GET['billId']) ? intval($_GET['billId']) : 0;

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

try {
    // Get bill information
    $billQuery = "SELECT s.*, c.CustomerName, c.CustomerCode 
                  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) {
        ob_clean();
        echo json_encode(['success' => false, 'message' => 'Bill not found']);
        ob_end_flush();
        mysqli_close($con);
        exit();
    }
    
    $bill = mysqli_fetch_assoc($billResult);
    
    // Get bill items
    $itemsQuery = "SELECT * FROM tblsales_details WHERE SaleID = $billId ORDER BY ID";
    $itemsResult = mysqli_query($con, $itemsQuery);
    
    if (!$itemsResult) {
        throw new Exception('Error fetching items: ' . mysqli_error($con));
    }
    
    $items = [];
    while ($row = mysqli_fetch_assoc($itemsResult)) {
        $items[] = $row;
    }
    
    // Get customer account transactions related to this bill
    $invoiceNumber = mysqli_real_escape_string($con, $bill['InvoiceNumber']);
    $accountQuery = "SELECT * FROM tblcustomer_accounts 
                     WHERE (InvoiceNumber = '$invoiceNumber' 
                            OR InvoiceNumber LIKE 'PAY-$invoiceNumber%')
                     ORDER BY TransactionDate, ID";
    $accountResult = mysqli_query($con, $accountQuery);
    
    if (!$accountResult) {
        throw new Exception('Error fetching account transactions: ' . mysqli_error($con));
    }
    
    $accountTransactions = [];
    while ($row = mysqli_fetch_assoc($accountResult)) {
        $accountTransactions[] = $row;
    }
    
    // Get loyalty points transactions related to this bill
    $loyaltyQuery = "SELECT * FROM tblcustomer_loyalty_points 
                     WHERE SaleID = $billId 
                     ORDER BY TransactionDate";
    $loyaltyResult = mysqli_query($con, $loyaltyQuery);
    
    if (!$loyaltyResult) {
        throw new Exception('Error fetching loyalty transactions: ' . mysqli_error($con));
    }
    
    $loyaltyTransactions = [];
    while ($row = mysqli_fetch_assoc($loyaltyResult)) {
        $loyaltyTransactions[] = $row;
    }
    
    // Get GST details if any - check if table exists first
    $gstCount = 0;
    $tablesQuery = "SHOW TABLES LIKE 'tblsales_gst_details'";
    $tablesResult = mysqli_query($con, $tablesQuery);
    
    if ($tablesResult && mysqli_num_rows($tablesResult) > 0) {
        $gstQuery = "SELECT COUNT(*) as count FROM tblsales_gst_details WHERE SaleID = $billId";
        $gstResult = mysqli_query($con, $gstQuery);
        if ($gstResult) {
            $gstRow = mysqli_fetch_assoc($gstResult);
            $gstCount = $gstRow['count'];
        }
    }
    
    // Calculate impact on customer balance
    $balanceAdjustment = 0;
    foreach ($accountTransactions as $trans) {
        if ($trans['TransactionType'] == 'Debit') {
            $balanceAdjustment -= floatval($trans['Amount']); // Will reduce balance
        } else {
            $balanceAdjustment += floatval($trans['Amount']); // Will increase balance
        }
    }
    
    // Calculate impact on loyalty points
    $pointsAdjustment = 0;
    foreach ($loyaltyTransactions as $trans) {
        if ($trans['TransactionType'] == 'EARNED') {
            $pointsAdjustment -= floatval($trans['Points']); // Will reduce points
        } else if ($trans['TransactionType'] == 'REDEEMED') {
            $pointsAdjustment += floatval($trans['Points']); // Will restore points
        }
    }
    
    // Clear any buffered output before sending JSON
    ob_clean();
    
    echo json_encode([
        'success' => true,
        'bill' => [
            'id' => $bill['ID'],
            'invoiceNumber' => $bill['InvoiceNumber'],
            'customerName' => $bill['CustomerName'],
            'customerCode' => $bill['CustomerCode'],
            'customerId' => $bill['CustomerID'],
            'saleDate' => $bill['SaleDate'],
            'totalAmount' => $bill['FinalAmount'],
            'paidAmount' => $bill['PaymentAmount'],
            'paymentStatus' => $bill['PaymentStatus']
        ],
        'items' => $items,
        'accountTransactions' => $accountTransactions,
        'loyaltyTransactions' => $loyaltyTransactions,
        'counts' => [
            'items' => count($items),
            'accountTransactions' => count($accountTransactions),
            'loyaltyTransactions' => count($loyaltyTransactions),
            'gstRecords' => $gstCount
        ],
        'impact' => [
            'balanceAdjustment' => $balanceAdjustment,
            'pointsAdjustment' => $pointsAdjustment
        ]
    ]);
    
} catch (Exception $e) {
    // Clear any output
    ob_clean();
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}

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