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

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) die('Invalid ID');

$master = $conn->query("
    SELECT mi.*, c.name AS client_name, c.phone AS client_phone, c.address AS client_address
    FROM master_invoices mi
    JOIN clients c ON c.id = mi.client_id
    WHERE mi.id = $id
")->fetch_assoc();
if (!$master) die('Master invoice not found.');

$totals = $conn->query("
    SELECT SUM(net_total) AS grand_total, SUM(received_amount) AS grand_received, SUM(balance_amount) AS grand_balance
    FROM sales_invoices WHERE master_invoice_id = $id
")->fetch_assoc();

// All items across all companies
$items = $conn->query("
    SELECT s.*, p.name AS product_name, p.unit, cm.company_name
    FROM sales_invoices si
    JOIN sales_items s  ON s.sales_invoice_id = si.id
    JOIN products p     ON p.id  = s.product_id
    JOIN company_master cm ON cm.id = si.company_id
    WHERE si.master_invoice_id = $id
    ORDER BY cm.id ASC, s.id ASC
");

$statusColor = $master['status'] === 'final' ? '#10b981' : '#f59e0b';

// Group items by company
$grouped = [];
while ($row = $items->fetch_assoc()) {
    $grouped[$row['company_name']][] = $row;
}
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: Inter, sans-serif; font-size: 13px; color: #1e293b; padding: 20px; background: #fff; }
.header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 18px; gap: 12px; }
.inv-no { font-size: 20px; font-weight: 700; color: #1e293b; }
.muted { color: #64748b; font-size: 12px; margin-top: 3px; }
.badge { display: inline-block; padding: 2px 10px; border-radius: 20px; font-size: 11px; font-weight: 600; }
.co-header { background: #eff6ff; padding: 6px 10px; font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: .05em; color: #2563eb; margin: 14px 0 0; border-left: 3px solid #2563eb; }
table { width: 100%; border-collapse: collapse; }
thead th { background: #f8fafc; text-transform: uppercase; font-size: 11px; letter-spacing: .4px; padding: 7px 10px; text-align: left; color: #475569; border-bottom: 1px solid #e2e8f0; }
tbody td { padding: 7px 10px; border-bottom: 1px solid #f8fafc; }
tbody tr:last-child td { border-bottom: none; }
.totals-table { width: 240px; margin-left: auto; margin-top: 16px; }
.totals-table td { padding: 5px 8px; }
.totals-table .label { color: #64748b; }
.totals-table .grand td { font-weight: 700; font-size: 14px; border-top: 2px solid #e2e8f0; padding-top: 8px; }
</style>
</head>
<body>

<div class="header">
    <div>
        <div class="inv-no"><?= htmlspecialchars($master['master_no']) ?></div>
        <div class="muted"><?= date('d M Y', strtotime($master['invoice_date'])) ?></div>
        <div class="muted" style="margin-top:2px;"><i>Master Invoice</i></div>
    </div>
    <div style="text-align:right;">
        <div style="font-weight:600;"><?= htmlspecialchars($master['client_name']) ?></div>
        <?php if ($master['client_phone']): ?>
        <div class="muted"><?= htmlspecialchars($master['client_phone']) ?></div>
        <?php endif; ?>
        <div style="margin-top:6px;">
            <span class="badge" style="background:<?= $statusColor ?>22;color:<?= $statusColor ?>;"><?= ucfirst($master['status']) ?></span>
        </div>
    </div>
</div>

<?php foreach ($grouped as $companyName => $rows): ?>
<div class="co-header"><?= htmlspecialchars($companyName) ?></div>
<table>
    <thead>
        <tr>
            <th>#</th>
            <th>Product</th>
            <th>Batch</th>
            <th style="text-align:right;">Qty</th>
            <th style="text-align:right;">Rate (incl.)</th>
            <th style="text-align:right;">Total</th>
        </tr>
    </thead>
    <tbody>
    <?php $i = 1; foreach ($rows as $item): ?>
    <tr>
        <td style="color:#94a3b8;"><?= $i++ ?></td>
        <td>
            <strong><?= htmlspecialchars($item['product_name']) ?></strong>
            <?php if ($item['unit']): ?><span style="font-size:11px;color:#94a3b8;margin-left:4px;"><?= htmlspecialchars($item['unit']) ?></span><?php endif; ?>
            <?php if ($item['description']): ?><div style="font-size:11px;color:#64748b;"><?= htmlspecialchars($item['description']) ?></div><?php endif; ?>
        </td>
        <td style="font-size:11px;color:#64748b;"><?= htmlspecialchars($item['batch_no']) ?></td>
        <td style="text-align:right;"><?= number_format($item['sold_qty'], 0) ?></td>
        <td style="text-align:right;">&#8377;&nbsp;<?= number_format($item['selling_price_incl'], 2) ?></td>
        <td style="text-align:right;font-weight:600;">&#8377;&nbsp;<?= number_format($item['total_amount'], 2) ?></td>
    </tr>
    <?php endforeach; ?>
    </tbody>
</table>
<?php endforeach; ?>

<table class="totals-table">
    <tr>
        <td class="label">Grand Total</td>
        <td style="text-align:right;">&#8377;&nbsp;<?= number_format($totals['grand_total'], 2) ?></td>
    </tr>
    <tr class="grand">
        <td>Net Payable</td>
        <td style="text-align:right;">&#8377;&nbsp;<?= number_format($totals['grand_total'], 2) ?></td>
    </tr>
    <?php if ($totals['grand_received'] > 0): ?>
    <tr>
        <td class="label">Received</td>
        <td style="text-align:right;color:#10b981;">&#8377;&nbsp;<?= number_format($totals['grand_received'], 2) ?></td>
    </tr>
    <tr>
        <td class="label">Balance</td>
        <td style="text-align:right;color:<?= $totals['grand_balance'] > 0 ? '#ef4444' : '#10b981' ?>;">
            &#8377;&nbsp;<?= number_format($totals['grand_balance'], 2) ?>
        </td>
    </tr>
    <?php endif; ?>
</table>

</body>
</html>
