@extends('agency.layouts.app')

@section('title', 'Müsaitlik & Planlama Takvimi')
@section('page_title', 'Müsaitlik & Planlama Takvimi')

@php
    $breadcrumbs = [
        ['title' => 'Dashboard', 'url' => route('agency.dashboard')],
        ['title' => 'Kaynak Yönetimi', 'url' => route('agency.resources.index')],
        ['title' => 'Müsaitlik Takvimi', 'url' => '']
    ];

    $monthNames = ['','Ocak','Şubat','Mart','Nisan','Mayıs','Haziran','Temmuz','Ağustos','Eylül','Ekim','Kasım','Aralık'];
    $dayNames   = ['Pzt','Sal','Çar','Per','Cum','Cmt','Paz'];

    $typeColors = [
        'tour_assignment' => ['dot'=>'#3b82f6','bg'=>'#eff6ff','text'=>'#2563eb','label'=>'Tur Görevi'],
        'block'           => ['dot'=>'#ef4444','bg'=>'#fff1f2','text'=>'#e11d48','label'=>'Bloke'],
        'maintenance'     => ['dot'=>'#f59e0b','bg'=>'#fffbeb','text'=>'#d97706','label'=>'Bakım'],
        'leave'           => ['dot'=>'#8b5cf6','bg'=>'#f5f3ff','text'=>'#7c3aed','label'=>'İzin'],
    ];

    $daySchedulesJson = [];
    for ($d = 1; $d <= $daysInMonth; $d++) {
        $daySchedulesJson[$d] = collect($daySchedules[$d] ?? [])->map(function($s) {
            return [
                'id'       => $s->id,
                'title'    => $s->title,
                'resource' => $s->resource->name,
                'type'     => $s->schedule_type,
                'start'    => $s->start_date->format('d.m.Y'),
                'end'      => $s->end_date->format('d.m.Y'),
                'canDelete'=> $s->schedule_type !== 'tour_assignment',
            ];
        })->values()->all();
    }
@endphp

@push('styles')
<style>
/* ─── LAYOUT ─── */
.cal-layout { display: grid; grid-template-columns: 280px 1fr; gap: 1.5rem; align-items: start; }
@media(max-width:991px){ .cal-layout { grid-template-columns:1fr; } }

/* ─── SIDE PANEL ─── */
.side-panel { position: sticky; top: 80px; display: flex; flex-direction: column; gap: 1rem; }
.panel-card {
    background:#fff; border-radius:16px; border:1px solid #f1f5f9;
    box-shadow:0 1px 4px rgba(0,0,0,.04); overflow:hidden;
}
.panel-head {
    padding:.9rem 1.25rem; border-bottom:1px solid #f8fafc;
    font-size:.8rem; font-weight:700; color:#475569; letter-spacing:.4px; text-transform:uppercase;
    display:flex; align-items:center; gap:.5rem;
}
.panel-body { padding:1.25rem; }

