<?php
require_once '../includes/auth.php';
requirePermission('sales', 'view');
require_once '../db.php';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

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

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

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

$result = $conn->query("
    SELECT si.*, c.name AS customer_name
    FROM sales_invoices si
    JOIN clients c ON c.id = si.client_id
    WHERE 1=1 $coWhere
    ORDER BY si.id DESC
");

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

<div class="page-header">
    <h2><i class="fas fa-receipt" style="color:var(--primary);margin-right:8px;"></i>Sales Invoices</h2>
    <div style="display:flex;gap:8px;">
        <a href="create_ai.php" class="btn btn-outline btn-sm btn-ai-outline">
            <i class="fas fa-magic"></i> New Invoice via AI
        </a>
        <a href="create.php" class="btn btn-primary"><i class="fas fa-plus"></i> New Invoice</a>
    </div>
</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 != $cid): ?>
            <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 Invoices</span>
        <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
            <?php if (isset($_GET['msg']) && $_GET['msg'] === 'cancelled'): ?>
            <span style="font-size:12px;color:var(--text-muted);background:#f1f5f9;padding:3px 10px;border-radius:4px;"><i class="fas fa-ban" style="margin-right:4px;"></i>Invoice cancelled.</span>
            <?php endif; ?>
            <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 invoice, customer..."
                       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>Invoice No</th>
                    <th>Date</th>
                    <th>Customer</th>
                    <th style="text-align:right;">Gross</th>
                    <th>Discount</th>
                    <th style="text-align:right;">GST</th>
                    <th style="text-align:right;">Net 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 if ($result->num_rows > 0): ?>
                <?php while ($row = $result->fetch_assoc()):
                    $ds = strtolower($row['invoice_no'].' '.$row['customer_name'].' '.$row['invoice_date'].' '.$row['status']);
                ?>
                <tr data-search="<?= htmlspecialchars($ds) ?>" data-id="<?= $row['id'] ?>" data-status="<?= htmlspecialchars($row['status']) ?>"
                    <?= $row['status'] === 'cancelled' ? 'style="opacity:.55;"' : '' ?>>
                    <td><strong><?= htmlspecialchars($row['invoice_no']) ?></strong></td>
                    <td><?= htmlspecialchars($row['invoice_date']) ?></td>
                    <td><?= htmlspecialchars($row['customer_name']) ?></td>
                    <td style="text-align:right;">&#8377; <?= number_format($row['gross_total'], 2) ?></td>
                    <td class="td-discount">
                        <?php
                        if ($row['overall_discount_type'] === 'percent')
                            echo $row['overall_discount_value'] . '%';
                        elseif ($row['overall_discount_type'] === 'amount')
                            echo '&#8377; ' . number_format($row['overall_discount_value'], 2);
                        else echo '<span class="text-muted">—</span>';
                        ?>
                    </td>
                    <td class="td-gst" style="text-align:right;">&#8377; <?= number_format($row['total_gst'], 2) ?></td>
                    <td class="td-net" style="text-align:right;"><strong>&#8377; <?= number_format($row['net_total'], 2) ?></strong></td>
                    <td class="td-received" style="text-align:right;">&#8377; <?= number_format($row['received_amount'], 2) ?></td>
                    <td class="td-balance" style="text-align:right;">
                        <?php $bal = $row['balance_amount']; ?>
                        <span style="color:<?= $bal > 0 ? 'var(--danger)' : 'var(--success)' ?>;">
                            &#8377; <?= number_format($bal, 2) ?>
                        </span>
                    </td>
                    <td>
                        <?php
                        $s  = strtolower($row['status']);
                        $bc = $s === 'final' || $s === 'finalized' ? 'badge-success'
                            : ($s === 'draft' ? 'badge-warning'
                            : ($s === 'cancelled' ? 'badge-gray' : 'badge-gray'));
                        ?>
                        <span class="badge <?= $bc ?>"><?= ucfirst($s) ?></span>
                    </td>
                    <td>
                        <div class="action-links" style="justify-content:center;">
                            <?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="javascript:void(0)"
                                   onclick="openPrintModal('sales', <?= $row['id'] ?>, 'invoice', 'thermal')"
                                   class="action-btn print" title="Print Thermal">
                                    <i class="fas fa-print"></i>
                                </a>
                                <a href="view.php?id=<?= $row['id'] ?>" class="action-btn view" title="View">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <a href="javascript:void(0)"
                                   onclick="openPaymentModal(<?= $row['id'] ?>, '<?= htmlspecialchars($row['invoice_no'], ENT_QUOTES) ?>', <?= (float)$row['gross_total'] ?>, <?= (float)$row['round_off'] ?>, '<?= addslashes($row['overall_discount_type'] ?? '') ?>', <?= (float)($row['overall_discount_value'] ?? 0) ?>, <?= (float)$row['received_amount'] ?>)"
                                   class="action-btn" style="color:var(--success);" title="Update Payment">
                                    <i class="fas fa-rupee-sign"></i>
                                </a>
                                <a href="cancel.php?id=<?= $row['id'] ?>"
                                   onclick="return confirm('Cancel this draft invoice / quotation? This cannot be undone.')"
                                   class="action-btn" style="color:var(--danger);" title="Cancel Invoice">
                                    <i class="fas fa-ban"></i>
                                </a>
                                <a href="delete.php?id=<?= $row['id'] ?>"
                                   onclick="return confirm('Delete this draft invoice?')"
                                   class="action-btn delete" title="Delete">
                                    <i class="fas fa-trash-alt"></i>
                                </a>
                            <?php elseif ($row['status'] === 'cancelled'): ?>
                                <a href="view.php?id=<?= $row['id'] ?>" class="action-btn view" title="View">
                                    <i class="fas fa-eye"></i>
                                </a>
                            <?php else: ?>
                                <a href="javascript:void(0)"
                                   onclick="openPrintModal('sales', <?= $row['id'] ?>, 'invoice', 'thermal')"
                                   class="action-btn print" title="Print Thermal">
                                    <i class="fas fa-print"></i>
                                </a>
                                <a href="view.php?id=<?= $row['id'] ?>" class="action-btn view" title="View">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <a href="javascript:void(0)"
                                   onclick="openPaymentModal(<?= $row['id'] ?>, '<?= htmlspecialchars($row['invoice_no'], ENT_QUOTES) ?>', <?= (float)$row['gross_total'] ?>, <?= (float)$row['round_off'] ?>, '<?= addslashes($row['overall_discount_type'] ?? '') ?>', <?= (float)($row['overall_discount_value'] ?? 0) ?>, <?= (float)$row['received_amount'] ?>)"
                                   class="action-btn" style="color:var(--success);" title="Update Payment">
                                    <i class="fas fa-rupee-sign"></i>
                                </a>
                                <a href="<?= BASE_URL ?>/sales_return/create.php?invoice_id=<?= $row['id'] ?>"
                                   class="action-btn return" title="Sales Return">
                                    <i class="fas fa-undo"></i>
                                </a>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr>
                    <td colspan="11" style="text-align:center;padding:40px;color:var(--text-muted);">
                        <i class="fas fa-inbox" style="font-size:28px;display:block;margin-bottom:8px;"></i>
                        No sales invoices found.
                    </td>
                </tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
    <div id="pgBar" class="pg-bar"></div>
