<?php
$count    = $count ?? [];
$lines    = $lines ?? [['product_id' => '', 'system_qty' => '', 'counted_qty' => '', 'notes' => '']];
$warehouses = $warehouses ?? [];
$products = $products ?? [];
$oldLines = old('lines');
if (is_array($oldLines) && count($oldLines) > 0) {
    $lines = $oldLines;
}
?>
<div class="enterprise-settings-fields">
    <div class="enterprise-field">
        <label class="enterprise-field-label">Count Date <span class="text-danger">*</span></label>
        <input type="date" name="count_date" class="form-control" value="<?= esc(old('count_date', $count['count_date'] ?? date('Y-m-d'))) ?>" required>
    </div>
    <div class="enterprise-field">
        <label class="enterprise-field-label">Warehouse <span class="text-danger">*</span></label>
        <select name="warehouse_id" class="form-select" required>
            <option value="">Select warehouse</option>
            <?php foreach ($warehouses as $w): ?>
                <option value="<?= (int) $w['id'] ?>" <?= (int) old('warehouse_id', $count['warehouse_id'] ?? 0) === (int) $w['id'] ? 'selected' : '' ?>>
                    <?= esc($w['name']) ?>
                </option>
            <?php endforeach; ?>
        </select>
    </div>
    <div class="enterprise-field enterprise-field--full">
        <label class="enterprise-field-label">Notes</label>
        <textarea name="notes" class="form-control" rows="2"><?= esc(old('notes', $count['notes'] ?? '')) ?></textarea>
    </div>
</div>

<div class="mt-4">
    <div class="d-flex justify-content-between align-items-center mb-2">
        <h3 class="h6 mb-0">Count Lines</h3>
        <button type="button" class="btn btn-sm btn-outline-secondary" id="addCountLine">
            <i class="fa-solid fa-plus me-1"></i> Add Line
        </button>
    </div>
    <div class="table-responsive">
        <table class="enterprise-data-table" id="countLinesTable">
            <thead>
                <tr>
                    <th>Product</th>
                    <th style="width:120px;">System Qty</th>
                    <th style="width:120px;">Counted Qty</th>
                    <th>Notes</th>
                    <th style="width:50px;"></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($lines as $i => $line): ?>
                    <tr>
                        <td>
                            <select name="lines[<?= $i ?>][product_id]" class="form-select form-select-sm">
                                <option value="">Select product</option>
                                <?php foreach ($products as $p): ?>
                                    <option value="<?= (int) $p['id'] ?>" <?= (int) ($line['product_id'] ?? 0) === (int) $p['id'] ? 'selected' : '' ?>>
                                        <?= esc($p['name']) ?> (<?= esc($p['sku']) ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                        <td>
                            <input type="number" step="0.001" name="lines[<?= $i ?>][system_qty]" class="form-control form-control-sm"
                                   value="<?= esc($line['system_qty'] ?? '') ?>" placeholder="Auto">
                        </td>
                        <td>
                            <input type="number" step="0.001" name="lines[<?= $i ?>][counted_qty]" class="form-control form-control-sm"
                                   value="<?= esc($line['counted_qty'] ?? '') ?>">
                        </td>
                        <td>
                            <input type="text" name="lines[<?= $i ?>][notes]" class="form-control form-control-sm"
                                   value="<?= esc($line['notes'] ?? '') ?>">
                        </td>
                        <td>
                            <button type="button" class="btn btn-sm btn-outline-danger remove-line"><i class="fa-solid fa-trash"></i></button>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
(function () {
    const table = document.getElementById('countLinesTable');
    if (!table) return;
    const tbody = table.querySelector('tbody');
    const addBtn = document.getElementById('addCountLine');
    const productOptions = <?= json_encode(array_map(static fn ($p) => [
        'id' => (int) $p['id'],
        'label' => $p['name'] . ' (' . $p['sku'] . ')',
    ], $products), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) ?>;

    function nextIndex() {
        return tbody.querySelectorAll('tr').length;
    }

    function rowHtml(index) {
        let opts = '<option value="">Select product</option>';
        productOptions.forEach(function (p) {
            opts += '<option value="' + p.id + '">' + p.label.replace(/</g, '&lt;') + '</option>';
        });
        return '<tr>' +
            '<td><select name="lines[' + index + '][product_id]" class="form-select form-select-sm">' + opts + '</select></td>' +
            '<td><input type="number" step="0.001" name="lines[' + index + '][system_qty]" class="form-control form-control-sm" placeholder="Auto"></td>' +
            '<td><input type="number" step="0.001" name="lines[' + index + '][counted_qty]" class="form-control form-control-sm"></td>' +
            '<td><input type="text" name="lines[' + index + '][notes]" class="form-control form-control-sm"></td>' +
            '<td><button type="button" class="btn btn-sm btn-outline-danger remove-line"><i class="fa-solid fa-trash"></i></button></td>' +
            '</tr>';
    }

    addBtn.addEventListener('click', function () {
        tbody.insertAdjacentHTML('beforeend', rowHtml(nextIndex()));
    });

    tbody.addEventListener('click', function (e) {
        const btn = e.target.closest('.remove-line');
        if (!btn) return;
        const rows = tbody.querySelectorAll('tr');
        if (rows.length <= 1) return;
        btn.closest('tr').remove();
    });
})();
</script>
