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

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

$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 sr.company_id = $filterCo" : "";

$sql = "
    SELECT sr.id, sr.return_no, sr.return_date, sr.status, sr.total_amount,
           inv.invoice_no, c.name AS client_name,
           SUM(sri.return_qty) AS total_qty
    FROM sales_returns sr
    JOIN sales_invoices inv ON inv.id = sr.sales_invoice_id
    JOIN clients c ON c.id = sr.client_id
    LEFT JOIN sales_return_items sri ON sri.sales_return_id = sr.id
    WHERE 1=1 $coWhere";
if ($search !== '') {
    $s = $conn->real_escape_string($search);
    $sql .= " AND (sr.return_no LIKE '%$s%' OR inv.invoice_no LIKE '%$s%' OR c.name LIKE '%$s%')";
}
$sql .= " GROUP BY sr.id ORDER BY sr.return_date DESC";
$result = $conn->query($sql);
?>

<div class="page-header">
    <h2><i class="fas fa-rotate-left" style="color:var(--primary);margin-right:8px;"></i>Sales Returns</h2>
    <button type="button" class="btn btn-primary" onclick="var p=document.getElementById('newReturnPanel');p.style.display=p.style.display==='none'?'block':'none';if(p.style.display==='block'){document.getElementById('invoiceSearch').focus();}"><i class="fas fa-plus" style="margin-right:6px;"></i>New Sales Return</button>
</div>

