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

<div class="container mt-4">
    <h1>Add Expense / Purchase</h1>
<?php if (session()->getFlashdata('error')): ?>
    <div class="alert alert-danger">
        <?= session()->getFlashdata('error') ?>
    </div>
<?php endif; ?>
    <form method="post" action="<?= base_url('expenses/store') ?>" enctype="multipart/form-data">
        <?= csrf_field() ?>

        <div class="mb-3">
            <label class="form-label">Category</label>
            <select name="category" class="form-control" required>
                <option value="Expense">Expense</option>
                <option value="Purchase">Purchase</option>
                <option value="Reimbursement">Reimbursement</option>
                <option value="Donation">Donation (non-reimbursable)</option>
            </select>
            <div class="form-text text-muted">Use Donation when someone gifts items to the school so it is counted as an expense but skipped from reimbursement queues.</div>
        </div>

        <div class="mb-3">
            <label class="form-label">Amount</label>
            <input type="number" step="0.01" name="amount" class="form-control" required>
        </div>

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

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

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

        <div class="mb-3">
            <label class="form-label">Description</label>
            <textarea name="description" class="form-control"><?= old('description') ?></textarea>
        </div>
       <div class="mb-3">
            <label class="form-label">Receipt Image</label>
            <input type="file" name="receipt" class="form-control" required>
        </div>


        <!-- school_year and semester are auto-populated in controller -->
        <button type="submit" class="btn btn-primary">Submit</button>
        <a href="<?= site_url('expenses/index') ?>" class="btn btn-secondary ms-2">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
            // Safe JSON of retailors for quick client-side check
            $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 {
                // No selection: allow manual entry if desired
                input.classList.remove('d-none');
                input.removeAttribute('readonly');
            }
        }

        // Initial state
        const current = input.value || '';
        if (current && list.includes(current)) {
            // Match in list: select it and hide input
            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)) {
            // Not in list: choose Other and show input
            for (const opt of select.options) { if (opt.value === '_other') { opt.selected = true; break; } }
            input.classList.remove('d-none');
            input.removeAttribute('readonly');
        } else {
            // Empty: allow selection or manual entry
            input.classList.remove('d-none');
            input.removeAttribute('readonly');
        }

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