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

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

session_start();

// Use the standard config file for database connection
require_once('../../includes/config.php');

// Clean buffer
ob_end_clean();

// Start fresh buffer for JSON
ob_start();

// Set headers
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-cache, must-revalidate');

// Check if user is logged in
if (!isset($_SESSION['uid'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    ob_end_flush();
    exit();
}

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    ob_end_flush();
    exit();
}

$customerId = isset($_POST['customerId']) ? intval($_POST['customerId']) : 0;

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

try {
    // Get outstanding invoices based on PaymentStatus
    // The tblsales table already tracks PaymentAmount and PaymentStatus correctly
    $query = "
        SELECT 
            s.ID as InvoiceID,
            s.InvoiceNumber,
            s.SaleDate as InvoiceDate,
            s.FinalAmount as InvoiceAmount,
            s.PaymentAmount as PaidAmount,
            s.PaymentStatus,
            (s.FinalAmount - s.PaymentAmount) as Outstanding
        FROM tblsales s
        WHERE s.CustomerID = ?
        AND s.PaymentStatus IN ('Unpaid', 'Partial')
        AND (s.FinalAmount - s.PaymentAmount) > 0
        ORDER BY s.SaleDate ASC, s.ID ASC
    ";

    $stmt = mysqli_prepare($con, $query);
    if (!$stmt) {
        throw new Exception('Query preparation failed: ' . mysqli_error($con));
    }

    mysqli_stmt_bind_param($stmt, 'i', $customerId);
    
    if (!mysqli_stmt_execute($stmt)) {
        throw new Exception('Query execution failed: ' . mysqli_stmt_error($stmt));
    }
    
    $result = mysqli_stmt_get_result($stmt);

    $invoices = [];
    while ($row = mysqli_fetch_assoc($result)) {
        $invoices[] = [
            'InvoiceID' => $row['InvoiceID'],
            'InvoiceNumber' => $row['InvoiceNumber'],
            'InvoiceDate' => $row['InvoiceDate'],
            'InvoiceAmount' => number_format($row['InvoiceAmount'], 2, '.', ''),
            'PaidAmount' => number_format($row['PaidAmount'], 2, '.', ''),
            'Outstanding' => number_format($row['Outstanding'], 2, '.', '')
        ];
    }

    mysqli_stmt_close($stmt);

    echo json_encode([
        'success' => true,
        'invoices' => $invoices,
        'count' => count($invoices)
    ]);

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error fetching outstanding invoices: ' . $e->getMessage()
    ]);
}

ob_end_flush();
?>
