@extends('layouts.app', ['includeFullCalendar' => true])

@section('title', 'Availability Calendar')

@section('content')
    <x-breadcrumbs :items="[
        ['label' => 'Dashboard', 'url' => route('dashboard')],
        ['label' => 'Availability Calendar'],
    ]" />

    <x-page-header title="Availability Calendar" subtitle="View space availability and bookings" />

    <div class="vem-filter-bar mb-3">
        <form id="calendar-filters" class="row g-3 align-items-end">
            <div class="col-md-3">
                <label class="form-label" for="filter_space_id">Space</label>
                <select name="space_id" id="filter_space_id" class="form-select form-select-sm">
                    <option value="">All spaces</option>
                    @foreach ($spaces as $space)
                        <option value="{{ $space->id }}">{{ $space->name }}</option>
                    @endforeach
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label" for="filter_customer_id">Customer</label>
                <select name="customer_id" id="filter_customer_id" class="form-select form-select-sm">
                    <option value="">All customers</option>
                    @foreach ($customers as $customer)
                        <option value="{{ $customer->id }}">{{ $customer->name }}</option>
                    @endforeach
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label" for="filter_status">Booking Status</label>
                <select name="status" id="filter_status" class="form-select form-select-sm">
                    <option value="">All statuses</option>
                    @foreach (\App\Enums\BookingStatus::cases() as $status)
                        <option value="{{ $status->value }}">{{ $status->label() }}</option>
                    @endforeach
                </select>
            </div>
            <div class="col-md-3 d-flex gap-2">
                <button type="button" id="apply-filters" class="btn btn-primary btn-sm">Apply Filters</button>
                <button type="button" id="reset-filters" class="btn btn-outline-secondary btn-sm">Reset</button>
            </div>
        </form>
    </div>

    <x-card>
        <div id="availability-calendar" style="min-height: 600px;"></div>
    </x-card>
@endsection

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function () {
    var el = document.getElementById('availability-calendar');
    if (!el || typeof FullCalendar === 'undefined') return;

    var filterForm = document.getElementById('calendar-filters');
    var eventsUrl = @json(route('availability.events'));

    function buildEventsUrl(info) {
        var params = new URLSearchParams({
            start: info.startStr,
            end: info.endStr
        });

        ['space_id', 'customer_id', 'status'].forEach(function (field) {
            var input = filterForm.querySelector('[name="' + field + '"]');
            if (input && input.value) {
                params.set(field, input.value);
            }
        });

        return eventsUrl + '?' + params.toString();
    }

    var calendar = new FullCalendar.Calendar(el, {
        initialView: 'dayGridMonth',
        headerToolbar: {
            left: 'prev,next today',
            center: 'title',
            right: 'dayGridMonth,timeGridWeek,timeGridDay'
        },
        height: 'auto',
        events: function (info, successCallback, failureCallback) {
            fetch(buildEventsUrl(info), {
                headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }
            })
                .then(function (response) { return response.json(); })
                .then(successCallback)
                .catch(failureCallback);
        },
        eventDidMount: function (info) {
            var props = info.event.extendedProps || {};
            var tooltip = info.event.title;
            if (props.booking_status_label) {
                tooltip += ' — Booking: ' + props.booking_status_label;
            }
            if (props.reservation_status_label) {
                tooltip += ' — Reservation: ' + props.reservation_status_label;
            }
            info.el.setAttribute('title', tooltip);
        }
    });

    calendar.render();

    document.getElementById('apply-filters').addEventListener('click', function () {
        calendar.refetchEvents();
    });

    document.getElementById('reset-filters').addEventListener('click', function () {
        filterForm.reset();
        calendar.refetchEvents();
    });
});
</script>
@endpush
