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

$search = trim($_GET['search'] ?? '');
$where  = '';
if ($search !== '') {
    $s = $conn->real_escape_string($search);
    $where = "AND (mi.master_no LIKE '%$s%' OR c.name LIKE '%$s%')";
}

$masters = $conn->query("
    SELECT mi.*, c.name AS client_name,
           COUNT(si.id)     AS invoice_count,
           SUM(si.net_total) AS total_net
    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 $where
    GROUP BY mi.id
    ORDER BY mi.created_at DESC
");
?>

<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>

<div class="panel">
    <div class="panel-header">
        <span class="panel-title">All Master Invoices</span>
        <form method="get" class="search-bar">
            <input type="text" name="search" placeholder="Search by ref / client..." value="<?= htmlspecialchars($search) ?>">
            <button type="submit" class="btn btn-primary btn-sm"><i class="fas fa-search"></i></button>
            <?php if ($search): ?><a href="index.php" class="btn btn-secondary btn-sm">Clear</a><?php endif; ?>
        </form>
    </div>
    <div style="overflow-x:auto;">
        <table>
            <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>Status</th>
                    <th style="text-align:center;">Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php while ($row = $masters->fetch_assoc()): ?>
            <tr data-master-id="<?= $row['id'] ?>" data-status="<?= $row['status'] ?>">
                <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($row['total_net'] ?? 0, 2) ?></strong></td>
                <td>
                    <?php $s = $row['status']; ?>
                    <span class="badge <?= $s==='final'?'badge-success':'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="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; ?>
                        <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; ?>
                    </div>
                </td>
            </tr>
            <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- 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 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;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>

<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;">Pay</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)}', ${parseFloat(inv.gross_total)}, ${parseFloat(inv.round_off)}, '${escJs(inv.overall_discount_type || '')}', ${parseFloat(inv.overall_discount_value || 0)}, ${parseFloat(inv.received_amount)})">
                        <i class="fas fa-rupee-sign"></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 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) {
    _pmInvId    = 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';
    _pmInvId = 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;
        }
        // Update the picker row for this invoice
        const bal = parseFloat(data.balance_amount);
        const recvEl = document.querySelector(`.pk-recv-${id}`);
        const balEl  = document.querySelector(`.pk-bal-${id}`);
        if (recvEl) recvEl.textContent = '₹' + parseFloat(data.received_amount).toFixed(2);
        if (balEl)  { balEl.textContent = '₹' + bal.toFixed(2); balEl.style.color = bal > 0 ? '#ef4444' : '#10b981'; }

        // If master invoice was finalized, update its row badge + show return button
        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'; }
                // Show return button (append after payment button)
                const actLinks = masterRow.querySelector('.action-links');
                if (actLinks && !actLinks.querySelector('.action-btn.return')) {
                    const retBtn = document.createElement('a');
                    retBtn.href = `../master_returns/create_master.php?master_id=${data.master_id}`;
                    retBtn.className = 'action-btn';
                    retBtn.title = 'Create Return';
                    retBtn.style.cssText = 'background:#fef3c7;color:#92400e;border-color:#fde68a;';
                    retBtn.innerHTML = '<i class="fas fa-undo"></i>';
                    actLinks.appendChild(retBtn);
                }
                // Hide edit/delete buttons
                masterRow.querySelectorAll('.action-btn.edit, .action-btn.delete').forEach(b => b.remove());
                masterRow.dataset.status = 'final';
            }
        }
        closePaymentModal();
    })
    .catch(() => { errEl.textContent = 'Server error. Try again.'; errEl.style.display = 'block'; });
}
</script>

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