<?php
require_once '../includes/auth.php';
require_once '../db.php';

requirePermission('master_sales', 'edit', BASE_URL . '/dashboard.php');

require_once '../includes/header.php';
require_once '../includes/sidebar.php';

$return_id = (int)($_GET['id'] ?? 0);
if ($return_id <= 0) die('Invalid Return');

$sr = $conn->query("
    SELECT sr.*, si.invoice_no, si.master_invoice_id, mi.master_no, cm.company_name
    FROM sales_returns sr
    JOIN sales_invoices si ON si.id = sr.sales_invoice_id
    JOIN master_invoices mi ON mi.id = si.master_invoice_id
    JOIN company_master cm ON cm.id = sr.company_id
    WHERE sr.id = $return_id
      AND si.master_invoice_id IS NOT NULL
")->fetch_assoc();
if (!$sr) die('Return not found.');

if ($sr['status'] === 'final') {
    header("Location: view.php?id=$return_id"); exit;
}

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

$items = $conn->query("
    SELECT si.id AS sales_item_id, p.name AS product_name, si.batch_no, si.sold_qty,
           IFNULL(v.total_returned_qty, 0) AS returned_qty,
           (si.sold_qty - IFNULL(v.total_returned_qty, 0)) AS balance_qty,
           si.selling_price_incl, si.gst_percent,
           sri.return_qty AS current_return_qty
    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
    LEFT JOIN sales_return_items sri
        ON sri.sales_item_id = si.id
       AND sri.sales_return_id = $return_id
    WHERE si.sales_invoice_id = {$sr['sales_invoice_id']}
");
?>

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

<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;">Credit Note No</div>
                <div style="font-size:15px;font-weight:700;"><?= htmlspecialchars($sr['return_no']) ?></div>
            </div>
            <div>
                <div style="font-size:11px;font-weight:700;text-transform:uppercase;color:var(--text-muted);margin-bottom:4px;">Master Ref</div>
                <div style="font-size:14px;font-weight:600;"><?= htmlspecialchars($sr['master_no']) ?></div>
            </div>
            <div>
                <div style="font-size:11px;font-weight:700;text-transform:uppercase;color:var(--text-muted);margin-bottom:4px;">Company</div>
                <div style="font-size:14px;"><?= htmlspecialchars($sr['company_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:14px;"><?= htmlspecialchars($sr['invoice_no']) ?></div>
            </div>
            <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>
</div>

<form method="post" action="update.php" id="returnForm">
    <input type="hidden" name="sales_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:200px;">
                <label>Return Date <span style="color:var(--danger)">*</span></label>
                <input type="date" name="return_date" value="<?= htmlspecialchars($sr['return_date']) ?>" required>
            </div>
        </div>
    </div>

    <div class="panel" style="margin-bottom:16px;">
        <div class="panel-header"><span class="panel-title">Items</span></div>
        <div style="overflow-x:auto;">
            <table id="returnTable">
                <thead>
                    <tr>
                        <th>Product</th>
                        <th>Batch</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 while ($row = $items->fetch_assoc()):
                    $maxReturn = $row['balance_qty'] + ($row['current_return_qty'] ?? 0);
                ?>
                <tr class="returnRow">
                    <td><strong><?= htmlspecialchars($row['product_name']) ?></strong></td>
                    <td style="font-size:12px;color:var(--text-secondary);"><?= htmlspecialchars($row['batch_no']) ?></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['sales_item_id'] ?>]"
                               class="returnQty" min="0" max="<?= $maxReturn ?>"
                               step="0.01" value="<?= $row['current_return_qty'] ?? 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:260px;">
            <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 grand-total"><span>Total 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> Update Draft
        </button>
        <button type="submit" name="action" value="final" class="btn btn-success"
                onclick="return confirm('Finalize this return and restore stock?')">
            <i class="fas fa-check-circle"></i> Finalize Return
        </button>
    </div>
</form>

<script>
function recalcReturn() {
    let totalTaxable = 0, totalGST = 0, grandTotal = 0;
    document.querySelectorAll('.returnRow').forEach(row => {
        const qtyInput = row.querySelector('.returnQty');
        const qty  = parseFloat(qtyInput.value || 0);
        const rate = parseFloat(row.querySelector('.rate').innerText.replace('₹','').replace(/,/g,'') || 0);
        const gstp = parseFloat(row.querySelector('.gst').innerText || 0);
        const max  = parseFloat(qtyInput.max);
        if (qty > max) qtyInput.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;
    });
    document.getElementById('totalTaxable').innerText = totalTaxable.toFixed(2);
    document.getElementById('totalGST').innerText     = totalGST.toFixed(2);
    document.getElementById('grandTotal').innerText   = grandTotal.toFixed(2);
}
document.addEventListener('input', function(e) {
    if (e.target.classList.contains('returnQty')) recalcReturn();
});
document.addEventListener('DOMContentLoaded', recalcReturn);
</script>

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