</div>

<style>
.btn-ai-outline{color:var(--primary);border-color:var(--primary);background:#fff;}
.btn-ai-outline:hover{background:var(--primary);color:#fff;}
.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>

<!-- 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:var(--bg-light,#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:var(--danger);">—</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>
let _pmRow = 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 ? 'var(--danger)' : 'var(--success)';
}

function openPaymentModal(id, invoiceNo, grossTotal, roundOff, discType, discVal, received) {
    _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';
    _pmRow = document.querySelector(`tr[data-id="${id}"]`);
    calcPayModal();
    document.getElementById('paymentModal').style.display = 'flex';
    document.getElementById('pm_received').focus();
}

function closePaymentModal() {
    document.getElementById('paymentModal').style.display = 'none';
    _pmRow = 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('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 payment.';
            errEl.style.display = 'block';
            return;
        }
        if (_pmRow) {
            const discCell = _pmRow.querySelector('.td-discount');
            const gstCell  = _pmRow.querySelector('.td-gst');
            const netCell  = _pmRow.querySelector('.td-net');
            const recCell  = _pmRow.querySelector('.td-received');
            const balCell  = _pmRow.querySelector('.td-balance');
            if (discCell) {
                if (data.discount_type === 'percent') discCell.textContent = data.discount_value + '%';
                else if (data.discount_type === 'amount') discCell.textContent = '₹ ' + parseFloat(data.discount_value).toFixed(2);
                else discCell.innerHTML = '<span class="text-muted">—</span>';
            }
            if (gstCell) gstCell.textContent = '₹ ' + parseFloat(data.total_gst).toFixed(2);
            if (netCell) netCell.innerHTML = '<strong>₹ ' + parseFloat(data.net_total).toFixed(2) + '</strong>';
            if (recCell) recCell.textContent = '₹ ' + parseFloat(data.received_amount).toFixed(2);
            if (balCell) {
                const span = balCell.querySelector('span');
                if (span) {
                    span.textContent = '₹ ' + parseFloat(data.balance_amount).toFixed(2);
                    span.style.color = data.balance_amount > 0 ? 'var(--danger)' : 'var(--success)';
                }
            }
            // If invoice was draft, update badge and action buttons to reflect final status
            if (data.was_draft) {
                const badgeEl = _pmRow.querySelector('.badge');
                if (badgeEl) {
                    badgeEl.className = 'badge badge-success';
                    badgeEl.textContent = 'Final';
                }
                const actEl = _pmRow.querySelector('.action-links');
                if (actEl) {
                    const invId = document.getElementById('pm_id').value;
                    const baseUrl = '<?= BASE_URL ?>';
                    actEl.innerHTML =
                        `<a href="${baseUrl}/sales/view.php?id=${invId}" class="action-btn view" title="View"><i class="fas fa-eye"></i></a>` +
                        `<a href="javascript:void(0)" onclick="openPrintModal('sales',${invId},'invoice','thermal')" class="action-btn print" title="Print Thermal"><i class="fas fa-print"></i></a>` +
                        `<a href="javascript:void(0)" onclick="openPaymentModal(${invId},'${document.getElementById('pm_invoice_no').textContent}',${_pmGross},${_pmRoundOff},'${data.discount_type}',${data.discount_value},${data.received_amount})" class="action-btn" style="color:var(--success);" title="Update Payment"><i class="fas fa-rupee-sign"></i></a>` +
                        `<a href="${baseUrl}/sales_return/create.php?invoice_id=${invId}" class="action-btn return" title="Sales Return"><i class="fas fa-undo"></i></a>`;
                }
            }
        }
        closePaymentModal();
    })
    .catch(() => { errEl.textContent = 'Server error. Try again.'; errEl.style.display = 'block'; });
}
</script>

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