<?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';

$userRole = $_SESSION['user_role'] ?? '';

$filterCo  = 0;
$companies = null;
if ($userRole === 'admin') {
    $filterCo  = isset($_GET['co']) ? (int)$_GET['co'] : 0;
    $companies = $conn->query("SELECT id, company_name FROM company_master ORDER BY company_name");
}

$coWhere = $filterCo > 0 ? "AND c.company_id = $filterCo" : "";

$masters = $conn->query("
    SELECT mi.*,
           c.name AS client_name,
           COUNT(si.id)                 AS invoice_count,
           COALESCE(SUM(si.net_total),      0) AS total_net,
           COALESCE(SUM(si.received_amount), 0) AS total_received,
           COALESCE(SUM(si.balance_amount),  0) AS total_balance
    FROM master_invoices mi
    JOIN clients c ON c.id = mi.client_id
    LEFT JOIN sales_invoices si ON si.master_invoice_id = mi.id
    WHERE 1=1 $coWhere
    GROUP BY mi.id
    ORDER BY mi.created_at DESC
");

$showCancelled = isset($_GET['cancelled']) || isset($_GET['show_cancelled']);
?>

<div class="page-header">
    <h2><i class="fas fa-layer-group" style="color:var(--primary);margin-right:8px;"></i>Master Sales Invoices</h2>
    <a href="create.php" class="btn btn-primary"><i class="fas fa-plus"></i> New Master Invoice</a>
</div>

<?php if ($userRole === 'admin' && $companies): ?>
<div class="panel" style="margin-bottom:14px;">
    <div class="panel-body" style="padding:10px 16px;">
        <form method="get" style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;">
            <label style="font-size:13px;font-weight:600;color:var(--text-secondary);margin:0;">Company:</label>
            <select name="co" onchange="this.form.submit()" style="font-size:13px;padding:5px 10px;border:1px solid var(--border);border-radius:6px;">
                <option value="0" <?= $filterCo == 0 ? 'selected' : '' ?>>All Companies</option>
                <?php while ($co = $companies->fetch_assoc()): ?>
                <option value="<?= $co['id'] ?>" <?= $filterCo == $co['id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($co['company_name']) ?>
                </option>
                <?php endwhile; ?>
            </select>
            <?php if ($filterCo > 0): ?>
            <a href="index.php" class="btn btn-secondary btn-sm">Clear</a>
            <?php endif; ?>
        </form>
    </div>
</div>
<?php endif; ?>

<div class="panel">
    <div class="panel-header">
        <span class="panel-title">All Master Invoices</span>
        <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
            <label style="display:inline-flex;align-items:center;gap:5px;font-size:12px;cursor:pointer;color:var(--text-muted);font-weight:500;white-space:nowrap;">
                <input type="checkbox" id="showCancelledChk" <?= $showCancelled ? 'checked' : '' ?> onchange="toggleCancelled(this.checked)">
                Show Cancelled
            </label>
            <div style="position:relative;">
                <i class="fas fa-search" style="position:absolute;left:8px;top:50%;transform:translateY(-50%);color:var(--text-muted);font-size:12px;pointer-events:none;"></i>
                <input type="text" id="pgSearch" placeholder="Search ref, client..."
                       style="padding:5px 8px 5px 28px;font-size:12px;border:1px solid var(--border);border-radius:6px;width:210px;">
            </div>
            <select id="pgPerPage" style="padding:5px 8px;font-size:12px;border:1px solid var(--border);border-radius:6px;">
                <option value="10">10 / page</option>
                <option value="25" selected>25 / page</option>
                <option value="50">50 / page</option>
                <option value="100">100 / page</option>
                <option value="500">500 / page</option>
            </select>
        </div>
    </div>
    <div style="overflow-x:auto;">
        <table id="mainTable">
            <thead>
                <tr>
                    <th>Master Ref</th>
                    <th>Date</th>
                    <th>Client</th>
                    <th style="text-align:center;">Invoices</th>
                    <th style="text-align:right;">Grand Total</th>
                    <th style="text-align:right;">Received</th>
                    <th style="text-align:right;">Balance</th>
                    <th>Status</th>
                    <th style="text-align:center;">Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php while ($row = $masters->fetch_assoc()):
                $ds = strtolower($row['master_no'] . ' ' . $row['client_name'] . ' ' . $row['invoice_date'] . ' ' . $row['status']);
                $bal = (float)$row['total_balance'];
            ?>
            <tr data-search="<?= htmlspecialchars($ds) ?>" data-status="<?= htmlspecialchars($row['status']) ?>"
                data-master-id="<?= $row['id'] ?>"
                <?= $row['status'] === 'cancelled' ? 'style="opacity:.55;"' : '' ?>>
                <td><a href="view.php?id=<?= $row['id'] ?>" style="font-weight:700;color:var(--primary);"><?= htmlspecialchars($row['master_no']) ?></a></td>
                <td><?= date('d-m-Y', strtotime($row['invoice_date'])) ?></td>
                <td><?= htmlspecialchars($row['client_name']) ?></td>
                <td style="text-align:center;"><span class="badge badge-gray"><?= $row['invoice_count'] ?></span></td>
                <td style="text-align:right;"><strong>&#8377; <?= number_format((float)$row['total_net'], 2) ?></strong></td>
                <td class="td-received" style="text-align:right;">&#8377; <?= number_format((float)$row['total_received'], 2) ?></td>
                <td class="td-balance" style="text-align:right;">
                    <span style="font-weight:600;color:<?= $bal > 0 ? 'var(--danger)' : 'var(--success)' ?>;">
                        &#8377; <?= number_format($bal, 2) ?>
                    </span>
                </td>
                <td>
                    <?php $s = $row['status']; ?>
                    <span class="badge <?= $s === 'final' ? 'badge-success' : ($s === 'cancelled' ? 'badge-gray' : 'badge-warning') ?>"><?= ucfirst($s) ?></span>
                </td>
                <td style="text-align:center;">
                    <div class="action-links" style="justify-content:center;">
                        <a href="view.php?id=<?= $row['id'] ?>" class="action-btn view" title="View"><i class="fas fa-eye"></i></a>
                        <?php if ($row['status'] === 'draft'): ?>
                        <a href="edit.php?id=<?= $row['id'] ?>" class="action-btn edit" title="Edit"><i class="fas fa-edit"></i></a>
                        <a href="cancel.php?id=<?= $row['id'] ?>" class="action-btn delete" title="Cancel Invoice"
                           onclick="return confirm('Cancel this master invoice? All sub-invoices will also be cancelled.')"><i class="fas fa-ban"></i></a>
                        <a href="delete.php?id=<?= $row['id'] ?>" class="action-btn delete" title="Delete"
                           onclick="return confirm('Delete this draft master invoice and all its sub-invoices?')"><i class="fas fa-trash"></i></a>
                        <?php endif; ?>
                        <?php if ($row['status'] === 'cancelled'): ?>
                        <a href="create.php?copy_from=<?= $row['id'] ?>" class="action-btn" title="Copy Invoice" style="background:#eff6ff;color:#2563eb;border-color:#bfdbfe;"><i class="fas fa-copy"></i></a>
                        <?php endif; ?>
                        <button type="button" class="action-btn print" title="Print Invoice Thermal"
                            onclick="printThermal(<?= $row['id'] ?>)">
                            <i class="fas fa-print"></i>
                        </button>
                        <button type="button" class="action-btn" style="color:#0891b2;" title="Print Transport Slip"
                            onclick="printThermalTransport(<?= $row['id'] ?>)">
                            <i class="fas fa-truck"></i>
                        </button>
                        <button type="button" class="action-btn" style="color:var(--success);" title="Update Payment"
                            onclick="openPickerModal(<?= $row['id'] ?>, '<?= htmlspecialchars($row['master_no'], ENT_QUOTES) ?>')">
                            <i class="fas fa-rupee-sign"></i>
                        </button>
                        <?php if ($row['status'] === 'final'): ?>
                        <a href="../master_returns/create_master.php?master_id=<?= $row['id'] ?>" class="action-btn" title="Create Return" style="background:#fef3c7;color:#92400e;border-color:#fde68a;"><i class="fas fa-undo"></i></a>
                        <?php endif; ?>
                        <?php if ($row['status'] === 'final' && hasPermission('master_sales', 'revert')): ?>
                        <a href="revert_to_draft.php?id=<?= $row['id'] ?>"
                           onclick="return confirm('Revert this master invoice to Draft?\nStock will be restored for all sub-invoices and it will become editable again.')"
                           class="action-btn" style="color:#7c3aed;" title="Revert to Draft">
                            <i class="fas fa-clock-rotate-left"></i>
                        </a>
                        <?php endif; ?>
                    </div>
                </td>
            </tr>
            <?php endwhile; ?>
            </tbody>
        </table>
    </div>
    <div id="pgBar" class="pg-bar"></div>
</div>

<style>
.pg-bar{display:flex;align-items:center;gap:8px;padding:8px 16px;border-top:1px solid var(--border,#e2e8f0);flex-wrap:wrap;background:#fafafa;border-radius:0 0 8px 8px}
.pg-info{font-size:13px;color:var(--text-muted,#94a3b8)}
.pg-btns{display:flex;gap:3px;margin-left:auto}
.pg-btns button{padding:3px 9px;font-size:12px;border:1px solid var(--border,#e2e8f0);border-radius:4px;background:#fff;cursor:pointer;min-width:32px}
.pg-btns button:disabled{opacity:.4;cursor:not-allowed}
.pg-btns button.active{background:var(--primary,#2563eb);color:#fff;border-color:var(--primary,#2563eb);font-weight:600}
</style>

<script>
let _showCancelled = <?= $showCancelled ? 'true' : 'false' ?>;
function toggleCancelled(show) {
    _showCancelled = show;
    pgGo(1);
}
(function(){
    const rows     = Array.from(document.querySelectorAll('#mainTable tbody tr[data-search]'));
    const searchEl = document.getElementById('pgSearch');
    const perPageEl= document.getElementById('pgPerPage');
    const barEl    = document.getElementById('pgBar');
    let page = 1;

    function getVis() {
        const q = (searchEl?.value || '').trim().toLowerCase();
        return rows.filter(r => {
            if (!_showCancelled && r.dataset.status === 'cancelled') return false;
            return !q || (r.dataset.search || '').includes(q);
        });
    }
    function render() {
        const pp    = parseInt(perPageEl?.value || 25);
        const vis   = getVis();
        const total = vis.length;
        const pages = Math.max(1, Math.ceil(total / pp));
        if (page > pages) page = pages;

        rows.forEach(r => r.style.display = 'none');
        const start = (page - 1) * pp;
        vis.slice(start, start + pp).forEach(r => r.style.display = '');

        const s = Math.max(1, page - 2), e = Math.min(pages, page + 2);
        let html = `<span class="pg-info">Showing ${total === 0 ? 0 : start + 1}–${Math.min(start + pp, total)} of ${total} records</span><div class="pg-btns">`;
        html += `<button onclick="pgGo(1)" ${page <= 1 ? 'disabled' : ''}>«</button>`;
        html += `<button onclick="pgGo(${page - 1})" ${page <= 1 ? 'disabled' : ''}>‹</button>`;
        for (let i = s; i <= e; i++) html += `<button onclick="pgGo(${i})" ${i === page ? 'class="active"' : ''}>${i}</button>`;
        html += `<button onclick="pgGo(${page + 1})" ${page >= pages ? 'disabled' : ''}>›</button>`;
        html += `<button onclick="pgGo(${pages})" ${page >= pages ? 'disabled' : ''}>»</button></div>`;
        barEl.innerHTML = html;
    }
    window.pgGo = function(p) { page = parseInt(p); render(); };
    searchEl?.addEventListener('input', function() { page = 1; render(); });
    perPageEl?.addEventListener('change', function() { page = 1; render(); });
    render();
})();
</script>


<!-- Sub-Invoice Picker Modal -->
<div id="pickerModal" 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:24px 26px 20px;width:600px;max-width:96vw;max-height:85vh;display:flex;flex-direction:column;box-shadow:0 8px 40px rgba(0,0,0,.2);">
        <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:14px;">
            <h3 style="margin:0;font-size:15px;"><i class="fas fa-layer-group" style="color:var(--primary);margin-right:8px;"></i>Select Invoice — <span id="picker_master_no" style="color:var(--primary);"></span></h3>
            <button type="button" onclick="closePickerModal()" style="background:none;border:none;font-size:18px;cursor:pointer;color:var(--text-muted);">&times;</button>
        </div>
        <div id="pickerBody" style="overflow-y:auto;flex:1;">
            <div style="text-align:center;padding:30px;color:var(--text-muted);"><i class="fas fa-spinner fa-spin"></i> Loading...</div>
        </div>
    </div>
</div>

<!-- Payment Ledger Modal -->
<div id="paymentModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.45);z-index:3000;align-items:center;justify-content:center;">
    <div style="background:#fff;border-radius:10px;width:520px;max-width:97vw;max-height:90vh;display:flex;flex-direction:column;box-shadow:0 8px 40px rgba(0,0,0,.2);">
        <div style="padding:16px 20px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;flex-shrink:0;">
            <h3 style="margin:0;font-size:15px;"><i class="fas fa-receipt" style="color:var(--success);margin-right:8px;"></i>Payment Ledger &nbsp;<span id="pm_invoice_no" style="color:var(--text-muted);font-weight:500;font-size:13px;"></span><span id="pm_invoice_date" style="color:var(--text-muted);font-weight:400;font-size:12px;margin-left:8px;"></span></h3>
            <button type="button" onclick="closePaymentModal()" style="background:none;border:none;font-size:20px;cursor:pointer;color:var(--text-muted);line-height:1;">&times;</button>
        </div>
        <div style="padding:14px 20px;overflow-y:auto;flex:1;">
            <input type="hidden" id="pm_id">
            <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px;margin-bottom:14px;">
                <div style="background:#f0f9ff;border-radius:6px;padding:8px 12px;text-align:center;">
                    <div style="font-size:11px;color:var(--text-muted);text-transform:uppercase;letter-spacing:.5px;margin-bottom:2px;">Net Payable</div>
                    <div style="font-weight:700;font-size:14px;color:var(--primary);">₹<span id="pm_net_display">—</span></div>
                </div>
                <div style="background:#f0fdf4;border-radius:6px;padding:8px 12px;text-align:center;">
                    <div style="font-size:11px;color:var(--text-muted);text-transform:uppercase;letter-spacing:.5px;margin-bottom:2px;">Total Paid</div>
                    <div style="font-weight:700;font-size:14px;color:var(--success);">₹<span id="pm_paid_display">—</span></div>
                </div>
                <div style="background:#fef2f2;border-radius:6px;padding:8px 12px;text-align:center;">
                    <div style="font-size:11px;color:var(--text-muted);text-transform:uppercase;letter-spacing:.5px;margin-bottom:2px;">Balance</div>
                    <div id="pm_balance_box" style="font-weight:700;font-size:14px;color:#ef4444;">₹<span id="pm_balance_display">—</span></div>
                </div>
            </div>
            <div style="margin-bottom:14px;">
                <div style="font-size:12px;font-weight:600;text-transform:uppercase;letter-spacing:.5px;color:var(--text-muted);margin-bottom:6px;">Payment History</div>
                <div id="pm_history"><div style="text-align:center;padding:10px;color:var(--text-muted);"><i class="fas fa-spinner fa-spin"></i></div></div>
            </div>
            <div style="background:#f8fafc;border-radius:8px;padding:12px 14px;margin-bottom:14px;">
                <div style="font-size:12px;font-weight:600;text-transform:uppercase;letter-spacing:.5px;color:var(--text-muted);margin-bottom:10px;">Add Payment</div>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:10px;">
                    <div class="form-group" style="margin:0;"><label style="font-size:12px;">Amount (₹)</label><input type="number" step="0.01" id="pm_new_amount" placeholder="0.00" style="width:100%;"></div>
                    <div class="form-group" style="margin:0;"><label style="font-size:12px;">Payment Mode</label>
                        <select id="pm_new_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 class="form-group" style="margin:0;"><label style="font-size:12px;">Payment Date</label><input type="date" id="pm_new_date" style="width:100%;"></div>
                    <div class="form-group" style="margin:0;"><label style="font-size:12px;">Note (optional)</label><input type="text" id="pm_new_note" placeholder="Ref, cheque no..." style="width:100%;"></div>
                </div>
                <div id="pm_add_error" style="color:var(--danger);font-size:12px;margin-bottom:6px;display:none;"></div>
                <button type="button" class="btn btn-success btn-sm" onclick="pmAddPayment()"><i class="fas fa-plus"></i> Add Payment</button>
            </div>
            <div style="background:#fff7ed;border-radius:8px;padding:12px 14px;border:1px solid #fed7aa;">
                <div style="font-size:12px;font-weight:600;text-transform:uppercase;letter-spacing:.5px;color:#92400e;margin-bottom:10px;">Update Overall Discount &amp; Finalize</div>
                <div style="display:flex;gap:8px;align-items:flex-end;flex-wrap:wrap;">
                    <div class="form-group" style="margin:0;flex:0 0 110px;"><label style="font-size:12px;">Discount Type</label>
                        <select id="pm_disc_type" style="width:100%;"><option value="">None</option><option value="percent">Percent %</option><option value="amount">Amount ₹</option></select>
                    </div>
                    <div class="form-group" style="margin:0;flex:1;min-width:80px;"><label style="font-size:12px;">Value</label>
                        <input type="number" step="0.01" min="0" id="pm_disc_val" placeholder="0.00" style="width:100%;">
                    </div>
                    <button type="button" class="btn btn-primary btn-sm" onclick="pmSaveDiscount()" style="margin-bottom:1px;"><i class="fas fa-tag"></i> Apply &amp; Finalize</button>
                </div>
                <div id="pm_disc_error" style="color:var(--danger);font-size:12px;margin-top:6px;display:none;"></div>
            </div>
        </div>
        <div style="padding:12px 20px;border-top:1px solid var(--border);display:flex;justify-content:flex-end;flex-shrink:0;">
            <button type="button" class="btn btn-secondary" onclick="closePaymentModal()">Close</button>
        </div>
    </div>
</div>

<script>
/* ---- Picker Modal ---- */
let _currentMasterId = null;

function openPickerModal(masterId, masterNo) {
    _currentMasterId = masterId;
    document.getElementById('picker_master_no').textContent = masterNo;
    document.getElementById('pickerBody').innerHTML =
        '<div style="text-align:center;padding:30px;color:var(--text-muted);"><i class="fas fa-spinner fa-spin"></i> Loading...</div>';
    document.getElementById('pickerModal').style.display = 'flex';

    fetch('ajax_sub_invoices.php?master_id=' + masterId)
    .then(r => r.json())
    .then(invoices => {
        if (!invoices.length) {
            document.getElementById('pickerBody').innerHTML =
                '<div style="padding:20px;color:var(--text-muted);">No invoices found.</div>';
            return;
        }
        let html = '<table style="width:100%;border-collapse:collapse;font-size:13px;">';
        html += '<thead><tr style="background:#f1f5f9;">' +
            '<th style="padding:7px 10px;text-align:left;font-size:11px;text-transform:uppercase;">Company</th>' +
            '<th style="padding:7px 10px;text-align:left;font-size:11px;text-transform:uppercase;">Invoice No</th>' +
            '<th style="padding:7px 10px;text-align:right;font-size:11px;text-transform:uppercase;">Net Total</th>' +
            '<th style="padding:7px 10px;text-align:right;font-size:11px;text-transform:uppercase;">Received</th>' +
            '<th style="padding:7px 10px;text-align:right;font-size:11px;text-transform:uppercase;">Balance</th>' +
            '<th style="padding:7px 10px;text-align:center;font-size:11px;text-transform:uppercase;">Ledger</th>' +
            '</tr></thead><tbody>';

        invoices.forEach(inv => {
            const bal = parseFloat(inv.balance_amount);
            const balColor = bal > 0 ? '#ef4444' : '#10b981';
            html += `<tr id="picker-row-${inv.id}" style="border-bottom:1px solid #e2e8f0;">
                <td style="padding:8px 10px;">${escHtml(inv.company_name)}</td>
                <td style="padding:8px 10px;font-weight:600;">${escHtml(inv.invoice_no)}</td>
                <td style="padding:8px 10px;text-align:right;">₹${parseFloat(inv.net_total).toFixed(2)}</td>
                <td class="pk-recv-${inv.id}" style="padding:8px 10px;text-align:right;color:#10b981;">₹${parseFloat(inv.received_amount).toFixed(2)}</td>
                <td class="pk-bal-${inv.id}" style="padding:8px 10px;text-align:right;font-weight:600;color:${balColor};">₹${bal.toFixed(2)}</td>
                <td style="padding:8px 10px;text-align:center;">
                    <button class="btn btn-sm btn-success" style="padding:3px 10px;"
                        onclick="openPaymentModal(${inv.id}, '${escJs(inv.invoice_no)}', '${escJs(inv.invoice_date ? new Date(inv.invoice_date).toLocaleDateString('en-GB').split('/').join('-') : '')}', ${parseFloat(inv.gross_total)}, ${parseFloat(inv.round_off)}, '${escJs(inv.overall_discount_type || '')}', ${parseFloat(inv.overall_discount_value || 0)})">
                        <i class="fas fa-receipt"></i>
                    </button>
                </td>
            </tr>`;
        });
        html += '</tbody></table>';
        document.getElementById('pickerBody').innerHTML = html;
    })
    .catch(() => {
        document.getElementById('pickerBody').innerHTML =
            '<div style="padding:20px;color:var(--danger);">Failed to load invoices.</div>';
    });
}

function closePickerModal() {
    document.getElementById('pickerModal').style.display = 'none';
    _currentMasterId = null;
}

function escHtml(str) {
    return String(str).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
function escJs(str) {
    return String(str).replace(/\\/g,'\\\\').replace(/'/g,"\\'");
}

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

function openPaymentModal(id, invoiceNo, invoiceDate, grossTotal, roundOff, discType, discVal) {
    _pmInvId    = id;
    _pmGross    = parseFloat(grossTotal);
    _pmRoundOff = parseFloat(roundOff);
    document.getElementById('pm_id').value               = id;
    document.getElementById('pm_invoice_no').textContent = invoiceNo;
    document.getElementById('pm_invoice_date').textContent = invoiceDate ? '· ' + invoiceDate : '';
    document.getElementById('pm_disc_type').value        = discType || '';
    document.getElementById('pm_disc_val').value         = parseFloat(discVal || 0).toFixed(2);
    document.getElementById('pm_new_date').value         = new Date().toISOString().slice(0,10);
    document.getElementById('pm_new_amount').value       = '';
    document.getElementById('pm_new_note').value         = '';
    document.getElementById('pm_add_error').style.display  = 'none';
    document.getElementById('pm_disc_error').style.display = 'none';
    document.getElementById('paymentModal').style.display  = 'flex';
    pmLoadHistory(id);
    document.getElementById('pm_new_amount').focus();
}

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

function pmUpdateSummary(net, paid, balance) {
    document.getElementById('pm_net_display').textContent     = parseFloat(net).toFixed(2);
    document.getElementById('pm_paid_display').textContent    = parseFloat(paid).toFixed(2);
    document.getElementById('pm_balance_display').textContent = parseFloat(balance).toFixed(2);
    const bb = document.getElementById('pm_balance_box');
    bb.style.color      = parseFloat(balance) > 0 ? '#ef4444' : '#10b981';
    bb.style.background = parseFloat(balance) > 0 ? '' : '#f0fdf4';
    const recvEl = document.querySelector('.pk-recv-' + _pmInvId);
    const balEl  = document.querySelector('.pk-bal-'  + _pmInvId);
    if (recvEl) recvEl.textContent = '₹' + parseFloat(paid).toFixed(2);
    if (balEl)  { balEl.textContent = '₹' + parseFloat(balance).toFixed(2); balEl.style.color = parseFloat(balance) > 0 ? '#ef4444' : '#10b981'; }
}

function pmLoadHistory(id) {
    document.getElementById('pm_history').innerHTML =
        '<div style="text-align:center;padding:10px;color:var(--text-muted);"><i class="fas fa-spinner fa-spin"></i></div>';
    fetch('../sales/ajax_payment.php?action=list&sales_invoice_id=' + id)
    .then(r => r.json())
    .then(data => {
        if (data.status !== 'ok') { document.getElementById('pm_history').innerHTML = '<div style="color:var(--danger);font-size:13px;">' + data.msg + '</div>'; return; }
        pmUpdateSummary(data.net_total, data.received_amount, data.balance_amount);
        pmRenderHistory(data.payments, id);
    });
}

const _pmModeIcon = {Cash:'💵',UPI:'📱',Card:'💳',Bank:'🏦'};
function pmRenderHistory(payments, invId) {
    if (!payments.length) { document.getElementById('pm_history').innerHTML = '<div style="color:var(--text-muted);font-size:13px;padding:6px 0;">No payments recorded yet.</div>'; return; }
    let html = '<table style="width:100%;border-collapse:collapse;font-size:12px;"><thead><tr style="background:#f8fafc;"><th style="padding:5px 8px;text-align:left;font-weight:600;">Date</th><th style="padding:5px 8px;text-align:left;font-weight:600;">Mode</th><th style="padding:5px 8px;text-align:right;font-weight:600;">Amount</th><th style="padding:5px 8px;text-align:left;font-weight:600;">Note</th><th style="padding:5px 4px;"></th></tr></thead><tbody>';
    payments.forEach(p => {
        const d = p.payment_date.split('-');
        html += `<tr style="border-bottom:1px solid #f1f5f9;">
            <td style="padding:5px 8px;">${d[2]+'-'+d[1]+'-'+d[0]}</td>
            <td style="padding:5px 8px;">${_pmModeIcon[p.payment_mode]||''} ${p.payment_mode}</td>
            <td style="padding:5px 8px;text-align:right;font-weight:600;color:var(--success);">₹${parseFloat(p.amount).toFixed(2)}</td>
            <td style="padding:5px 8px;color:var(--text-muted);">${p.note||'—'}</td>
            <td style="padding:5px 4px;text-align:center;"><button type="button" onclick="pmDeletePayment(${p.id},${invId})" style="background:none;border:none;color:var(--danger);cursor:pointer;font-size:13px;" title="Delete"><i class="fas fa-trash-alt"></i></button></td>
        </tr>`;
    });
    html += '</tbody></table>';
    document.getElementById('pm_history').innerHTML = html;
}

function pmAddPayment() {
    const id = document.getElementById('pm_id').value;
    const amount = parseFloat(document.getElementById('pm_new_amount').value || 0);
    const mode   = document.getElementById('pm_new_mode').value;
    const date   = document.getElementById('pm_new_date').value;
    const note   = document.getElementById('pm_new_note').value.trim();
    const errEl  = document.getElementById('pm_add_error');
    errEl.style.display = 'none';
    if (amount <= 0) { errEl.textContent = 'Enter a valid amount.'; errEl.style.display = 'block'; return; }
    if (!date)       { errEl.textContent = 'Select a payment date.'; errEl.style.display = 'block'; return; }
    fetch('../sales/ajax_payment.php', {method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'},
        body:`action=add&sales_invoice_id=${id}&amount=${amount}&payment_mode=${encodeURIComponent(mode)}&payment_date=${date}&note=${encodeURIComponent(note)}`})
    .then(r => r.json())
    .then(data => {
        if (data.status !== 'ok') { errEl.textContent = data.msg; errEl.style.display = 'block'; return; }
        document.getElementById('pm_new_amount').value = '';
        document.getElementById('pm_new_note').value   = '';
        pmUpdateSummary(data.net_total, data.received_amount, data.balance_amount);
        pmLoadHistory(id);
    })
    .catch(() => { errEl.textContent = 'Server error.'; errEl.style.display = 'block'; });
}

function pmDeletePayment(payId, invId) {
    if (!confirm('Delete this payment entry?')) return;
    fetch('../sales/ajax_payment.php', {method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'},
        body:`action=delete&sales_invoice_id=${invId}&payment_id=${payId}`})
    .then(r => r.json())
    .then(data => {
        if (data.status !== 'ok') { alert(data.msg); return; }
        pmUpdateSummary(data.net_total, data.received_amount, data.balance_amount);
        pmLoadHistory(invId);
    });
}

function pmSaveDiscount() {
    const id       = document.getElementById('pm_id').value;
    const discType = document.getElementById('pm_disc_type').value;
    const discVal  = parseFloat(document.getElementById('pm_disc_val').value || 0);
    const errEl    = document.getElementById('pm_disc_error');
    errEl.style.display = 'none';
    fetch('../sales/ajax_update_payment.php', {method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'},
        body:`id=${id}&overall_discount_type=${encodeURIComponent(discType)}&overall_discount_value=${discVal}`})
    .then(r => r.json())
    .then(data => {
        if (data.status !== 'ok') { errEl.textContent = data.msg || 'Error.'; errEl.style.display = 'block'; return; }
        pmUpdateSummary(data.net_total, data.received_amount, data.balance_amount);
        if (data.master_finalized && data.master_id) {
            const masterRow = document.querySelector(`tr[data-master-id="${data.master_id}"]`);
            if (masterRow) {
                const badgeEl = masterRow.querySelector('.badge:not(.badge-gray)');
                if (badgeEl) { badgeEl.className = 'badge badge-success'; badgeEl.textContent = 'Final'; }
                masterRow.querySelectorAll('.action-btn.edit, .action-btn.delete').forEach(b => b.remove());
            }
        }
        pmLoadHistory(id);
    })
    .catch(() => { errEl.textContent = 'Server error.'; errEl.style.display = 'block'; });
}
</script>


<!-- Print Picker Modal -->
<div id="printPickerModal" 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:24px 26px 20px;width:520px;max-width:96vw;max-height:80vh;display:flex;flex-direction:column;box-shadow:0 8px 40px rgba(0,0,0,.2);">
        <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:14px;">
            <h3 style="margin:0;font-size:15px;"><i class="fas fa-print" style="color:var(--primary);margin-right:8px;"></i>Select Invoice to Print</h3>
            <button type="button" onclick="closePrintPicker()" style="background:none;border:none;font-size:18px;cursor:pointer;color:var(--text-muted);">&times;</button>
        </div>
        <div id="printPickerBody" style="overflow-y:auto;flex:1;">
            <div style="text-align:center;padding:30px;color:var(--text-muted);"><i class="fas fa-spinner fa-spin"></i> Loading...</div>
        </div>
    </div>
</div>

<script>
let _printType = 'invoice';

function openPrintPicker(masterId, type) {
    _printType = type;
    document.getElementById('printPickerBody').innerHTML =
        '<div style="text-align:center;padding:30px;color:var(--text-muted);"><i class="fas fa-spinner fa-spin"></i> Loading...</div>';

    fetch('ajax_sub_invoices.php?master_id=' + masterId)
    .then(r => r.json())
    .then(invoices => {
        if (!invoices.length) {
            document.getElementById('printPickerBody').innerHTML =
                '<div style="padding:20px;color:var(--text-muted);">No invoices found.</div>';
            document.getElementById('printPickerModal').style.display = 'flex';
            return;
        }
        if (invoices.length === 1) {
            doPrint(invoices[0].id, type);
            return;
        }
        let html = '<table style="width:100%;border-collapse:collapse;font-size:13px;">';
        html += '<thead><tr style="background:#f1f5f9;">' +
            '<th style="padding:7px 10px;text-align:left;font-size:11px;text-transform:uppercase;">Company</th>' +
            '<th style="padding:7px 10px;text-align:left;font-size:11px;text-transform:uppercase;">Invoice No</th>' +
            '<th style="padding:7px 10px;text-align:center;font-size:11px;text-transform:uppercase;">Print</th>' +
            '</tr></thead><tbody>';
        invoices.forEach(inv => {
            html += `<tr style="border-bottom:1px solid #e2e8f0;">
                <td style="padding:8px 10px;">${escHtml(inv.company_name)}</td>
                <td style="padding:8px 10px;font-weight:600;">${escHtml(inv.invoice_no)}</td>
                <td style="padding:8px 10px;text-align:center;display:flex;gap:6px;justify-content:center;">
                    <button class="btn btn-sm btn-secondary" onclick="doPrint(${inv.id},'invoice')" title="Print Invoice Thermal">
                        <i class="fas fa-receipt"></i> Invoice
                    </button>
                    <button class="btn btn-sm btn-secondary" style="color:#0891b2;border-color:#0891b2;" onclick="doPrint(${inv.id},'transport')" title="Print Transport Slip">
                        <i class="fas fa-truck"></i> Transport
                    </button>
                </td>
            </tr>`;
        });
        html += '</tbody></table>';
        document.getElementById('printPickerBody').innerHTML = html;
        document.getElementById('printPickerModal').style.display = 'flex';
    })
    .catch(() => {
        document.getElementById('printPickerBody').innerHTML =
            '<div style="padding:20px;color:var(--danger);">Failed to load invoices.</div>';
        document.getElementById('printPickerModal').style.display = 'flex';
    });
}

function doPrint(salesInvoiceId, type) {
    window.open('../sales/layout_loader_thermal.php?id=' + salesInvoiceId + '&type=' + type,
        'thermal_print', 'width=560,height=780,scrollbars=yes');
    closePrintPicker();
}

function closePrintPicker() {
    document.getElementById('printPickerModal').style.display = 'none';
}

function printThermal(masterId)          { openPrintPicker(masterId, 'invoice'); }
function printThermalTransport(masterId) { openPrintPicker(masterId, 'transport'); }
</script>

<?php if (($msg = $_GET['msg'] ?? '') === 'cancelled'): ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const notice = document.createElement('div');
    notice.style.cssText = 'position:fixed;top:70px;right:20px;background:#1e293b;color:#fff;padding:12px 20px;border-radius:8px;z-index:9999;font-size:14px;box-shadow:0 4px 16px rgba(0,0,0,.3);';
    notice.innerHTML = '<i class="fas fa-ban" style="margin-right:8px;color:#f87171;"></i>Invoice cancelled successfully.';
    document.body.appendChild(notice);
    setTimeout(() => notice.remove(), 3500);
});
</script>
<?php endif; ?>

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