<?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 purchase information
    $billQuery = "SELECT p.*, s.SupplierName, s.SupplierCode 
                  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) {
        ob_clean();
        echo json_encode(['success' => false, 'message' => 'Purchase not found']);
        ob_end_flush();
        mysqli_close($con);
        exit();
    }
    
    $bill = mysqli_fetch_assoc($billResult);
    
    // Get purchase items
    $itemsQuery = "SELECT * FROM tblpurchases_details WHERE PurchaseID = $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 supplier account transactions related to this bill
    $invoiceNumber = mysqli_real_escape_string($con, $bill['InvoiceNumber']);
    $accountQuery = "SELECT * FROM tblsupplier_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;
    }
    
    // No loyalty points for purchases
    $loyaltyTransactions = [];
    
    // Get GST details if any
    $gstCount = 0;
    $tablesQuery = "SHOW TABLES LIKE 'tblpurchases_gst_details'";
    $tablesResult = mysqli_query($con, $tablesQuery);
    
    if ($tablesResult && mysqli_num_rows($tablesResult) > 0) {
        $gstQuery = "SELECT COUNT(*) as count FROM tblpurchases_gst_details WHERE PurchaseID = $billId";
        $gstResult = mysqli_query($con, $gstQuery);
        if ($gstResult) {
            $gstRow = mysqli_fetch_assoc($gstResult);
            $gstCount = $gstRow['count'];
        }
    }
    
    // Calculate impact on supplier account
    // For supplier accounts: Credit = we owe them, Debit = we paid them
    $balanceAdjustment = 0;
    foreach ($accountTransactions as $trans) {
        if ($trans['TransactionType'] == 'Credit') {
            $balanceAdjustment -= floatval($trans['Amount']); // Will reduce our liability
        } else {
            $balanceAdjustment += floatval($trans['Amount']); // Will restore our payment
        }
    }
    
    // No loyalty points for purchases
    $pointsAdjustment = 0;
    
    // Clear any buffered output before sending JSON
    ob_clean();
    
    echo json_encode([
        'success' => true,
        'bill' => [
            'id' => $bill['ID'],
            'invoiceNumber' => $bill['InvoiceNumber'],
            'customerName' => $bill['SupplierName'],
            'customerCode' => $bill['SupplierCode'],
            'customerId' => $bill['SupplierID'],
            'saleDate' => $bill['PurchaseDate'],
            'totalAmount' => $bill['FinalAmount'],
            'paidAmount' => $bill['PaymentAmount'],
            'paymentStatus' => $bill['PaymentStatus']
        ],
        'items' => $items,
        'accountTransactions' => $accountTransactions,
        'loyaltyTransactions' => $loyaltyTransactions,
        'counts' => [
            'items' => count($items),
            'accountTransactions' => count($accountTransactions),
            'loyaltyTransactions' => 0,
            'gstRecords' => $gstCount
        ],
        'impact' => [
            'balanceAdjustment' => $balanceAdjustment,
            'pointsAdjustment' => 0
        ]
    ]);
    
} 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);
?>
