@extends('agency.layouts.app')

@section('title', 'Acente Takvimi')
@section('page_title', 'Acente Takvimi')

@push('styles')
<style>
    .ac-wrap { --slate:#334155; }

    /* ── Üst araç çubuğu ── */
    .ac-toolbar { display:flex; flex-wrap:wrap; gap:10px; align-items:center; margin-bottom:14px; }
    .ac-tbtn { display:inline-flex; align-items:center; gap:9px; height:42px; padding:0 15px; border:1px solid #e2e8f0; background:#fff; border-radius:12px; font-size:.85rem; font-weight:700; color:#334155; cursor:pointer; transition:.18s; }
    .ac-tbtn:hover { border-color:#cbd5e1; background:#f8fafc; }
    .ac-tbtn.on { background:#eef2f6; border-color:#94a3b8; }
    .ac-tbtn .caret { font-size:.68rem; color:#94a3b8; transition:transform .2s; }
    .ac-tbtn.open .caret { transform:rotate(180deg); }
    .ac-count { background:#334155; color:#fff; border-radius:999px; font-size:.66rem; font-weight:800; min-width:18px; height:18px; display:none; align-items:center; justify-content:center; padding:0 5px; }
    .ac-count.on { display:inline-flex; }

    .ac-source { display:inline-flex; background:#f1f5f9; border:1px solid #e2e8f0; border-radius:12px; padding:3px; gap:2px; }
    .ac-source button { border:none; background:transparent; font-size:.8rem; font-weight:700; color:#64748b; padding:8px 14px; border-radius:9px; cursor:pointer; transition:.15s; }
    .ac-source button.active { background:#334155; color:#fff; box-shadow:0 2px 6px rgba(30,41,59,.2); }

    .ac-legend-inline { display:flex; flex-wrap:wrap; gap:12px; align-items:center; margin-left:auto; }
    .ac-legend-inline .li { display:inline-flex; align-items:center; gap:6px; font-size:.75rem; font-weight:600; color:#64748b; }
    .ac-legend-inline .dot { width:9px; height:9px; border-radius:50%; }
    @media (max-width:900px) { .ac-legend-inline { margin-left:0; width:100%; } }

    /* ── Açılır filtre paneli (yatay) ── */
    .ac-filters { overflow:hidden; transition:max-height .28s ease, opacity .2s ease, margin .2s ease; max-height:260px; opacity:1; margin-bottom:14px; }
    .ac-filters.collapsed { max-height:0; opacity:0; margin-bottom:0; }
    .ac-filters-inner { background:#fff; border:1px solid #e2e8f0; border-radius:16px; padding:14px 16px; display:flex; flex-wrap:wrap; gap:14px; align-items:flex-end; box-shadow:0 4px 16px rgba(15,23,42,.03); }
    .ac-field { display:flex; flex-direction:column; gap:5px; min-width:170px; flex:1 1 170px; max-width:230px; }
    .ac-field label { font-size:.68rem; font-weight:800; text-transform:uppercase; letter-spacing:.03em; color:#94a3b8; }
    .ac-sel { width:100%; padding:9px 12px; border:1.5px solid #e2e8f0; border-radius:11px; font-size:.85rem; font-weight:600; color:#334155; background:#f8fafc; cursor:pointer; transition:.18s; }
    .ac-sel:focus { outline:none; border-color:#334155; background:#fff; box-shadow:0 0 0 4px rgba(51,65,85,.06); }
    .ac-clear { height:40px; padding:0 14px; border:1px solid #fecaca; background:#fef2f2; color:#dc2626; border-radius:11px; font-size:.8rem; font-weight:700; cursor:pointer; transition:.15s; }
    .ac-clear:hover { background:#fee2e2; }

    /* ── Takvim ── */
    .ac-cal-card { background:#fff; border:1px solid #e2e8f0; border-radius:18px; padding:18px; box-shadow:0 4px 16px rgba(15,23,42,.03); }
    #agencyCalendar { --fc-border-color:#eef2f6; --fc-today-bg-color:#fffbeb; --fc-page-bg-color:#fff; }
    #agencyCalendar .fc .fc-toolbar-title { font-size:1.2rem; font-weight:800; color:#0f172a; }
    #agencyCalendar .fc .fc-button { background:#334155; border-color:#334155; font-weight:600; font-size:.82rem; text-transform:capitalize; box-shadow:none; }
    #agencyCalendar .fc .fc-button:hover { background:#1e293b; border-color:#1e293b; }
    #agencyCalendar .fc .fc-button-primary:not(:disabled).fc-button-active { background:#0f172a; border-color:#0f172a; }
    #agencyCalendar .fc .fc-button-primary:disabled { background:#94a3b8; border-color:#94a3b8; }
    #agencyCalendar .fc .fc-col-header-cell-cushion { font-size:.72rem; font-weight:800; text-transform:uppercase; letter-spacing:.03em; color:#94a3b8; padding:8px; }
    #agencyCalendar .fc .fc-daygrid-day-number { font-size:.8rem; font-weight:700; color:#64748b; }
    #agencyCalendar .fc-event { border-radius:6px; font-size:.72rem; font-weight:600; padding:1px 2px; cursor:pointer; border:none; }
    #agencyCalendar .fc-event:hover { filter:brightness(.94); }
    #agencyCalendar .fc .fc-daygrid-event { white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }

    .ac-loading { display:none; align-items:center; gap:8px; font-size:.82rem; color:#64748b; font-weight:600; }
    .ac-loading.on { display:inline-flex; }
</style>
@endpush

@section('content')
<div class="ac-wrap">

    {{-- Üst araç çubuğu --}}
    <div class="ac-toolbar">
        <button type="button" class="ac-tbtn open" id="acFilterToggle">
            <i class="fas fa-filter"></i> Filtreler
            <span class="ac-count" id="acCount">0</span>
            <i class="fas fa-chevron-down caret"></i>
        </button>

        <div class="ac-source" id="acSource">
            <button type="button" class="active" data-source="all">Tümü</button>
            <button type="button" data-source="tours">Turlar</button>
            <button type="button" data-source="resources">Kaynaklar</button>
        </div>

        <div class="ac-legend-inline">
            @foreach($depTypes as $d)
                <span class="li"><span class="dot" style="background:{{ $d['color'] }}"></span>{{ $d['label'] }}</span>
            @endforeach
            @php $sl = ['block'=>'Bloke','maintenance'=>'Bakım','leave'=>'İzin']; @endphp
            {{-- Tur ataması iki durumda: ön atama (amber) / kesin atama (yeşil) --}}
            <span class="li"><span class="dot" style="background:#f59e0b"></span>Ön Atama</span>
            <span class="li"><span class="dot" style="background:#16a34a"></span>Kesin Atama</span>
            @foreach($schedColors as $type => $color)
                @continue($type === 'tour_assignment')
                <span class="li"><span class="dot" style="background:{{ $color }}"></span>{{ $sl[$type] ?? $type }}</span>
            @endforeach
        </div>
    </div>

    {{-- Açılır filtre paneli --}}
    <div class="ac-filters" id="acFilters">
        <div class="ac-filters-inner">
            <div class="ac-field">
                <label>Tur Tipi</label>
                <select class="ac-sel cal-flt js-cselect" id="fltTourType" data-icon="fa-layer-group">
                    <option value="">Tüm Tur Tipleri</option>
                    @foreach($depTypes as $key => $d)
                        <option value="{{ $key }}">{{ $d['label'] }}</option>
                    @endforeach
                </select>
            </div>
            <div class="ac-field">
                <label>Kaynak Tipi</label>
                <select class="ac-sel cal-flt js-cselect" id="fltResType" data-icon="fa-cubes">
                    <option value="">Tüm Kaynak Tipleri</option>
                    <option value="guide">Rehber</option>
                    <option value="vehicle">Araç</option>
                    <option value="captain">Kaptan</option>
                </select>
            </div>
            <div class="ac-field">
                <label>Plan Tipi</label>
                <select class="ac-sel cal-flt js-cselect" id="fltSchedType" data-icon="fa-calendar-check">
                    <option value="">Tüm Planlar</option>
                    <option value="tour_assignment">Tur Görevi</option>
                    <option value="block">Bloke</option>
                    <option value="maintenance">Bakım</option>
                    <option value="leave">İzin</option>
                </select>
            </div>
            <div class="ac-field">
                <label>Tekil Kaynak</label>
                <select class="ac-sel cal-flt js-cselect" id="fltResource" data-icon="fa-cube">
                    <option value="">Tüm Kaynaklar</option>
                    @foreach($resources as $r)
                        <option value="{{ $r->id }}">[{{ $r->type === 'guide' ? 'Rehber' : ($r->type === 'vehicle' ? 'Araç' : 'Kaptan') }}] {{ $r->name }}</option>
                    @endforeach
                </select>
            </div>
            <button type="button" class="ac-clear" id="acClear"><i class="fas fa-eraser me-1"></i>Temizle</button>
        </div>
    </div>

    {{-- Takvim --}}
    <div class="ac-cal-card">
        <div class="d-flex align-items-center mb-2">
            <div class="ac-loading" id="acLoading"><i class="fas fa-spinner fa-spin"></i> Yükleniyor…</div>
            <div class="text-muted small ms-auto"><i class="fas fa-hand-pointer me-1"></i>Etkinliğe tıklayarak detay kartını açabilirsiniz</div>
        </div>
        <div id="agencyCalendar"></div>
    </div>
</div>
@include('agency.partials.custom-select')
@endsection

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.15/index.global.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.15/locales-all.global.min.js"></script>
<script>
(function () {
    const EVENTS_URL = "{{ route('agency.calendar.events') }}";
    const el = document.getElementById('agencyCalendar');
    if (!el || !window.FullCalendar) return;

    let source = 'all';
    const val = id => (document.getElementById(id)?.value || '');
    const loading = document.getElementById('acLoading');

    const calendar = new FullCalendar.Calendar(el, {
        initialView: 'dayGridMonth',
        locale: 'tr',
        firstDay: 1,
        height: 'auto',
        headerToolbar: {
            left: 'prev,next today',
            center: 'title',
            right: 'dayGridMonth,timeGridWeek,timeGridDay,listMonth'
        },
        buttonText: { today: 'Bugün', month: 'Ay', week: 'Hafta', day: 'Gün', list: 'Liste' },
        dayMaxEvents: 4,
        nowIndicator: true,
        loading: function (isLoading) { loading.classList.toggle('on', isLoading); },
        events: function (info, success, failure) {
            const p = new URLSearchParams({
                start: info.startStr, end: info.endStr,
                source: source,
                tour_type: val('fltTourType'),
                resource_type: val('fltResType'),
                schedule_type: val('fltSchedType'),
                resource_id: val('fltResource'),
            });
            fetch(EVENTS_URL + '?' + p.toString(), { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
                .then(r => r.json()).then(success).catch(failure);
        },
        eventDidMount: function (i) { i.el.title = i.event.title; },
        eventClick: function (info) {
            info.jsEvent.preventDefault();
            const ep = info.event.extendedProps || {};
            if (ep.kind === 'departure' && ep.qvUrl && typeof openQuickView === 'function') {
                openQuickView(ep.qvUrl);
            } else if (ep.kind === 'resource' && ep.resourceId && typeof openResourceDrawer === 'function') {
                openResourceDrawer(ep.resourceId);
            }
        }
    });
    calendar.render();

    // ── Aktif filtre sayısı ──
    function updateCount() {
        let n = 0;
        ['fltTourType', 'fltResType', 'fltSchedType', 'fltResource'].forEach(id => { if (val(id)) n++; });
        const badge = document.getElementById('acCount');
        badge.textContent = n;
        badge.classList.toggle('on', n > 0);
    }

    // ── Filtre değişimi ──
    document.querySelectorAll('.cal-flt').forEach(s => s.addEventListener('change', () => { calendar.refetchEvents(); updateCount(); }));

    document.getElementById('acClear').addEventListener('click', function () {
        document.querySelectorAll('.cal-flt').forEach(s => { s.value = ''; if (window.jcsRefresh) window.jcsRefresh(s); });
        calendar.refetchEvents();
        updateCount();
    });

    // ── Görünüm kaynağı ──
    document.querySelectorAll('#acSource button').forEach(b => b.addEventListener('click', function () {
        document.querySelectorAll('#acSource button').forEach(x => x.classList.remove('active'));
        this.classList.add('active');
        source = this.dataset.source;
        calendar.refetchEvents();
    }));

    // ── Aç/kapa (tercih hatırlanır) ──
    const toggle = document.getElementById('acFilterToggle');
    const filters = document.getElementById('acFilters');
    function applyCollapsed(collapsed) {
        filters.classList.toggle('collapsed', collapsed);
        toggle.classList.toggle('open', !collapsed);
        setTimeout(() => calendar.updateSize(), 300);
    }
    let collapsed = localStorage.getItem('acFiltersCollapsed') === '1';
    applyCollapsed(collapsed);
    toggle.addEventListener('click', function () {
        collapsed = !collapsed;
        localStorage.setItem('acFiltersCollapsed', collapsed ? '1' : '0');
        applyCollapsed(collapsed);
    });

    updateCount();
})();
</script>
@endpush
