<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<div class="row justify-content-center">
    <div class="col-lg-6">
        <div class="card">
            <div class="card-header d-flex align-items-center gap-2">
                <i class="bi bi-tools" style="color: var(--brand);"></i> <?= isset($workOrder) ? 'Edit Work Order' : 'New Work Order' ?>
            </div>
            <div class="card-body">
                <form id="workOrderForm" action="<?= isset($workOrder) ? site_url('maintenance/' . $workOrder->id) : site_url('maintenance') ?>" method="post">
                    <?= csrf_field() ?>
                    <div class="mb-3">
                        <label class="form-label small fw-semibold">Title</label>
                        <input type="text" class="form-control" id="triage_title" name="title" placeholder="e.g. AC Not Cooling" value="<?= esc($workOrder->title ?? '') ?>" required>
                    </div>
                    <div class="row g-3 mb-3">
                        <div class="col-md-6">
                            <label class="form-label small fw-semibold">Asset / Location <span class="text-muted fw-normal">(optional)</span></label>
                            <input type="text" class="form-control" name="asset" placeholder="e.g. Lobby HVAC" value="<?= esc($workOrder->asset ?? '') ?>">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label small fw-semibold">Room <span class="text-muted fw-normal">(optional)</span></label>
                            <div class="dropdown">
                                <input type="text" class="form-control" id="room_search" autocomplete="off" placeholder="Not room-specific — search to pick one">
                                <input type="hidden" name="room_id" id="room_id_hidden">
                                <div class="dropdown-menu w-100" id="room_dropdown" style="max-height: 280px; overflow-y: auto;"></div>
                            </div>
                        </div>
                    </div>
                    <div class="row g-3 mb-3">
                        <div class="col-md-6">
                            <label class="form-label small fw-semibold">Priority</label>
                            <select class="form-select" name="priority" id="triage_priority">
                                <?php foreach ($lookups->taskPriorities as $key => $meta): ?>
                                    <option value="<?= $key ?>" <?= (isset($workOrder) ? $workOrder->priority === $key : $key === 'medium') ? 'selected' : '' ?>><?= esc($meta['label']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label small fw-semibold">Due Date <span class="text-muted fw-normal">(optional)</span></label>
                            <input type="date" class="form-control" name="due_date" value="<?= esc($workOrder->due_date ?? '') ?>">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label small fw-semibold">Assign To <span class="text-muted fw-normal">(optional)</span></label>
                        <select class="form-select" name="assigned_to">
                            <option value="">Unassigned</option>
                            <?php foreach ($staff as $person): ?>
                                <option value="<?= $person->id ?>" <?= isset($workOrder) && (int) $workOrder->assigned_to === (int) $person->id ? 'selected' : '' ?>><?= esc($person->full_name) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label small fw-semibold">Notes <span class="text-muted fw-normal">(optional)</span></label>
                        <textarea class="form-control" name="notes" id="triage_notes" rows="2"><?= esc($workOrder->notes ?? '') ?></textarea>
                    </div>
                    <div class="mb-4">
                        <button type="button" class="btn btn-sm btn-outline-primary" id="suggestTriageBtn"><i class="bi bi-stars me-1"></i>Suggest with AI</button>
                        <div class="small mt-2 d-none" id="triageResult"></div>
                    </div>
                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-primary"><i class="bi bi-check2 me-1"></i><?= isset($workOrder) ? 'Save Changes' : 'Create Work Order' ?></button>
                        <a href="<?= isset($workOrder) ? site_url('maintenance/' . $workOrder->id) : site_url('maintenance') ?>" class="btn btn-outline-secondary">Cancel</a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<script>
initRoomPicker({
    inputId: 'room_search',
    hiddenId: 'room_id_hidden',
    dropdownId: 'room_dropdown',
    emptyLabel: 'Not room-specific',
    rooms: <?= json_encode(array_map(static fn ($r) => [
        'id'    => $r->id,
        'label' => $r->room_number . ' — ' . $r->room_type_name . ' (Floor ' . $r->floor . ')',
    ], $rooms)) ?>,
    selectedId: <?= isset($workOrder) && $workOrder->room_id ? (int) $workOrder->room_id : 'null' ?>,
});

document.getElementById('suggestTriageBtn').addEventListener('click', function () {
    const btn = this;
    const resultEl = document.getElementById('triageResult');
    const title = document.getElementById('triage_title').value.trim();
    const notes = document.getElementById('triage_notes').value.trim();

    function showError(message) {
        resultEl.classList.remove('d-none');
        resultEl.textContent = '';
        const span = document.createElement('span');
        span.className = 'text-danger';
        span.textContent = message; // textContent, not innerHTML — message may echo AI/attacker-influenced text
        resultEl.appendChild(span);
    }

    if (! title && ! notes) {
        showError('Enter a title or notes first.');
        return;
    }

    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Thinking...';

    window.maxyieldsPost('<?= site_url('maintenance/suggest-triage') ?>', { title: title, notes: notes })
        .then(function (data) {
            resultEl.classList.remove('d-none');

            if (! data.success) {
                showError(data.error);
                return;
            }

            document.getElementById('triage_priority').value = data.priority;

            // Built via textContent, not innerHTML — suggested_role/reasoning
            // are Claude's response text, which is only as trustworthy as
            // whatever a staff member typed into title/notes (a prompt-
            // injection vector); never inserted as raw HTML.
            resultEl.textContent = '';
            const wrap = document.createElement('div');
            wrap.className = 'alert alert-primary py-2 mb-0';

            const strong = document.createElement('strong');
            strong.textContent = 'Suggested priority set to ' + data.priority + '. ';
            wrap.appendChild(strong);
            wrap.appendChild(document.createTextNode(data.suggested_role || ''));

            if (data.reasoning) {
                wrap.appendChild(document.createElement('br'));
                const reasoningEl = document.createElement('span');
                reasoningEl.className = 'text-muted';
                reasoningEl.textContent = data.reasoning;
                wrap.appendChild(reasoningEl);
            }

            resultEl.appendChild(wrap);
        })
        .catch(function () {
            showError('Could not reach the server — please try again.');
        })
        .finally(function () {
            btn.disabled = false;
            btn.innerHTML = '<i class="bi bi-stars me-1"></i>Suggest with AI';
        });
});
</script>
<?= $this->endSection() ?>
