<?php
require_once '../includes/auth.php';
requirePermission('purchase_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'] ?? '';

$poList = $conn->query("
    SELECT po.id, po.po_no, v.name AS vendor_name, po.net_amount
    FROM purchase_orders po
    JOIN vendors v ON v.id = po.vendor_id
    WHERE po.status = 'final' AND po.company_id = $cid
    ORDER BY po.id DESC
");
?>

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

<!-- Step 1: Select PO -->
<div class="filter-panel">
    <form method="get" class="filter-form">
        <div class="filter-group" style="flex:1;max-width:400px;">
            <label>Select Purchase Order</label>
            <input type="text" name="po_no" list="po_list" placeholder="Type PO number..."
                   value="<?= htmlspecialchars($_GET['po_no'] ?? '') ?>">
            <datalist id="po_list">
                <?php while($po = $poList->fetch_assoc()): ?>
                <option value="<?= htmlspecialchars($po['po_no']) ?>">
                    <?= htmlspecialchars($po['po_no']) ?> — <?= htmlspecialchars($po['vendor_name']) ?> — &#8377; <?= number_format($po['net_amount'], 2) ?>
                </option>
                <?php endwhile; ?>
            </datalist>
        </div>
        <div class="filter-actions">
            <button type="submit" class="btn btn-primary"><i class="fas fa-arrow-right"></i> Load PO</button>
        </div>
    </form>
</div>

<?php
if (!empty($_GET['po_no'])) {
    $po_no = $conn->real_escape_string($_GET['po_no']);
    $po = $conn->query("
        SELECT po.*, v.name AS vendor_name
        FROM purchase_orders po JOIN vendors v ON v.id = po.vendor_id
        WHERE po.po_no = '$po_no' AND po.status = 'final' AND po.company_id = $cid
    ")->fetch_assoc();

    if (!$po) {
        echo '<div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> Invalid or draft PO selected.</div>';
    } else {
        $items = $conn->query("
            SELECT pi.*, p.name AS product_name
            FROM purchase_items pi JOIN products p ON p.id = pi.product_id
            WHERE pi.purchase_order_id = {$po['id']}
        ");
        $dnNo = 'DN-' . date('Y') . '-' . str_pad(rand(1,9999), 4, '0', STR_PAD_LEFT);
?>

<div class="panel" style="margin-bottom:16px;">
    <div class="panel-header">
        <span class="panel-title">
            <i class="fas fa-file-invoice" style="margin-right:6px;color:var(--primary);"></i>
            PO: <strong><?= htmlspecialchars($po['po_no']) ?></strong>
            &nbsp;—&nbsp; Vendor: <strong><?= htmlspecialchars($po['vendor_name']) ?></strong>
        </span>
    </div>
</div>

<form method="post" action="save.php">
    <input type="hidden" name="return_no" value="<?= $dnNo ?>">
    <input type="hidden" name="purchase_order_id" value="<?= $po['id'] ?>">
    <input type="hidden" name="vendor_id" value="<?= $po['vendor_id'] ?>">

    <div class="panel" style="margin-bottom:16px;">
        <div class="panel-header">
            <span class="panel-title">Return Items</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>
                <thead>
                    <tr>
                        <th style="text-align:center;width:32px;">#</th>
                        <th>Product</th>
                        <th style="text-align:center;">Purchased</th>
                        <th style="text-align:center;">Available</th>
                        <th style="text-align:center;">Return Qty</th>
                        <th style="text-align:right;">Price</th>
                        <th style="text-align:center;">GST %</th>
                        <th style="text-align:right;">Taxable</th>
                        <th style="text-align:right;">GST</th>
                        <th style="text-align:right;">Total</th>
                    </tr>
                </thead>
                <tbody>
                <?php $rowNum = 0; while($row = $items->fetch_assoc()): $rowNum++; ?>
                <tr>
                    <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 style="text-align:center;"><?= $row['quantity'] ?></td>
                    <td style="text-align:center;"><?= $row['available_qty'] ?></td>
                    <td style="text-align:center;">
                        <input type="number" step="0.01" min="0" max="<?= $row['available_qty'] ?>"
                               name="return_qty[<?= $row['id'] ?>]" class="returnQty" value="0"
                               style="width:70px;text-align:center;">
                        <input type="hidden" class="price" value="<?= $row['purchase_price'] ?>">
                        <input type="hidden" class="gstp"  value="<?= $row['gst_percent'] ?>">
                    </td>
                    <td style="text-align:right;">&#8377; <?= number_format($row['purchase_price'], 2) ?></td>
                    <td style="text-align:center;"><?= $row['gst_percent'] ?>%</td>
                    <td class="taxable" style="text-align:right;">0.00</td>
                    <td class="gst" style="text-align:right;">0.00</td>
                    <td class="total" 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 Total</span><span>&#8377; <span id="taxableTotal">0.00</span></span></div>
            <div class="totals-row"><span>GST Total</span><span>&#8377; <span id="gstTotal">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 Payable</span><span>&#8377; <span id="netTotal">0.00</span></span></div>
        </div>
    </div>

    <div style="display:flex;gap:12px;">
        <button type="submit" name="action" value="save" 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 reduce stock?')">
            <i class="fas fa-check-circle"></i> Complete Return
        </button>
    </div>
</form>

<?php }} ?>

<script>
function recalcReturn() {
    let taxableTotal = 0, gstTotal = 0;
    document.querySelectorAll('.returnQty').forEach(function(input) {
        const row = input.closest('tr');
        const qty   = parseFloat(input.value || 0);
        const price = parseFloat(row.querySelector('.price').value || 0);
        const gstp  = parseFloat(row.querySelector('.gstp').value || 0);
        if (qty > parseFloat(input.max)) input.value = input.max;
        const taxable = qty * price;
        const gst = taxable * gstp / 100;
        row.querySelector('.taxable').innerText = taxable.toFixed(2);
        row.querySelector('.gst').innerText = gst.toFixed(2);
        row.querySelector('.total').innerText = (taxable + gst).toFixed(2);
        taxableTotal += taxable; gstTotal += gst;
    });
    const sub = taxableTotal + gstTotal;
    const roundOff = parseFloat(document.getElementById('roundOff')?.value || 0);
    document.getElementById('taxableTotal') && (document.getElementById('taxableTotal').innerText = taxableTotal.toFixed(2));
    document.getElementById('gstTotal') && (document.getElementById('gstTotal').innerText = gstTotal.toFixed(2));
    document.getElementById('subTotal') && (document.getElementById('subTotal').innerText = sub.toFixed(2));
    document.getElementById('netTotal') && (document.getElementById('netTotal').innerText = (sub + 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();
});
recalcReturn();

function filterReturnItems(q) {
    const term = q.trim().toLowerCase();
    document.querySelectorAll('.returnQty').forEach(input => {
        const tr = input.closest('tr');
        const name = (tr.querySelectorAll('td')[1]?.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'; ?>
