<?= $this->extend('layout/management_layout') ?>
<?= $this->section('content') ?>

<div class="container mt-4">
    <h2>Edit Expense #<?= esc($expense['id']) ?></h2>
    <?php if (!empty($errors)): ?>
        <div class="alert alert-danger"><?= implode('<br>', array_map('esc', $errors)) ?></div>
    <?php endif; ?>

    <form method="post" action="<?= site_url('expenses/update/' . $expense['id']) ?>" enctype="multipart/form-data">
        <?= csrf_field() ?>

        <div class="mb-3">
            <label>Category</label>
            <select name="category" class="form-control" required>
                <?php foreach (['Expense', 'Purchase', 'Reimbursement', 'Donation'] as $opt): ?>
                    <option value="<?= $opt ?>" <?= $expense['category'] === $opt ? 'selected' : '' ?>>
                        <?= $opt === 'Donation' ? 'Donation (non-reimbursable)' : $opt ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <div class="form-text text-muted">Donation entries are tracked as expenses but will not move through reimbursement batches.</div>
        </div>

        <div class="mb-3">
            <label>Amount</label>
            <input type="number" step="0.01" name="amount" class="form-control"
                value="<?= old('amount', $expense['amount']) ?>" required>
        </div>

        <div class="mb-3">
            <label>Vendor</label>
            <?php $currentRetailor = old('retailor', $expense['retailor'] ?? ''); ?>
            <select id="retailor_select" class="form-control">
                <option value="">-- Select Vendor --</option>
                <?php foreach (($retailors ?? []) as $r): ?>
                    <option value="<?= esc($r) ?>" <?= ($currentRetailor === $r) ? 'selected' : '' ?>><?= esc($r) ?></option>
                <?php endforeach; ?>
                <option value="_other" <?= ($currentRetailor && !in_array($currentRetailor, ($retailors ?? []), true)) ? 'selected' : '' ?>>Other</option>
            </select>
            <input type="text" id="retailor_input" name="retailor" class="form-control mt-2" placeholder="Enter retailor"
                   value="<?= esc($currentRetailor) ?>">
        </div>

        <div class="mb-3">
            <label>Purchased By</label>
            <select name="purchased_by" class="form-control" required>
                <?php foreach ($users as $u): ?>
                    <?php $val = $u['id'] . '|' . $u['firstname'] . ' ' . $u['lastname']; ?>
                    <option value="<?= esc($val) ?>" <?= ($expense['purchased_by'] == $u['id'] ? 'selected' : '') ?>>
                        <?= esc($u['firstname'] . ' ' . $u['lastname']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="mb-3">
            <label>Date of Purchase</label>
            <input type="date" name="date_of_purchase" class="form-control"
                value="<?= old('date_of_purchase', $expense['date_of_purchase'] ?? '') ?>">
        </div>

        <div class="mb-3">
            <label>Description</label>
            <textarea name="description" class="form-control"><?= old('description', $expense['description']) ?></textarea>
        </div>

        <div class="mb-3">
            <label>Receipt (optional to replace)</label>
            <?php if (!empty($receipt_url)): ?>
                <div class="mb-2"><a href="<?= esc($receipt_url) ?>" target="_blank">Current receipt</a></div>
            <?php endif; ?>
            <input type="file" name="receipt" class="form-control" accept=".jpg,.jpeg,.png,.webp,.gif,.pdf">
            <?php if (!empty($expense['receipt_path'])): ?>
                <div class="form-check mt-2">
                    <input class="form-check-input" type="checkbox" name="remove_receipt" value="1" id="rmr">
                    <label class="form-check-label" for="rmr">Remove existing receipt</label>
                </div>
            <?php endif; ?>
        </div>

        <button class="btn btn-primary">Save</button>
        <a class="btn btn-secondary" href="<?= site_url('expenses/index') ?>">Cancel</a>
    </form>
    <br>
</div>

<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script>
    (function(){
        const select = document.getElementById('retailor_select');
        const input  = document.getElementById('retailor_input');
        const list = <?php
            $list = json_encode(array_values($retailors ?? []));
            echo $list ?: '[]';
        ?>;

        function syncFromSelect() {
            const val = select.value;
            if (val === '_other') {
                input.classList.remove('d-none');
                input.removeAttribute('readonly');
                if (!input.value) input.focus();
            } else if (val) {
                input.value = val;
                input.setAttribute('readonly', 'readonly');
                input.classList.add('d-none');
            } else {
                input.classList.remove('d-none');
                input.removeAttribute('readonly');
            }
        }

        // Initial state
        const current = input.value || '';
        if (current && list.includes(current)) {
            for (const opt of select.options) { if (opt.value === current) { opt.selected = true; break; } }
            input.classList.add('d-none');
            input.setAttribute('readonly', 'readonly');
        } else if (current && !list.includes(current)) {
            for (const opt of select.options) { if (opt.value === '_other') { opt.selected = true; break; } }
            input.classList.remove('d-none');
            input.removeAttribute('readonly');
        } else {
            input.classList.remove('d-none');
            input.removeAttribute('readonly');
        }

        select.addEventListener('change', syncFromSelect);
    })();
    </script>
<?= $this->endSection() ?>
