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

$return_id = (int)$_GET['id'];

$pr = $conn->query("
    SELECT pr.*, 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 pr.id = $return_id AND pr.company_id = $cid
")->fetch_assoc();

if (!$pr) die("Return not found");
if ($pr['status'] === 'final') die("This return is finalized and cannot be edited.");

$po_id = $pr['purchase_order_id'];

$items = $conn->query("
    SELECT
        pi.id AS purchase_item_id,
        p.name AS product_name,
        pi.batch_no,
        pi.available_qty,
        pi.purchase_price,
        pi.gst_percent,
        IFNULL(pri.id, 0) AS return_item_id,
        IFNULL(pri.return_qty, 0) AS return_qty,
        IFNULL(pri.taxable_amount, 0) AS taxable_amount,
        IFNULL(pri.gst_amount, 0) AS gst_amount,
        IFNULL(pri.total_amount, 0) AS total_amount
    FROM purchase_items pi
    JOIN products p ON p.id = pi.product_id
    LEFT JOIN purchase_return_items pri
        ON pri.purchase_item_id = pi.id
        AND pri.purchase_return_id = $return_id
    WHERE pi.purchase_order_id = $po_id
");
?>

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

<!-- Info Panel -->
<div class="panel" style="margin-bottom:16px;">
    <div class="panel-body">
        <div style="display:flex;gap:32px;flex-wrap:wrap;">
            <div>
                <div style="font-size:11px;font-weight:700;text-transform:uppercase;color:var(--text-muted);margin-bottom:3px;">Debit Note</div>
                <div style="font-size:15px;font-weight:700;"><?= htmlspecialchars($pr['return_no']) ?></div>
            </div>
            <div>
                <div style="font-size:11px;font-weight:700;text-transform:uppercase;color:var(--text-muted);margin-bottom:3px;">Purchase Order</div>
                <div style="font-size:15px;font-weight:600;"><?= htmlspecialchars($pr['po_no']) ?></div>
            </div>
            <div>
                <div style="font-size:11px;font-weight:700;text-transform:uppercase;color:var(--text-muted);margin-bottom:3px;">Vendor</div>
                <div style="font-size:15px;font-weight:600;"><?= htmlspecialchars($pr['vendor_name']) ?></div>
            </div>
        </div>
    </div>
</div>

<form method="post" action="update.php">
    <input type="hidden" name="return_id" value="<?= $return_id ?>">

    <div class="panel" style="margin-bottom:16px;">
        <div class="panel-header"><span class="panel-title">Return Details</span></div>
        <div class="panel-body">
            <div class="form-group" style="max-width:400px;">
                <label>Reason</label>
                <input type="text" name="reason" value="<?= htmlspecialchars($pr['reason']) ?>">
            </div>
        </div>
    </div>

    <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 id="returnTable">
                <thead>
                    <tr>
                        <th style="text-align:center;width:32px;">#</th>
                        <th>Product</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++;
                    $maxQty = $row['available_qty'] + $row['return_qty'];
                ?>
                <tr>
                    <td style="text-align:center;color:var(--text-muted);font-size:12px;"><?= $rowNum ?></td>
                    <td><strong><?= htmlspecialchars($row['product_name']) ?></strong></td>
                    <td style="text-align:center;"><?= $maxQty ?></td>
                    <td style="text-align:center;">
                        <input type="number" step="0.01" min="0" max="<?= $maxQty ?>"
                               name="return_qty[<?= $row['purchase_item_id'] ?>]"
                               class="returnQty" value="<?= $row['return_qty'] ?>"
                               style="width:80px;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;"><?= number_format($row['taxable_amount'],2) ?></td>
                    <td class="gst" style="text-align:right;"><?= number_format($row['gst_amount'],2) ?></td>
                    <td class="total" style="text-align:right;font-weight:700;"><?= number_format($row['total_amount'],2) ?></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="taxableTotal"><?= number_format($pr['total_amount'],2) ?></span></span></div>
            <div class="totals-row"><span>GST</span><span>&#8377; <span id="gstTotal"><?= number_format($pr['gst_amount'],2) ?></span></span></div>
            <div class="totals-row"><span>Sub Total</span><span>&#8377; <span id="subTotal"><?= number_format($pr['total_amount'] + $pr['gst_amount'],2) ?></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="<?= number_format($pr['round_off'] ?? 0, 2, '.', '') ?>"
                           style="width:80px;text-align:right;padding:2px 6px;font-size:13px;"
                           oninput="recalcReturnEdit()">
                    <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"><?= number_format($pr['net_amount'],2) ?></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 and reduce stock?')">
            <i class="fas fa-check-circle"></i> Complete Return
        </button>
    </div>
</form>

<script>
function recalcReturnEdit(){
    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);
        const taxable = qty * price;
        const gst = taxable * gstp / 100;
        const total = taxable + gst;
        row.querySelector('.taxable').innerText = taxable.toFixed(2);
        row.querySelector('.gst').innerText = gst.toFixed(2);
        row.querySelector('.total').innerText = total.toFixed(2);
        taxableTotal += taxable;
        gstTotal += gst;
    });
    const sub = taxableTotal + gstTotal;
    const roundOff = parseFloat(document.getElementById('roundOff')?.value || 0);
    document.getElementById('taxableTotal').innerText = taxableTotal.toFixed(2);
    document.getElementById('gstTotal').innerText = gstTotal.toFixed(2);
    document.getElementById('subTotal').innerText = sub.toFixed(2);
    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);
    recalcReturnEdit();
}

document.addEventListener('input', function(e){
    if(e.target.classList.contains('returnQty') || e.target.id === 'roundOff'){ recalcReturnEdit(); }
});
recalcReturnEdit();

function filterReturnItems(q) {
    const term = q.trim().toLowerCase();
    document.querySelectorAll('#returnTable tbody tr').forEach(tr => {
        const name = (tr.querySelector('td:first-child')?.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'; ?>