<!-- ── Create New Return ── -->
<div id="newReturnPanel" class="panel" style="margin-bottom:20px;display:<?= !empty($_GET['inv_search']) ? 'block' : 'none' ?>;">
    <div class="panel-header">
        <span class="panel-title"><i class="fas fa-plus-circle" style="margin-right:6px;"></i>Create New Sales Return</span>
    </div>
    <div class="panel-body">
        <form method="get" action="index.php" style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
            <input type="hidden" name="tab" value="new">
            <input type="text" id="invoiceSearch" name="inv_search" placeholder="Search invoice no. or client name..."
                   value="<?= htmlspecialchars($_GET['inv_search'] ?? '') ?>"
                   style="font-size:13px;padding:7px 12px;border:1px solid var(--border);border-radius:6px;width:300px;">
            <button type="submit" class="btn btn-primary btn-sm"><i class="fas fa-search" style="margin-right:4px;"></i>Search</button>
            <?php if (!empty($_GET['inv_search'])): ?>
            <a href="index.php" class="btn btn-secondary btn-sm">Clear</a>
            <?php endif; ?>
        </form>
        <?php if (!empty($_GET['inv_search'])):
            $invS = $conn->real_escape_string(trim($_GET['inv_search']));
            $invResults = $conn->query("
                SELECT si.id, si.invoice_no, si.invoice_date, si.net_total,
                       c.name AS client_name
                FROM sales_invoices si
                JOIN clients c ON c.id = si.client_id
                WHERE si.status = 'final' AND si.company_id = $cid
                  AND (si.invoice_no LIKE '%$invS%' OR c.name LIKE '%$invS%')
                ORDER BY si.invoice_date DESC LIMIT 20
            ");
            if ($invResults && $invResults->num_rows > 0): ?>
        <table style="margin-top:12px;width:100%;border-collapse:collapse;font-size:13px;">
            <thead>
                <tr style="background:#f1f5f9;">
                    <th style="padding:6px 10px;text-align:left;font-size:11px;text-transform:uppercase;letter-spacing:.04em;">Invoice No</th>
                    <th style="padding:6px 10px;text-align:left;font-size:11px;text-transform:uppercase;letter-spacing:.04em;">Date</th>
                    <th style="padding:6px 10px;text-align:left;font-size:11px;text-transform:uppercase;letter-spacing:.04em;">Client</th>
                    <th style="padding:6px 10px;text-align:right;font-size:11px;text-transform:uppercase;letter-spacing:.04em;">Net Total</th>
                    <th style="padding:6px 10px;text-align:center;font-size:11px;text-transform:uppercase;letter-spacing:.04em;">Action</th>
                </tr>
            </thead>
            <tbody>
            <?php while ($inv = $invResults->fetch_assoc()): ?>
                <tr style="border-bottom:1px solid #e2e8f0;">
                    <td style="padding:7px 10px;"><?= htmlspecialchars($inv['invoice_no']) ?></td>
                    <td style="padding:7px 10px;"><?= htmlspecialchars($inv['invoice_date']) ?></td>
                    <td style="padding:7px 10px;"><?= htmlspecialchars($inv['client_name']) ?></td>
                    <td style="padding:7px 10px;text-align:right;">&#8377;<?= number_format($inv['net_total'], 2) ?></td>
                    <td style="padding:7px 10px;text-align:center;">
                        <a href="create.php?invoice_id=<?= $inv['id'] ?>" class="btn btn-success btn-sm"><i class="fas fa-undo" style="margin-right:4px;"></i>Create Return</a>
                    </td>
                </tr>
            <?php endwhile; ?>
            </tbody>
        </table>
        <?php else: ?>
        <p style="margin-top:12px;color:var(--text-muted);font-size:13px;">No final invoices found for "<?= htmlspecialchars($_GET['inv_search']) ?>".</p>
        <?php endif; endif; ?>
    </div>
</div>

<?php if (isset($_GET['deleted'])): ?>
<div class="alert alert-success" style="margin-bottom:16px;">
    <i class="fas fa-check-circle"></i> Sales return deleted successfully.
</div>
<?php endif; ?>

<div class="panel">
    <div class="panel-header">
        <span class="panel-title">Credit Note Register</span>
        <form method="get" class="search-bar" style="display:flex;gap:6px;align-items:center;flex-wrap:wrap;">
            <?php if ($userRole === 'admin' && $companies): ?>
            <select name="co" onchange="this.form.submit()" style="font-size:13px;padding:5px 8px;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 endif; ?>
            <input type="text" name="search" placeholder="Search credit note / invoice / client..."
                   value="<?= htmlspecialchars($search) ?>">
            <button type="submit" class="btn btn-primary btn-sm"><i class="fas fa-search"></i></button>
            <?php if ($search || ($userRole === 'admin' && $filterCo != $cid)): ?>
            <a href="index.php" class="btn btn-secondary btn-sm">Clear</a>
            <?php endif; ?>
        </form>
        <select id="pgPerPage" style="padding:5px 8px;font-size:12px;border:1px solid var(--border);border-radius:6px;flex-shrink:0;width:auto;margin-left:auto;">
            <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 style="overflow-x:auto;">
        <table id="mainTable">
            <thead>
                <tr>
                    <th>Credit Note</th>
                    <th>Date</th>
                    <th>Invoice No</th>
                    <th>Client</th>
                    <th style="text-align:right;">Qty</th>
                    <th style="text-align:right;">Amount</th>
                    <th>Status</th>
                    <th style="text-align:center;">Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php while ($row = $result->fetch_assoc()):
                $ds = strtolower($row['return_no'].' '.$row['invoice_no'].' '.$row['client_name'].' '.$row['return_date'].' '.$row['status']);
            ?>
            <tr data-search="<?= htmlspecialchars($ds) ?>">
                <td><strong><?= htmlspecialchars($row['return_no']) ?></strong></td>
                <td><?= date('d-m-Y', strtotime($row['return_date'])) ?></td>
                <td style="color:var(--text-secondary);"><?= htmlspecialchars($row['invoice_no']) ?></td>
                <td><?= htmlspecialchars($row['client_name']) ?></td>
                <td style="text-align:right;"><?= number_format($row['total_qty'], 0) ?></td>
                <td style="text-align:right;"><strong>&#8377; <?= number_format($row['total_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>
                        <a href="delete.php?id=<?= $row['id'] ?>"
                           onclick="return confirm('Delete this draft return?')"
                           class="action-btn delete" title="Delete">
                            <i class="fas fa-trash-alt"></i>
                        </a>
                        <?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; ?>
            </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 perPageEl=document.getElementById('pgPerPage');
    const barEl=document.getElementById('pgBar');
    let page=1;
    function render(){
        const pp=parseInt(perPageEl?.value||25);
        const total=rows.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;
        rows.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();};
    perPageEl?.addEventListener('change',function(){page=1;render();});
    render();
})();
</script>

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