<?php
require_once '../includes/auth.php';
require_once '../db.php';

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

$inv_id = (int)($_GET['inv_id'] ?? 0);
if ($inv_id <= 0) { echo json_encode(['error' => 'Invalid invoice']); exit; }

/* Invoice header */
$inv = $conn->query("
    SELECT si.invoice_no, si.invoice_date,
           si.gross_total, si.overall_discount_type, si.overall_discount_value,
           si.total_gst, si.net_total, si.received_amount, si.balance_amount,
           COALESCE(cl.name, '—') AS customer_name,
           cl.phone AS customer_phone
    FROM sales_invoices si
    LEFT JOIN clients cl ON cl.id = si.client_id
    WHERE si.id = $inv_id AND si.status = 'final'
    LIMIT 1
")->fetch_assoc();

if (!$inv) { echo json_encode(['error' => 'Invoice not found']); exit; }

/* Line items */
$itemsRes = $conn->query("
    SELECT
        p.name AS product_name,
        sit.batch_no,
        sit.description,
        sit.sold_qty,
        sit.selling_price_excl,
        sit.selling_price_incl,
        sit.discount_type,
        sit.discount_value,
        sit.gst_percent,
        sit.taxable_amount,
        sit.gst_amount,
        sit.total_amount
    FROM sales_items sit
    JOIN products p ON p.id = sit.product_id
    WHERE sit.sales_invoice_id = $inv_id
    ORDER BY sit.id ASC
");

$items = [];
while ($item = $itemsRes->fetch_assoc()) $items[] = $item;

echo json_encode([
    'invoice' => [
        'invoice_no'             => $inv['invoice_no'],
        'invoice_date'           => date('d-m-Y', strtotime($inv['invoice_date'])),
        'customer_name'          => $inv['customer_name'],
        'customer_phone'         => $inv['customer_phone'] ?? '',
        'gross_total'            => (float)$inv['gross_total'],
        'overall_discount_type'  => $inv['overall_discount_type'],
        'overall_discount_value' => (float)$inv['overall_discount_value'],
        'total_gst'              => (float)$inv['total_gst'],
        'net_total'              => (float)$inv['net_total'],
        'received_amount'        => (float)$inv['received_amount'],
        'balance_amount'         => (float)$inv['balance_amount'],
    ],
    'items' => $items,
]);