/* Filter inputs */
.f-label { font-size:.72rem;font-weight:700;color:#64748b;letter-spacing:.3px;text-transform:uppercase;margin-bottom:.4rem;display:block; }
.f-select { width:100%;padding:.55rem .8rem;border:1.5px solid #e2e8f0;border-radius:10px;font-size:.83rem;background:#f8fafc;color:#0f172a;margin-bottom:.85rem;transition:border-color .2s; }
.f-select:focus { outline:none;border-color:#3b82f6;background:#fff; }

/* Legend */
.legend-item { display:flex;align-items:center;gap:.6rem;margin-bottom:.6rem; }
.legend-dot { width:10px;height:10px;border-radius:50%;flex-shrink:0; }
.legend-txt { font-size:.8rem;color:#475569;font-weight:500; }

/* Block form */
.f-input {
    width:100%;padding:.55rem .8rem;border:1.5px solid #e2e8f0;border-radius:10px;
    font-size:.83rem;background:#f8fafc;color:#0f172a;margin-bottom:.85rem;
    transition:border-color .2s;
}
.f-input:focus { outline:none;border-color:#3b82f6;background:#fff; }
.f-textarea { resize:vertical;min-height:60px; }
.btn-add { width:100%;padding:.65rem;border-radius:10px;border:none;cursor:pointer;font-weight:700;font-size:.875rem;color:#fff;background:linear-gradient(135deg,#ef4444,#dc2626);transition:all .15s; }
.btn-add:hover { transform:translateY(-1px);box-shadow:0 4px 12px rgba(239,68,68,.3); }

/* ─── CALENDAR ─── */
.cal-card { background:#fff;border-radius:16px;border:1px solid #f1f5f9;box-shadow:0 1px 4px rgba(0,0,0,.04);overflow:hidden; }
.cal-head {
    padding:1.1rem 1.5rem;
    display:flex;align-items:center;justify-content:space-between;
    border-bottom:1px solid #f1f5f9;
    background:linear-gradient(135deg,#0f172a,#1e293b);
    color:#fff;
}
.cal-title { font-size:1.15rem;font-weight:800; }
.cal-nav-btn {
    width:36px;height:36px;border-radius:10px;border:1px solid rgba(255,255,255,.15);
    background:rgba(255,255,255,.08);color:#fff;cursor:pointer;
    display:flex;align-items:center;justify-content:center;font-size:14px;
    transition:all .15s;text-decoration:none;
}
.cal-nav-btn:hover { background:rgba(255,255,255,.18);color:#fff; }
.cal-nav-btn.today { padding:0 1rem;font-size:.8rem;font-weight:600;width:auto; }

/* Day headers */
.cal-dow-row { display:grid;grid-template-columns:repeat(7,1fr); background:#f8fafc; }
.cal-dow { padding:.6rem;text-align:center;font-size:.7rem;font-weight:700;color:#94a3b8;letter-spacing:.5px; }
.cal-dow:nth-child(6),.cal-dow:nth-child(7) { color:#ef4444; }

/* Grid */
.cal-grid { display:grid;grid-template-columns:repeat(7,1fr); }
.cal-cell {
    min-height:100px;padding:.5rem;border-right:1px solid #f1f5f9;border-bottom:1px solid #f1f5f9;
    position:relative; transition:background .12s; cursor:pointer;
}
.cal-cell:hover { background:#fafbff; }
.cal-cell.empty { background:#fafafa;cursor:default; }
.cal-cell.today-cell { background:#fffbeb; }
.cal-cell:nth-child(7n),.cal-cell:nth-child(7n-0) { border-right:none; }

.day-num {
    font-size:.8rem;font-weight:700;color:#64748b;
    width:26px;height:26px;display:flex;align-items:center;justify-content:center;
    border-radius:50%;margin-bottom:.3rem;
}
.cal-cell.today-cell .day-num { background:#f59e0b;color:#fff; }
.day-weekend .day-num { color:#ef4444; }

/* Schedule chips in grid */
.sched-chip {
    display:block;padding:2px 6px;border-radius:6px;font-size:.65rem;font-weight:600;
    margin-bottom:2px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;
    max-width:100%;
}
.more-badge { font-size:.65rem;color:#94a3b8;font-weight:600;margin-top:2px; }

/* ─── DAY DETAIL PANEL ─── */
.day-detail {
    background:#fff;border-radius:16px;border:1px solid #f1f5f9;
    box-shadow:0 4px 20px rgba(0,0,0,.08);padding:1.25rem;
    margin-top:1rem;display:none;
}
.day-detail.show { display:block; }
.dd-head { display:flex;align-items:center;justify-content:space-between;margin-bottom:1rem; }
.dd-title { font-size:1rem;font-weight:800;color:#0f172a; }
.dd-close { width:28px;height:28px;border-radius:8px;border:none;background:#f1f5f9;color:#64748b;cursor:pointer;display:flex;align-items:center;justify-content:center; }
.sched-row { display:flex;align-items:center;gap:.75rem;padding:.65rem .75rem;border-radius:10px;border:1px solid #f1f5f9;margin-bottom:.5rem; }
.sched-dot { width:10px;height:10px;border-radius:50%;flex-shrink:0; }
.sched-info { flex:1;min-width:0; }
.sched-name { font-size:.825rem;font-weight:700;color:#0f172a; }
.sched-sub  { font-size:.72rem;color:#94a3b8;margin-top:1px; }
.sched-badge { font-size:.68rem;font-weight:700;padding:3px 8px;border-radius:20px;flex-shrink:0; }
.sched-del { width:26px;height:26px;border-radius:8px;border:none;background:#fff1f2;color:#ef4444;cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:11px;flex-shrink:0; }

/* ── Yatay açılır filtre bar ── */
.rc-toolbar { display:flex; flex-wrap:wrap; gap:10px; align-items:center; margin-bottom:14px; }
.rc-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; }
.rc-tbtn:hover { border-color:#cbd5e1; background:#f8fafc; }
.rc-tbtn.open { background:#eef2f6; border-color:#94a3b8; }
.rc-tbtn .caret { font-size:.68rem; color:#94a3b8; transition:transform .2s; }
.rc-tbtn.open .caret { transform:rotate(180deg); }
.rc-tbtn.rc-add { color:#dc2626; border-color:#fecaca; background:#fef2f2; }
.rc-tbtn.rc-add:hover { background:#fee2e2; }
.rc-tbtn.rc-add.open { background:#dc2626; color:#fff; border-color:#dc2626; }
.rc-legend { display:flex; flex-wrap:wrap; gap:12px; align-items:center; margin-left:auto; }
.rc-legend .li { display:inline-flex; align-items:center; gap:6px; font-size:.75rem; font-weight:600; color:#64748b; }
.rc-legend .dot { width:9px; height:9px; border-radius:50%; }
@media(max-width:800px){ .rc-legend { margin-left:0; width:100%; } }

.rc-panel { overflow:hidden; transition:max-height .28s ease, opacity .2s ease, margin .2s ease; max-height:400px; opacity:1; margin-bottom:14px; }
.rc-panel.collapsed { max-height:0; opacity:0; margin-bottom:0; }
.rc-panel-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 1px 4px rgba(0,0,0,.04); }
.rc-field { display:flex; flex-direction:column; gap:5px; min-width:170px; flex:1 1 170px; }
.rc-field.sm { flex:0 1 150px; }
.rc-field label { font-size:.68rem; font-weight:800; text-transform:uppercase; letter-spacing:.03em; color:#94a3b8; }
.rc-field .f-select, .rc-field .f-input { margin-bottom:0; }
.rc-add-submit { height:40px; padding:0 18px; border:none; border-radius:11px; background:linear-gradient(135deg,#ef4444,#dc2626); color:#fff; font-size:.85rem; font-weight:700; cursor:pointer; }
.rc-add-submit:hover { box-shadow:0 4px 12px rgba(239,68,68,.3); }
</style>
@endpush

@section('content')
<div class="container-fluid">

    {{-- Toolbar --}}
    <div class="d-flex align-items-center justify-content-between mb-4">
        <div>
            <h2 class="h5 mb-1 fw-bold">Müsaitlik & Planlama Takvimi</h2>
            <p class="text-muted small mb-0">Kaynakların aylık görev, bloke ve izin kayıtlarını takvim üzerinde görün.</p>
        </div>
        <a href="{{ route('agency.resources.index') }}" class="btn btn-sm"
           style="background:#f8fafc;border:1.5px solid #e2e8f0;border-radius:10px;color:#475569;font-weight:600">
            <i class="fas fa-list me-1"></i>Kaynak Listesi
        </a>
    </div>

    {{-- Filtre + aksiyon bar (yatay, açılır) --}}
    <div class="rc-toolbar">
        <button type="button" class="rc-tbtn open" id="rcFilterToggle"><i class="fas fa-filter"></i> Filtreler <i class="fas fa-chevron-down caret"></i></button>
        <button type="button" class="rc-tbtn rc-add" id="rcAddToggle"><i class="fas fa-calendar-minus"></i> Bloke / İzin Ekle</button>
        <div class="rc-legend">
            @foreach($typeColors as $type => $c)
                <span class="li"><span class="dot" style="background:{{ $c['dot'] }}"></span>{{ $c['label'] }}</span>
            @endforeach
        </div>
    </div>

    {{-- Açılır filtreler --}}
    <div class="rc-panel" id="rcFilters">
        <form method="GET" action="{{ route('agency.resources.calendar') }}" id="filterForm" class="rc-panel-inner">
            <input type="hidden" name="month" value="{{ $currentMonth->format('Y-m') }}">
            <div class="rc-field sm">
                <label>Kaynak Tipi</label>
                <select name="type" class="f-select js-cselect" data-icon="fa-cubes" onchange="this.form.submit()">
                    <option value="">Tüm Tipler</option>
                    <option value="guide"   {{ request('type')==='guide'   ? 'selected':'' }}>Rehberler</option>
                    <option value="vehicle" {{ request('type')==='vehicle' ? 'selected':'' }}>Araçlar</option>
                    <option value="captain" {{ request('type')==='captain' ? 'selected':'' }}>Kaptanlar</option>
                </select>
            </div>
            <div class="rc-field">
                <label>Tekil Kaynak</label>
                <select name="resource_id" class="f-select js-cselect" data-icon="fa-cube" onchange="this.form.submit()">
                    <option value="">Tüm Kaynaklar</option>
                    @foreach($resources as $res)
                        <option value="{{ $res->id }}" {{ request('resource_id')==$res->id ? 'selected':'' }}>[{{ $res->type==='guide'?'Rehber':($res->type==='vehicle'?'Araç':'Kaptan') }}] {{ $res->name }}</option>
                    @endforeach
                </select>
            </div>
            @if(request()->anyFilled(['type','resource_id']))
                <a href="{{ route('agency.resources.calendar', ['month'=>$currentMonth->format('Y-m')]) }}"
                   class="btn btn-outline-danger" style="border-radius:11px;height:40px;display:inline-flex;align-items:center;font-size:.8rem;font-weight:700">
                    <i class="fas fa-times me-1"></i>Temizle
                </a>
            @endif
        </form>
    </div>

    {{-- Açılır Bloke / İzin Ekle --}}
    <div class="rc-panel collapsed" id="rcAdd">
        <form id="add-block-form" class="rc-panel-inner">
            <div class="rc-field">
                <label>Kaynak *</label>
                <select name="resource_id" class="f-select" required>
                    <option value="">— Seçin —</option>
                    @foreach($resources as $res)
                        <option value="{{ $res->id }}">[{{ $res->type==='guide'?'Rehber':($res->type==='vehicle'?'Araç':'Kaptan') }}] {{ $res->name }}</option>
                    @endforeach
                </select>
            </div>
            <div class="rc-field sm">
                <label>Kısıtlama Tipi *</label>
                <select name="schedule_type" class="f-select" required>
                    <option value="block">Genel Bloke</option>
                    <option value="maintenance">Araç Bakım</option>
                    <option value="leave">İzin / Tatil</option>
                </select>
            </div>
            <div class="rc-field">
                <label>Başlık *</label>
                <input type="text" name="title" class="f-input" placeholder="İzinli, Serviste vb." required>
            </div>
            <div class="rc-field sm">
                <label>Başlangıç *</label>
                <input type="date" name="start_date" class="f-input" required>
            </div>
            <div class="rc-field sm">
                <label>Bitiş *</label>
                <input type="date" name="end_date" class="f-input" required>
            </div>
            <div class="rc-field">
                <label>Açıklama</label>
                <input type="text" name="description" class="f-input" placeholder="İsteğe bağlı...">
            </div>
            <button type="submit" class="rc-add-submit"><i class="fas fa-plus me-1"></i>Ekle</button>
        </form>
    </div>

    {{-- ── CALENDAR (tam genişlik) ── --}}
    <div>
            <div class="cal-card">
                {{-- Header --}}
                <div class="cal-head">
                    <a href="{{ route('agency.resources.calendar', array_merge(request()->except('month'), ['month'=>$prevMonth])) }}"
                       class="cal-nav-btn"><i class="fas fa-chevron-left"></i></a>
                    <div class="cal-title">
                        {{ $monthNames[$currentMonth->month] }} {{ $currentMonth->year }}
                    </div>
                    <div class="d-flex gap-2">
                        <a href="{{ route('agency.resources.calendar', array_merge(request()->except('month'), ['month'=>now()->format('Y-m')])) }}"
                           class="cal-nav-btn today">Bugün</a>
                        <a href="{{ route('agency.resources.calendar', array_merge(request()->except('month'), ['month'=>$nextMonth])) }}"
                           class="cal-nav-btn"><i class="fas fa-chevron-right"></i></a>
                    </div>
                </div>

                {{-- Day-of-week headers --}}
                <div class="cal-dow-row">
                    @foreach($dayNames as $dn)
                        <div class="cal-dow">{{ $dn }}</div>
                    @endforeach
                </div>

                {{-- Grid --}}
                <div class="cal-grid">
                    {{-- Empty cells before month start --}}
                    @for($e = 0; $e < $startDow; $e++)
                        <div class="cal-cell empty"></div>
                    @endfor

                    {{-- Day cells --}}
                    @for($d = 1; $d <= $daysInMonth; $d++)
                        @php
                            $cellDate  = $currentMonth->copy()->day($d);
                            $isToday   = $cellDate->isToday();
                            $isWeekend = $cellDate->isWeekend();
                            $scheds    = $daySchedules[$d] ?? collect();
                            $visibleN  = 3;
                        @endphp
                        <div class="cal-cell {{ $isToday ? 'today-cell' : '' }} {{ $isWeekend ? 'day-weekend' : '' }}"
                             onclick="showDayDetail({{ $d }})">
                            <div class="day-num">{{ $d }}</div>

                            @foreach($scheds->take($visibleN) as $s)
                                @php
                                    $tc = $typeColors[$s->schedule_type] ?? ['dot'=>'#94a3b8','bg'=>'#f1f5f9','text'=>'#475569','label'=>$s->schedule_type];
                                @endphp
                                <span class="sched-chip"
                                      style="background:{{ $tc['bg'] }};color:{{ $tc['text'] }}">
                                    {{ $s->resource->name }}
                                </span>
                            @endforeach

                            @if($scheds->count() > $visibleN)
                                <div class="more-badge">+{{ $scheds->count() - $visibleN }} daha</div>
                            @endif
                        </div>
                    @endfor

                    {{-- Trailing empty cells to complete last row --}}
                    @php $total = $startDow + $daysInMonth; $trail = (7 - $total % 7) % 7; @endphp
                    @for($t = 0; $t < $trail; $t++)
                        <div class="cal-cell empty"></div>
                    @endfor
                </div>
            </div>

            {{-- ── Day Detail Panel ── --}}
            <div class="day-detail" id="dayDetail">
                <div class="dd-head">
                    <div class="dd-title" id="ddTitle"></div>
                    <button class="dd-close" onclick="closeDayDetail()"><i class="fas fa-times"></i></button>
                </div>
                <div id="ddBody"></div>
            </div>
        </div>
</div>
@include('agency.partials.custom-select')
@endsection

@push('scripts')
<script>
// ── Day schedule data ──
const daySchedules = @json($daySchedulesJson);

const typeColors = @json($typeColors);
const typeLabels = {
    'tour_assignment':'Tur Görevi','block':'Genel Bloke','maintenance':'Araç Bakım','leave':'İzin / Tatil'
};
const monthName = '{{ $monthNames[$currentMonth->month] }} {{ $currentMonth->year }}';

// ── Yatay filtre panellerini aç/kapa (tercih hatırlanır) ──
(function () {
    function setup(btnId, panelId, storeKey, defaultCollapsed) {
        const btn = document.getElementById(btnId), panel = document.getElementById(panelId);
        if (!btn || !panel) return;
        let stored = localStorage.getItem(storeKey);
        let c = stored === null ? defaultCollapsed : stored === '1';
        panel.classList.toggle('collapsed', c);
        btn.classList.toggle('open', !c);
        btn.addEventListener('click', function () {
            c = !c;
            panel.classList.toggle('collapsed', c);
            btn.classList.toggle('open', !c);
            localStorage.setItem(storeKey, c ? '1' : '0');
        });
    }
    setup('rcFilterToggle', 'rcFilters', 'rcFiltersCollapsed', false);
    setup('rcAddToggle', 'rcAdd', 'rcAddCollapsed', true);
})();

function showDayDetail(day) {
    const panel = document.getElementById('dayDetail');
    const title = document.getElementById('ddTitle');
    const body  = document.getElementById('ddBody');
    const scheds = daySchedules[day] || [];

    title.textContent = day + ' ' + monthName;
    body.innerHTML = '';

    if (!scheds.length) {
        body.innerHTML = '<div style="text-align:center;padding:1.5rem;color:#94a3b8"><i class="fas fa-calendar-check fa-2x mb-2"></i><br>Bu günde kayıt bulunmuyor.</div>';
    } else {
        scheds.forEach(s => {
            const tc = typeColors[s.type] || {dot:'#94a3b8',bg:'#f1f5f9',text:'#475569'};
            const del = s.canDelete
                ? `<form method="POST" action="/agency/resources/schedule/${s.id}" style="display:inline" onsubmit="return confirmDel(event)">
                       <input type="hidden" name="_token" value="{{ csrf_token() }}">
                       <input type="hidden" name="_method" value="DELETE">
                       <button class="sched-del" title="Sil"><i class="fas fa-trash-alt"></i></button>
                   </form>` : '';
            body.innerHTML += `
                <div class="sched-row">
                    <span class="sched-dot" style="background:${tc.dot}"></span>
                    <div class="sched-info">
                        <div class="sched-name">${s.resource} – ${s.title}</div>
                        <div class="sched-sub">${s.start} → ${s.end}</div>
                    </div>
                    <span class="sched-badge" style="background:${tc.bg};color:${tc.text}">${typeLabels[s.type]||s.type}</span>
                    ${del}
                </div>`;
        });
    }

    panel.classList.add('show');
    panel.scrollIntoView({behavior:'smooth', block:'nearest'});
}

function closeDayDetail() {
    document.getElementById('dayDetail').classList.remove('show');
}

function confirmDel(e) {
    if (!confirm('Bu plan kaydını silmek istediğinize emin misiniz?')) e.preventDefault();
}

// ── Add block via AJAX ──
document.getElementById('add-block-form').addEventListener('submit', function(e) {
    e.preventDefault();
    const fd = new FormData(this);
    const data = {};
    fd.forEach((v,k) => data[k]=v);

    const url = new URL("{{ route('agency.resources.api.add-block') }}").pathname;
    fetch(url, {
        method:'POST',
        headers:{'Content-Type':'application/json','X-CSRF-TOKEN':'{{ csrf_token() }}'},
        body: JSON.stringify(data)
    })
    .then(r => r.json())
    .then(res => {
        if (res.success) {
            Swal.fire({icon:'success',title:'Eklendi',text:res.message,timer:2000,showConfirmButton:false})
                .then(() => location.reload());
        } else {
            Swal.fire({icon:'error',title:'Hata',text:res.message||'Bir sorun oluştu.'});
        }
    })
    .catch(() => Swal.fire({icon:'error',title:'Sunucu Hatası',text:'İşlem gerçekleştirilemedi.'}));
});
</script>
@endpush
