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

if (!hasPermission('master_sales')) { http_response_code(403); exit; }

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

$master_id = (int)($_GET['master_id'] ?? 0);
if ($master_id <= 0) { echo json_encode([]); exit; }

$res = $conn->query("
    SELECT si.id, si.invoice_no, si.gross_total, si.round_off,
           si.overall_discount_type, si.overall_discount_value,
           si.net_total, si.received_amount, si.balance_amount,
           cm.company_name
    FROM sales_invoices si
    JOIN company_master cm ON cm.id = si.company_id
    WHERE si.master_invoice_id = $master_id
    ORDER BY si.id ASC
");

$invoices = [];
while ($r = $res->fetch_assoc()) $invoices[] = $r;
echo json_encode($invoices);
