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

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

$response = ['success' => false, 'message' => ''];

// Get supplier ID from POST data
$supplierId = isset($_POST['supplierId']) ? intval($_POST['supplierId']) : 0;

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

try {
    // Get outstanding purchase invoices for the supplier
    // We need to calculate outstanding as: FinalAmount - PaymentAmount
    $query = "SELECT 
                p.ID as InvoiceID,
                p.InvoiceNumber,
                p.PurchaseDate as InvoiceDate,
                p.FinalAmount as InvoiceAmount,
                p.PaymentAmount as PaidAmount,
                (p.FinalAmount - p.PaymentAmount) as Outstanding,
                p.PaymentStatus
              FROM tblpurchases p
              WHERE p.SupplierID = $supplierId
              AND (p.FinalAmount - p.PaymentAmount) > 0
              ORDER BY p.PurchaseDate ASC, p.ID ASC";
    
    $result = mysqli_query($con, $query);
    
    if ($result) {
        $invoices = [];
        while ($row = mysqli_fetch_assoc($result)) {
            $invoices[] = [
                'InvoiceID' => $row['InvoiceID'],
                'InvoiceNumber' => $row['InvoiceNumber'],
                'InvoiceDate' => $row['InvoiceDate'],
                'InvoiceAmount' => floatval($row['InvoiceAmount']),
                'PaidAmount' => floatval($row['PaidAmount']),
                'Outstanding' => floatval($row['Outstanding']),
                'PaymentStatus' => $row['PaymentStatus']
            ];
        }
        
        $response['success'] = true;
        $response['invoices'] = $invoices;
        $response['count'] = count($invoices);
        
        if (count($invoices) == 0) {
            $response['message'] = 'No outstanding invoices found for this supplier';
        }
    } else {
        $response['message'] = 'Database error: ' . mysqli_error($con);
    }
    
} catch (Exception $e) {
    $response['message'] = 'Error: ' . $e->getMessage();
}

echo json_encode($response);
?>
