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

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

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

$master_id = (int)($_GET['master_id'] ?? 0);
if ($master_id <= 0) die('Invalid ID');

$master = $conn->query("
    SELECT mi.*, c.name AS client_name
    FROM master_invoices mi
    JOIN clients c ON c.id = mi.client_id
    WHERE mi.id = $master_id AND mi.status = 'final'
")->fetch_assoc();
if (!$master) die('Master invoice not found or not finalized.');

// Load all final company invoices linked to this master
$invoices = $conn->query("
    SELECT si.id, si.invoice_no, cm.company_name
    FROM sales_invoices si
    JOIN company_master cm ON cm.id = si.company_id
    WHERE si.master_invoice_id = $master_id AND si.status = 'final'
    ORDER BY si.id ASC
");

$companyGroups = [];
while ($inv = $invoices->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
        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 = {$inv['id']}
        HAVING balance_qty > 0
    ");
    $rows = [];
    while ($row = $items->fetch_assoc()) $rows[] = $row;
    if (!empty($rows)) {
        $companyGroups[] = [
            'invoice_id'   => $inv['id'],
            'invoice_no'   => $inv['invoice_no'],
            'company_name' => $inv['company_name'],
            'items'        => $rows,
        ];
    }
}

if (empty($companyGroups)) die('No returnable items found for this master invoice.');
?>

<div class="page-header">
    <h2><i class="fas fa-rotate-left" style="color:var(--primary);margin-right:8px;"></i>Master Sales Return</h2>
    <a href="../master_sales/view.php?id=<?= $master_id ?>" class="btn btn-secondary">
        <i class="fas fa-arrow-left"></i> Back
    </a>
</div>

<!-- Master Info -->
<div class="panel" style="margin-bottom:16px;">
    <div class="panel-body">
        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:16px;">
            <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:15px;font-weight:700;"><?= htmlspecialchars($master['master_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($master['client_name']) ?></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_master.php" id="returnForm">
    <input type="hidden" name="master_id"   value="<?= $master_id ?>">
    <input type="hidden" name="return_date" id="return_date_hidden" value="<?= date('Y-m-d') ?>">

    <?php foreach ($companyGroups as $group): ?>
    <!-- Hidden: tie each item to its sales_invoice_id -->
    <?php foreach ($group['items'] as $item): ?>
    <input type="hidden" name="item_invoice[<?= $item['sales_item_id'] ?>]" value="<?= $group['invoice_id'] ?>">
    <?php endforeach; ?>

    <div class="panel" style="margin-bottom:16px;border-left:4px solid var(--primary);">
        <div class="panel-header">
            <span class="panel-title"><?= htmlspecialchars($group['company_name']) ?></span>
            <span style="font-size:13px;color:var(--text-secondary);margin-left:10px;">
                <?= htmlspecialchars($group['invoice_no']) ?>
            </span>
        </div>
        <div style="overflow-x:auto;">
            <table>
                <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 foreach ($group['items'] as $row): ?>
                <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="<?= $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 endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endforeach; ?>

    <!-- Grand Total -->
    <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> Save Draft
        </button>
        <button type="submit" name="action" value="final" class="btn btn-success"
                onclick="return confirm('Finalize return and restore stock for all companies?')">
            <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 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();
});
</script>

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