<?php
include 'includes/config.php';

header('Content-Type: application/json');

if (isset($_GET['customer_id']) && isset($_GET['invoice_no'])) {
    $customerId = $_GET['customer_id'];
    $invoiceNo = $_GET['invoice_no'];

    try {
        $query = "
            SELECT 
                s.product_name,
                s.sale_qty AS quantity,
                s.price AS unit_price,
                IFNULL(s.discount, 0) AS discount,
                IFNULL(s.order_tax, 0) AS tax,
                s.total_amount AS price_inc_tax,
                (s.sale_qty * s.price) AS subtotal,
                s.net_cash,
                s.date_sale
            FROM 
                stock_sale s
            WHERE 
                s.customer_id = :customer_id AND s.invoice = :invoice_no
        ";

        $stmt = $conn->prepare($query);
        $stmt->bindParam(':customer_id', $customerId, PDO::PARAM_INT);
        $stmt->bindParam(':invoice_no', $invoiceNo, PDO::PARAM_STR);
        $stmt->execute();
        $details = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $totalSubtotal = 0;
        $totalDiscount = 0;
        $totalTax = 0;
        $totalNetCash = 0;

        foreach ($details as $item) {
            $totalSubtotal += $item['subtotal'];
            $totalDiscount += $item['discount'];
            $totalTax += $item['tax'];
            $totalNetCash += $item['net_cash'];
        }

        $response = [
            'details' => $details,
            'totalSubtotal' => $totalSubtotal,
            'totalDiscount' => $totalDiscount,
            'totalTax' => $totalTax,
            'totalNetCash' => $totalNetCash,
            'grandTotal' => $totalSubtotal - $totalNetCash,
        ];

        echo json_encode($response);

    } catch (Exception $e) {
        echo json_encode(['error' => 'An error occurred: ' . $e->getMessage()]);
    }
} else {
    echo json_encode(['error' => 'Invalid parameters']);
}
?>
