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

$prefRow = $conn->query("SELECT invoice_prefix FROM company_master WHERE id = $cid LIMIT 1")->fetch_assoc();
$companyPrefix = $prefRow['invoice_prefix'] ?? '';

$invoice_id = (int)($_GET['invoice_id'] ?? 0);
if ($invoice_id <= 0) die("Invalid Invoice");
$inv = $conn->query("SELECT * FROM sales_invoices WHERE id = $invoice_id AND company_id = $cid")->fetch_assoc();
if (!$inv) die("Invoice not found");
if ($inv['status'] !== 'final') die("Sales Return allowed only for Final Invoices.");

$client = $conn->query("SELECT * FROM clients WHERE id = {$inv['client_id']}")->fetch_assoc();

$items = $conn->query("
    SELECT si.product_id, p.name AS product_name,
           SUM(si.sold_qty) AS sold_qty,
           SUM(IFNULL(v.total_returned_qty, 0)) AS returned_qty,
           SUM(si.sold_qty - IFNULL(v.total_returned_qty, 0)) AS balance_qty,
           MAX(si.selling_price_incl) AS selling_price_incl,
           MAX(si.gst_percent) AS gst_percent
    FROM sales_items si
    JOIN products p ON p.id = si.product_id
    LEFT JOIN v_sales_returned_qty v ON v.sales_item_id = si.id
    WHERE si.sales_invoice_id = $invoice_id
    GROUP BY si.product_id, p.name
    HAVING SUM(si.sold_qty) > 0
");
?>

<div class="page-header">
    <h2><i class="fas fa-rotate-left" style="color:var(--primary);margin-right:8px;"></i>Sales Return (Credit Note)</h2>
    <a href="../sales/index.php" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Back</a>
</div>

<!-- Invoice Info -->
<div class="panel" style="margin-bottom:16px;">
    <div class="panel-body">
        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:16px;">
            <div>
                <div style="font-size:11px;font-weight:700;text-transform:uppercase;color:var(--text-muted);margin-bottom:4px;">Client</div>
                <div style="font-size:15px;font-weight:700;"><?= htmlspecialchars($client['name']) ?></div>
            </div>
            <div>
                <div style="font-size:11px;font-weight:700;text-transform:uppercase;color:var(--text-muted);margin-bottom:4px;">Invoice No</div>
                <div style="font-size:15px;font-weight:600;"><?= htmlspecialchars($inv['invoice_no']) ?></div>
            </div>
            <div>
                <div style="font-size:11px;font-weight:700;text-transform:uppercase;color:var(--text-muted);margin-bottom:4px;">Return Date <span style="color:var(--danger)">*</span></div>
                <input type="date" id="return_date_display" value="<?= date('Y-m-d') ?>"
                       style="font-size:14px;max-width:180px;padding:7px 10px;">
            </div>
        </div>
    </div>
</div>

<form method="post" action="save.php" id="returnForm">
    <input type="hidden" name="sales_invoice_id" value="<?= $invoice_id ?>">
    <input type="hidden" name="return_date" id="return_date_hidden" value="<?= date('Y-m-d') ?>">

    <div class="panel" style="margin-bottom:16px;">
        <div class="panel-header">
            <span class="panel-title">Items to Return</span>
            <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="itemSearch" placeholder="Search product..."
                       oninput="filterReturnItems(this.value)"
                       style="padding:5px 8px 5px 28px;font-size:12px;border:1px solid var(--border);border-radius:6px;width:180px;">
            </div>
        </div>
        <div class="items-scroll-wrap">
            <table id="returnTable">
                <thead>
                    <tr>
                        <th style="text-align:center;width:32px;">#</th>
                        <th>Product</th>
                        <th style="text-align:center;">Sold</th>
                        <th style="text-align:center;">Returned</th>
                        <th style="text-align:center;">Balance</th>
                        <th style="text-align:center;">Return Now</th>
                        <th style="text-align:right;">Rate (Incl GST)</th>
                        <th style="text-align:center;">GST%</th>
                        <th style="text-align:right;">Line Total</th>
                    </tr>
                </thead>
                <tbody>
                <?php $rowNum = 0; while($row = $items->fetch_assoc()): $rowNum++; ?>
                <tr class="returnRow">
                    <td style="text-align:center;color:var(--text-muted);font-size:12px;"><?= $rowNum ?></td>
                    <td>
                        <span style="font-family:monospace;font-size:11px;background:#eff6ff;color:#2563eb;padding:1px 5px;border-radius:3px;margin-right:5px;"><?= htmlspecialchars($companyPrefix . '-' . $row['product_id']) ?></span>
                        <strong><?= htmlspecialchars($row['product_name']) ?></strong>
                    </td>
                    <td class="sold" style="text-align:center;"><?= $row['sold_qty'] ?></td>
                    <td class="returned" style="text-align:center;color:var(--text-muted);"><?= $row['returned_qty'] ?></td>
                    <td class="balance" style="text-align:center;font-weight:600;"><?= $row['balance_qty'] ?></td>
                    <td style="text-align:center;">
                        <input type="number" name="return_qty[<?= $row['product_id'] ?>]"
                               class="returnQty" min="0" max="<?= $row['balance_qty'] ?>"
                               step="0.01" value="0" style="width:70px;text-align:center;">
                    </td>
                    <td class="rate" style="text-align:right;">&#8377; <?= number_format($row['selling_price_incl'], 2) ?></td>
                    <td class="gst" style="text-align:center;"><?= $row['gst_percent'] ?></td>
                    <td class="lineTotal" style="text-align:right;font-weight:700;">0.00</td>
                </tr>
                <?php endwhile; ?>
                </tbody>
            </table>
        </div>
    </div>

    <div style="display:flex;justify-content:flex-end;margin-bottom:16px;">
        <div class="totals-box" style="min-width:280px;">
            <div class="totals-row"><span>Taxable</span><span>&#8377; <span id="totalTaxable">0.00</span></span></div>
            <div class="totals-row"><span>GST</span><span>&#8377; <span id="totalGST">0.00</span></span></div>
            <div class="totals-row"><span>Sub Total</span><span>&#8377; <span id="subTotal">0.00</span></span></div>
            <div class="totals-row">
                <span>Round Off</span>
                <span style="display:flex;align-items:center;gap:4px;justify-content:flex-end;">
                    <input type="number" step="0.01" name="round_off" id="roundOff" value="0.00"
                           style="width:80px;text-align:right;padding:2px 6px;font-size:13px;"
                           oninput="recalcReturn()">
                    <button type="button" onclick="autoRound()" class="btn btn-outline btn-sm"
                            style="padding:2px 8px;font-size:11px;" title="Auto">Auto</button>
                </span>
            </div>
            <div class="totals-row grand-total"><span>Net Return</span><span>&#8377; <span id="grandTotal">0.00</span></span></div>
        </div>
    </div>

    <div style="display:flex;gap:12px;">
        <button type="submit" name="action" value="draft" class="btn btn-secondary">
            <i class="fas fa-save"></i> Save Draft
        </button>
        <button type="submit" name="action" value="final" class="btn btn-success"
                onclick="return confirm('Finalize return and add stock back?')">
            <i class="fas fa-check-circle"></i> Finalize Return
        </button>
    </div>
</form>

<script>
document.getElementById('return_date_display').addEventListener('change', function() {
    document.getElementById('return_date_hidden').value = this.value;
});

function recalcReturn() {
    let totalTaxable = 0, totalGST = 0, grandTotal = 0;
    document.querySelectorAll('.returnRow').forEach(row => {
        const qty   = parseFloat(row.querySelector('.returnQty').value || 0);
        const rate  = parseFloat(row.querySelector('.rate').innerText.replace('₹','').replace(/,/g,'') || 0);
        const gstp  = parseFloat(row.querySelector('.gst').innerText || 0);
        const max   = parseFloat(row.querySelector('.returnQty').max);
        if (qty > max) row.querySelector('.returnQty').value = max;
        const lineTotal = qty * rate;
        const base = lineTotal / (1 + gstp / 100);
        const gst  = lineTotal - base;
        row.querySelector('.lineTotal').innerText = lineTotal.toFixed(2);
        totalTaxable += base; totalGST += gst; grandTotal += lineTotal;
    });
    const roundOff = parseFloat(document.getElementById('roundOff')?.value || 0);
    document.getElementById('totalTaxable').innerText = totalTaxable.toFixed(2);
    document.getElementById('totalGST').innerText = totalGST.toFixed(2);
    document.getElementById('subTotal').innerText = grandTotal.toFixed(2);
    document.getElementById('grandTotal').innerText = (grandTotal + roundOff).toFixed(2);
}

function autoRound() {
    const sub = parseFloat(document.getElementById('subTotal').innerText || 0);
    const rounded = Math.round(sub);
    document.getElementById('roundOff').value = (rounded - sub).toFixed(2);
    recalcReturn();
}
document.addEventListener('input', function(e) {
    if (e.target.classList.contains('returnQty')) recalcReturn();
});

function filterReturnItems(q) {
    const term = q.trim().toLowerCase();
    document.querySelectorAll('#returnTable tbody .returnRow').forEach(tr => {
        const name = (tr.querySelector('td:nth-child(2)')?.innerText || '').toLowerCase();
        tr.style.display = (!term || name.includes(term)) ? '' : 'none';
    });
}
</script>

<style>
.items-scroll-wrap { overflow-x:auto; overflow-y:auto; max-height:52vh; }
.items-scroll-wrap thead th { position:sticky; top:0; background:#f1f5f9; z-index:10; box-shadow:0 1px 0 var(--border,#e2e8f0); }
</style>

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