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

requirePermission('master_sales', 'view', BASE_URL . '/dashboard.php');

require_once '../includes/header.php';
require_once '../includes/sidebar.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();

// Load all split invoices linked to this master
$invoices = $conn->query("
    SELECT si.*, cm.company_name, cm.invoice_prefix
    FROM sales_invoices si
    JOIN company_master cm ON cm.id = si.company_id
    WHERE si.master_invoice_id = $id
    ORDER BY si.id ASC
");

$statusBadge = $master['status'] === 'final'
    ? '<span class="badge badge-success">Final</span>'
    : '<span class="badge badge-warning">Draft</span>';
?>

<div class="page-header">
    <h2><i class="fas fa-layer-group" style="color:var(--primary);margin-right:8px;"></i>Master Invoice</h2>
    <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
        <label style="display:flex;align-items:center;gap:6px;font-size:13px;font-weight:600;color:var(--text-secondary);">
            Template:
            <select id="printTemplate" class="btn btn-secondary btn-sm" style="padding:5px 8px;font-weight:500;">
                <option value="simple">Simple</option>
                <option value="tally">Tally</option>
                <option value="modern">Modern</option>
            </select>
        </label>
        <?php if ($master['status'] === 'draft'): ?>
        <a href="edit.php?id=<?= $id ?>" class="btn btn-primary">
            <i class="fas fa-edit"></i> Edit
        </a>
        <a href="delete.php?id=<?= $id ?>" class="btn btn-danger"
           onclick="return confirm('Delete this draft master invoice and all its sub-invoices?')">
            <i class="fas fa-trash"></i> Delete
        </a>
        <?php endif; ?>
        <?php if ($master['status'] === 'final'): ?>
        <a href="../master_returns/create_master.php?master_id=<?= $id ?>" class="btn btn-secondary">
            <i class="fas fa-rotate-left"></i> Return
        </a>
        <?php endif; ?>
        <?php if (!empty($master['client_phone'])): ?>
        <button onclick="sendWhatsApp()" class="btn btn-success" style="background:#25d366;border-color:#25d366;">
            <i class="fab fa-whatsapp"></i> WhatsApp
        </button>
        <?php endif; ?>
        <a href="index.php" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Back</a>
    </div>
</div>

<!-- Master Header -->
<div class="panel" style="margin-bottom:16px;">
    <div class="panel-body">
        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:16px;">
            <div>
                <div style="font-size:11px;font-weight:700;text-transform:uppercase;color:var(--text-muted);margin-bottom:4px;">Master Ref</div>
                <div style="font-size:16px;font-weight:700;"><?= htmlspecialchars($master['master_no']) ?></div>
            </div>
            <div>
                <div style="font-size:11px;font-weight:700;text-transform:uppercase;color:var(--text-muted);margin-bottom:4px;">Date</div>
                <div style="font-size:15px;"><?= date('d M Y', strtotime($master['invoice_date'])) ?></div>
            </div>
            <div>
                <div style="font-size:11px;font-weight:700;text-transform:uppercase;color:var(--text-muted);margin-bottom:4px;">Client</div>
                <div style="font-size:15px;font-weight:700;"><?= htmlspecialchars($master['client_name']) ?></div>
                <?php if ($master['client_phone']): ?><div style="font-size:12px;color:var(--text-muted);"><?= htmlspecialchars($master['client_phone']) ?></div><?php endif; ?>
            </div>
            <div>
                <div style="font-size:11px;font-weight:700;text-transform:uppercase;color:var(--text-muted);margin-bottom:4px;">Status</div>
                <div><?= $statusBadge ?></div>
            </div>
        </div>
    </div>
</div>

<!-- Per-company invoices -->
<?php
$grandNetTotal = 0;
$invoiceRows = [];
while ($inv = $invoices->fetch_assoc()) $invoiceRows[] = $inv;
foreach ($invoiceRows as $inv):
    $grandNetTotal += $inv['net_total'];
    $items = $conn->query("
        SELECT si.*, p.name AS product_name, p.unit
        FROM sales_items si
        JOIN products p ON p.id = si.product_id
        WHERE si.sales_invoice_id = {$inv['id']}
    ");
?>
<div class="panel" style="margin-bottom:16px;border-left:4px solid var(--primary);">
    <div class="panel-header" style="flex-wrap:wrap;gap:8px;">
        <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;">
            <span class="panel-title" style="font-size:15px;"><?= htmlspecialchars($inv['company_name']) ?></span>
            <span style="font-size:13px;color:var(--text-secondary);"><?= htmlspecialchars($inv['invoice_no']) ?></span>
            <?php $s = $inv['status']; ?>
            <span class="badge <?= $s==='final'?'badge-success':'badge-warning' ?>"><?= ucfirst($s) ?></span>
        </div>
        <div style="display:flex;gap:8px;margin-left:auto;flex-wrap:wrap;">
            <a href="../sales/view.php?id=<?= $inv['id'] ?>" class="btn btn-sm btn-outline" target="_blank">
                <i class="fas fa-eye"></i> View
            </a>
            <button type="button" onclick="printA4(<?= $inv['id'] ?>)" class="btn btn-sm btn-primary">
                <i class="fas fa-print"></i> Print A4
            </button>
            <button type="button" onclick="downloadPdf(<?= $inv['id'] ?>)" class="btn btn-sm btn-danger">
                <i class="fas fa-file-pdf"></i> PDF
            </button>
            <button type="button" onclick="printThermal(<?= $inv['id'] ?>)" class="btn btn-sm btn-secondary">
                <i class="fas fa-receipt"></i> Thermal
            </button>
            <?php if ($inv['status'] === 'final'): ?>
            <button type="button" class="btn btn-sm btn-success"
                onclick="openPaymentModal(<?= $inv['id'] ?>, '<?= htmlspecialchars($inv['invoice_no'], ENT_QUOTES) ?>', <?= (float)$inv['gross_total'] ?>, <?= (float)$inv['round_off'] ?>, '<?= addslashes($inv['overall_discount_type'] ?? '') ?>', <?= (float)($inv['overall_discount_value'] ?? 0) ?>, <?= (float)$inv['received_amount'] ?>)">
                <i class="fas fa-rupee-sign"></i> Payment
            </button>
            <?php endif; ?>
        </div>
    </div>
    <div style="overflow-x:auto;">
        <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; while ($item = $items->fetch_assoc()): ?>
            <tr>
                <td style="color:var(--text-muted);"><?= $i++ ?></td>
                <td>
                    <strong><?= htmlspecialchars($item['product_name']) ?></strong>
                    <?php if ($item['unit']): ?><span style="font-size:11px;color:var(--text-muted);margin-left:4px;"><?= htmlspecialchars($item['unit']) ?></span><?php endif; ?>
                </td>
                <td style="font-size:12px;color:var(--text-secondary);"><?= htmlspecialchars($item['batch_no']) ?></td>
                <td style="text-align:right;"><?= number_format($item['sold_qty'], 0) ?></td>
                <td style="text-align:right;">&#8377; <?= number_format($item['selling_price_incl'],2) ?></td>
                <td style="text-align:right;font-weight:600;">&#8377; <?= number_format($item['total_amount'],2) ?></td>
            </tr>
            <?php endwhile; ?>
            </tbody>
        </table>
    </div>
    <div style="display:flex;justify-content:flex-end;padding:12px 16px 4px;">
        <table id="inv-totals-<?= $inv['id'] ?>" style="width:240px;font-size:13px;border-collapse:collapse;">
            <tr><td style="color:var(--text-muted);padding:3px 8px;">Gross</td><td style="text-align:right;padding:3px 8px;">&#8377; <?= number_format($inv['gross_total'],2) ?></td></tr>
            <tr class="inv-disc-row-<?= $inv['id'] ?>" <?= $inv['overall_discount_value'] > 0 ? '' : 'style="display:none;"' ?>>
                <td style="color:var(--text-muted);padding:3px 8px;">Discount</td>
                <td class="inv-disc-val-<?= $inv['id'] ?>" style="text-align:right;padding:3px 8px;color:#ef4444;">- &#8377; <?= number_format($inv['overall_discount_value'],2) ?></td>
            </tr>
            <tr><td style="color:var(--text-muted);padding:3px 8px;">GST</td><td class="inv-gst-<?= $inv['id'] ?>" style="text-align:right;padding:3px 8px;">&#8377; <?= number_format($inv['total_gst'],2) ?></td></tr>
            <tr style="border-top:2px solid #e2e8f0;font-weight:700;">
                <td style="padding:6px 8px;">Net Total</td>
                <td class="inv-net-<?= $inv['id'] ?>" style="text-align:right;padding:6px 8px;">&#8377; <?= number_format($inv['net_total'],2) ?></td>
            </tr>
            <tr class="inv-recv-row-<?= $inv['id'] ?>">
                <td style="color:#10b981;padding:3px 8px;">Received</td>
                <td class="inv-recv-<?= $inv['id'] ?>" style="text-align:right;padding:3px 8px;color:#10b981;">&#8377; <?= number_format($inv['received_amount'],2) ?></td>
            </tr>
            <tr>
                <td class="inv-bal-lbl-<?= $inv['id'] ?>" style="color:<?= $inv['balance_amount']>0?'#ef4444':'#10b981' ?>;padding:3px 8px;">Balance</td>
                <td class="inv-bal-<?= $inv['id'] ?>" style="text-align:right;padding:3px 8px;color:<?= $inv['balance_amount']>0?'#ef4444':'#10b981' ?>;">&#8377; <?= number_format($inv['balance_amount'],2) ?></td>
            </tr>
        </table>
    </div>
</div>
<?php endforeach; ?>

<!-- Grand Total -->
<div style="display:flex;justify-content:flex-end;margin-bottom:24px;">
    <div class="totals-box" style="min-width:260px;">
        <div class="totals-row grand-total">
            <span>Master Grand Total</span>
            <span>&#8377; <?= number_format($grandNetTotal, 2) ?></span>
        </div>
    </div>
</div>

<script>
function printA4(id) {
    const template = document.getElementById('printTemplate').value;
    window.open('../sales/print_a4.php?id=' + id + '&template=' + template, '_blank', 'width=900,height=720,scrollbars=yes');
}
function downloadPdf(id) {
    const template = document.getElementById('printTemplate').value;
    window.location.href = '../sales/pdf_download.php?id=' + id + '&template=' + template;
}
function printThermal(id) {
    window.open('../sales/layout_loader_thermal.php?id=' + id, 'thermal_print', 'width=560,height=780,scrollbars=yes');
}

/* ---- Payment Modal ---- */
let _pmId = null, _pmGross = 0, _pmRoundOff = 0;

function calcPayModal() {
    const discType = document.getElementById('pm_disc_type').value;
    const discVal  = parseFloat(document.getElementById('pm_disc_val').value || 0);
    const received = parseFloat(document.getElementById('pm_received').value || 0);
    let net = _pmGross;
    if (discType === 'percent') net -= _pmGross * discVal / 100;
    else if (discType === 'amount') net -= discVal;
    net = Math.max(0, net);
    net = Math.round((net + _pmRoundOff) * 100) / 100;
    const balance = Math.max(0, Math.round((net - received) * 100) / 100);
    document.getElementById('pm_net_display').textContent     = '₹' + net.toFixed(2);
    document.getElementById('pm_balance_display').textContent = '₹' + balance.toFixed(2);
    document.getElementById('pm_balance_display').style.color = balance > 0 ? '#ef4444' : '#10b981';
}

function openPaymentModal(id, invoiceNo, grossTotal, roundOff, discType, discVal, received) {
    _pmId       = id;
    _pmGross    = parseFloat(grossTotal);
    _pmRoundOff = parseFloat(roundOff);
    document.getElementById('pm_id').value               = id;
    document.getElementById('pm_invoice_no').textContent = invoiceNo;
    document.getElementById('pm_gross_display').textContent = '₹' + _pmGross.toFixed(2);
    document.getElementById('pm_disc_type').value        = discType || '';
    document.getElementById('pm_disc_val').value         = parseFloat(discVal || 0).toFixed(2);
    document.getElementById('pm_received').value         = parseFloat(received).toFixed(2);
    document.getElementById('pm_mode').value             = 'Cash';
    document.getElementById('pm_error').style.display   = 'none';
    calcPayModal();
    document.getElementById('paymentModal').style.display = 'flex';
    document.getElementById('pm_received').focus();
}

function closePaymentModal() {
    document.getElementById('paymentModal').style.display = 'none';
    _pmId = null;
}

function savePayment() {
    const id       = document.getElementById('pm_id').value;
    const received = parseFloat(document.getElementById('pm_received').value || 0);
    const mode     = document.getElementById('pm_mode').value;
    const discType = document.getElementById('pm_disc_type').value;
    const discVal  = parseFloat(document.getElementById('pm_disc_val').value || 0);
    const errEl    = document.getElementById('pm_error');
    errEl.style.display = 'none';

    fetch('../sales/ajax_update_payment.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: `id=${id}&received_amount=${received}&payment_mode=${encodeURIComponent(mode)}&overall_discount_type=${encodeURIComponent(discType)}&overall_discount_value=${discVal}`
    })
    .then(r => r.json())
    .then(data => {
        if (data.status !== 'ok') {
            errEl.textContent = data.msg || 'Error saving.';
            errEl.style.display = 'block';
            return;
        }
        // Live-update sub-invoice totals table
        const net = parseFloat(data.net_total);
        const gst = parseFloat(data.total_gst);
        const rec = parseFloat(data.received_amount);
        const bal = parseFloat(data.balance_amount);
        const dt  = data.discount_type;
        const dv  = parseFloat(data.discount_value);

        const discRow = document.querySelector(`.inv-disc-row-${id}`);
        const discVal2 = document.querySelector(`.inv-disc-val-${id}`);
        if (discRow && discVal2) {
            if (dt === 'percent') { discVal2.textContent = '- ' + dv + '%'; discRow.style.display = ''; }
            else if (dt === 'amount') { discVal2.textContent = '- ₹' + dv.toFixed(2); discRow.style.display = ''; }
            else { discRow.style.display = 'none'; }
        }
        const gstEl    = document.querySelector(`.inv-gst-${id}`);
        const netEl    = document.querySelector(`.inv-net-${id}`);
        const recvEl   = document.querySelector(`.inv-recv-${id}`);
        const balEl    = document.querySelector(`.inv-bal-${id}`);
        const balLblEl = document.querySelector(`.inv-bal-lbl-${id}`);
        if (gstEl)    gstEl.textContent  = '₹' + gst.toFixed(2);
        if (netEl)    netEl.textContent  = '₹' + net.toFixed(2);
        if (recvEl)   recvEl.textContent = '₹' + rec.toFixed(2);
        if (balEl)    { balEl.textContent = '₹' + bal.toFixed(2); balEl.style.color = bal > 0 ? '#ef4444' : '#10b981'; }
        if (balLblEl) balLblEl.style.color = bal > 0 ? '#ef4444' : '#10b981';

        closePaymentModal();
    })
    .catch(() => { errEl.textContent = 'Server error. Try again.'; errEl.style.display = 'block'; });
}

function sendWhatsApp() {
    let phone = '<?= preg_replace('/\D/', '', $master['client_phone'] ?? '') ?>';
    if (phone.length === 10) phone = '91' + phone;

    const balance = <?= (float)($totals['grand_balance'] ?? 0) ?>;
    const msg =
        `Dear <?= addslashes($master['client_name']) ?>,\n\n` +
        `Your invoice is ready.\n\n` +
        `📄 Master Ref : *<?= addslashes($master['master_no']) ?>*\n` +
        `📅 Date       : <?= date('d-m-Y', strtotime($master['invoice_date'])) ?>\n` +
        `💰 Amount     : ₹<?= number_format((float)($totals['grand_total'] ?? 0), 2) ?>\n` +
        `✅ Paid       : ₹<?= number_format((float)($totals['grand_received'] ?? 0), 2) ?>\n` +
        (balance > 0 ? `⚠️ Balance    : ₹<?= number_format((float)($totals['grand_balance'] ?? 0), 2) ?>\n` : '') +
        `\nThank you for your business! 🙏`;

    window.open('https://wa.me/' + phone + '?text=' + encodeURIComponent(msg), '_blank');
}
</script>

<!-- Update Payment Modal -->
<div id="paymentModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.45);z-index:2000;align-items:center;justify-content:center;">
    <div style="background:#fff;border-radius:10px;padding:26px 28px 20px;width:430px;max-width:95vw;box-shadow:0 8px 40px rgba(0,0,0,.2);">
        <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;">
            <h3 style="margin:0;font-size:15px;"><i class="fas fa-rupee-sign" style="color:var(--success);margin-right:8px;"></i>Update Payment</h3>
            <button type="button" onclick="closePaymentModal()" style="background:none;border:none;font-size:18px;cursor:pointer;color:var(--text-muted);">&times;</button>
        </div>
        <div style="background:#f8fafc;border-radius:6px;padding:10px 14px;margin-bottom:16px;font-size:13px;line-height:1.9;">
            <div>Invoice: <strong id="pm_invoice_no">—</strong></div>
            <div>Gross Total: <strong id="pm_gross_display">—</strong></div>
            <div>Net Payable: <strong id="pm_net_display" style="color:var(--primary);">—</strong></div>
            <div>Balance: <span id="pm_balance_display" style="color:#ef4444;">—</span></div>
        </div>
        <input type="hidden" id="pm_id">
        <div class="form-group" style="margin-bottom:12px;">
            <label>Overall Discount</label>
            <div style="display:flex;gap:6px;">
                <select id="pm_disc_type" style="width:95px;" onchange="calcPayModal()">
                    <option value="">None</option>
                    <option value="percent">%</option>
                    <option value="amount">₹ Amount</option>
                </select>
                <input type="number" step="0.01" min="0" id="pm_disc_val" placeholder="0.00" style="flex:1;" oninput="calcPayModal()">
            </div>
        </div>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:16px;">
            <div class="form-group" style="margin:0;">
                <label>Received Amount</label>
                <input type="number" step="0.01" id="pm_received" placeholder="0.00" style="width:100%;" oninput="calcPayModal()">
            </div>
            <div class="form-group" style="margin:0;">
                <label>Payment Mode</label>
                <select id="pm_mode" style="width:100%;">
                    <option value="Cash">Cash</option>
                    <option value="UPI">UPI</option>
                    <option value="Card">Card</option>
                    <option value="Bank">Bank Transfer</option>
                </select>
            </div>
        </div>
        <div id="pm_error" style="color:var(--danger);font-size:13px;margin-bottom:8px;display:none;"></div>
        <div style="display:flex;gap:10px;justify-content:flex-end;">
            <button type="button" class="btn btn-secondary" onclick="closePaymentModal()">Cancel</button>
            <button type="button" class="btn btn-success" onclick="savePayment()"><i class="fas fa-save"></i> Save</button>
        </div>
    </div>
</div>

<?php require_once '../includes/footer.php'; ?>
