<?php
require_once '../includes/auth.php';
requirePermission('purchase_returns', '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 pr.company_id = $filterCo" : "";

$result = $conn->query("
    SELECT pr.id, pr.return_no, pr.return_date, pr.total_amount, pr.gst_amount,
           pr.net_amount, pr.status, po.po_no, v.name AS vendor_name
    FROM purchase_returns pr
    JOIN purchase_orders po ON po.id = pr.purchase_order_id
    JOIN vendors v ON v.id = pr.vendor_id
    WHERE 1=1 $coWhere
    ORDER BY pr.id DESC
");
?>

<div class="page-header">
    <h2><i class="fas fa-undo-alt" style="color:var(--primary);margin-right:8px;"></i>Purchase Returns</h2>
    <a href="create.php" class="btn btn-primary"><i class="fas fa-plus"></i> Create Return</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 != $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">Debit Notes</span>
        <div style="display:flex;gap:8px;align-items:center;">
            <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 return, PO, vendor..."
                       style="padding:5px 8px 5px 28px;font-size:12px;border:1px solid var(--border);border-radius:6px;width:200px;">
            </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>Return No</th>
                    <th>Date</th>
                    <th>PO No</th>
                    <th>Vendor</th>
                    <th style="text-align:right;">Taxable</th>
                    <th style="text-align:right;">GST</th>
                    <th style="text-align:right;">Net Total</th>
                    <th>Status</th>
                    <th style="text-align:center;">Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php if ($result->num_rows > 0): while ($row = $result->fetch_assoc()):
                $ds = strtolower($row['return_no'].' '.$row['po_no'].' '.$row['vendor_name'].' '.$row['return_date'].' '.$row['status']);
            ?>
            <tr data-search="<?= htmlspecialchars($ds) ?>">
                <td><strong><?= htmlspecialchars($row['return_no']) ?></strong></td>
                <td><?= htmlspecialchars($row['return_date']) ?></td>
                <td style="color:var(--text-secondary);"><?= htmlspecialchars($row['po_no']) ?></td>
                <td><?= htmlspecialchars($row['vendor_name']) ?></td>
                <td style="text-align:right;">&#8377; <?= number_format($row['total_amount'], 2) ?></td>
                <td style="text-align:right;">&#8377; <?= number_format($row['gst_amount'], 2) ?></td>
                <td style="text-align:right;"><strong>&#8377; <?= number_format($row['net_amount'], 2) ?></strong></td>
                <td>
                    <?php $s = strtolower($row['status']); ?>
                    <span class="badge <?= $s === 'final' ? 'badge-success' : 'badge-warning' ?>"><?= 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>
                        <?php else: ?>
                        <span class="badge badge-gray" style="font-size:11px;">Locked</span>
                        <?php endif; ?>
                        <a href="view.php?id=<?= $row['id'] ?>" class="action-btn view" title="View">
                            <i class="fas fa-eye"></i>
                        </a>
                    </div>
                </td>
            </tr>
            <?php endwhile; else: ?>
            <tr><td colspan="9" 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 purchase returns found.
            </td></tr>
            <?php endif; ?>
            </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>
(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 q?rows.filter(r=>(r.dataset.search||'').includes(q)):rows;}
    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>

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