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

<h1 class="h3 mb-3"><?= $event ? 'Edit Event' : 'New Event' ?></h1>

<div class="card shadow-sm" style="max-width: 640px;">
    <div class="card-body">
        <form action="<?= $event ? site_url('events/' . $event->id) : site_url('events') ?>" method="post">
            <?= csrf_field() ?>

            <?php if (! $event): ?>
            <h2 class="h6">Client</h2>
            <input type="hidden" name="guest_id" id="guest_id" value="<?= (int) $guestId ?>">
            <input type="hidden" name="event_client_id" id="event_client_id" value="<?= (int) $eventClientId ?>">

            <div class="row mb-3">
                <div class="col-md-6">
                    <label class="form-label small">Existing guest phone</label>
                    <div class="input-group input-group-sm">
                        <input type="text" class="form-control" id="guest_phone_lookup" placeholder="024XXXXXXX">
                        <button type="button" class="btn btn-outline-secondary" id="guest-lookup-btn">Look up</button>
                    </div>
                    <div id="guest-lookup-result" class="form-text"></div>
                </div>
                <div class="col-md-6">
                    <label class="form-label small">Or company client</label>
                    <div class="input-group input-group-sm">
                        <input type="text" class="form-control" id="client_lookup" placeholder="Company name">
                        <button type="button" class="btn btn-outline-secondary" id="client-lookup-btn">Search</button>
                    </div>
                    <div id="client-lookup-result" class="form-text"></div>
                </div>
            </div>
            <p class="form-text mb-3">No match? <a href="<?= site_url('event-clients/new') ?>" target="_blank">Create a new event client &rarr;</a>, then search for them here.</p>
            <?php endif; ?>

            <div class="mb-3">
                <label class="form-label">Event Name</label>
                <input type="text" class="form-control" name="event_name" required value="<?= esc(old('event_name', $event->event_name ?? '')) ?>">
            </div>

            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label">Event Type</label>
                    <input type="text" class="form-control" name="event_type" placeholder="e.g. Conference, Wedding" value="<?= esc(old('event_type', $event->event_type ?? '')) ?>">
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">Event Date</label>
                    <input type="date" class="form-control" name="event_date" required value="<?= esc(old('event_date', $event->event_date ?? '')) ?>">
                </div>
            </div>

            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label">Expected Headcount</label>
                    <input type="number" class="form-control" name="expected_headcount" min="1" value="<?= esc(old('expected_headcount', $event->expected_headcount ?? '')) ?>">
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">Venue / Space</label>
                    <input type="text" class="form-control" name="venue_space" value="<?= esc(old('venue_space', $event->venue_space ?? '')) ?>">
                </div>
            </div>
            <div class="mb-3">
                <label class="form-label">Description <span class="text-muted small">(optional)</span></label>
                <textarea class="form-control" name="description" id="eventDescription" rows="2" placeholder="A short description of this event package"><?= esc(old('description', $event->description ?? '')) ?></textarea>
                <button type="button" class="btn btn-sm btn-outline-primary mt-1" id="eventDraftBtn"><i class="bi bi-stars me-1"></i>Draft with AI</button>
            </div>


            <?php if ($event): ?>
            <div class="mb-3">
                <label class="form-label">Status</label>
                <select class="form-select" name="status">
                    <?php foreach ($lookups->eventStatuses as $key => $meta): ?>
                        <option value="<?= esc($key) ?>" <?= $event->status === $key ? 'selected' : '' ?>><?= esc($meta['label']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <?php endif; ?>

            <div class="mb-3">
                <label class="form-label">Contract / Notes</label>
                <textarea class="form-control" name="contract_notes" rows="3"><?= esc(old('contract_notes', $event->contract_notes ?? '')) ?></textarea>
            </div>

            <div class="d-flex gap-2">
                <button type="submit" class="btn btn-primary">Save</button>
                <a href="<?= site_url('events') ?>" class="btn btn-outline-secondary">Cancel</a>
            </div>
        </form>
    </div>
</div>

<?= $this->endSection() ?>
<?= $this->section('scripts') ?>
<script>
const guestLookupBtn = document.getElementById('guest-lookup-btn');
if (guestLookupBtn) {
    guestLookupBtn.addEventListener('click', function () {
        const phone = document.getElementById('guest_phone_lookup').value.trim();
        const resultEl = document.getElementById('guest-lookup-result');
        if (!phone) return;
        fetch('<?= site_url('guests/lookup') ?>?phone=' + encodeURIComponent(phone))
            .then((r) => r.json())
            .then((data) => {
                if (data.found) {
                    document.getElementById('guest_id').value = data.guest.id;
                    document.getElementById('event_client_id').value = 0;
                    resultEl.innerHTML = '<span class="text-success">Guest: ' + data.guest.full_name + '</span>';
                } else {
                    resultEl.innerHTML = '<span class="text-danger">No guest with that phone.</span>';
                }
            });
    });

    document.getElementById('client-lookup-btn').addEventListener('click', function () {
        const q = document.getElementById('client_lookup').value.trim();
        const resultEl = document.getElementById('client-lookup-result');
        if (!q) return;
        fetch('<?= site_url('event-clients/lookup') ?>?q=' + encodeURIComponent(q))
            .then((r) => r.json())
            .then((data) => {
                if (data.results.length) {
                    const first = data.results[0];
                    document.getElementById('event_client_id').value = first.id;
                    document.getElementById('guest_id').value = 0;
                    resultEl.innerHTML = '<span class="text-success">Client: ' + first.company_name + '</span>';
                } else {
                    resultEl.innerHTML = '<span class="text-danger">No matching client.</span>';
                }
            });
    });
}

document.getElementById('eventDraftBtn').addEventListener('click', function () {
    const btn = this;
    const name = document.querySelector('input[name="event_name"]').value.trim();
    const textarea = document.getElementById('eventDescription');

    if (! name) {
        alert('Enter an event name first.');
        return;
    }

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

    window.maxyieldsPost('<?= site_url('ai/draft-description') ?>', { context: 'event', name: name, prompt: textarea.value })
        .then(function (data) {
            if (data.success) {
                textarea.value = data.text;
            } else {
                alert(data.error);
            }
        })
        .catch(function () {
            alert('Could not reach the server — please try again.');
        })
        .finally(function () {
            btn.disabled = false;
            btn.innerHTML = '<i class="bi bi-stars me-1"></i>Draft with AI';
        });
});
</script>
<?= $this->endSection() ?>
