@extends('layouts.app')
@section('title','Calendar')
@section('content')
@php
    $filters = [];
    if(request()->filled('from')) $filters[] = ['label'=>'From','value'=>\Carbon\CarbonImmutable::parse($from)->format('d M Y'),'removeUrl'=>route('calendar.index',request()->except('from'))];
    if(request()->filled('to')) $filters[] = ['label'=>'To','value'=>\Carbon\CarbonImmutable::parse($to)->format('d M Y'),'removeUrl'=>route('calendar.index',request()->except('to'))];
    if(request()->filled('type')) $filters[] = ['label'=>'Type','value'=>$types[$selectedType] ?? $selectedType,'removeUrl'=>route('calendar.index',request()->except('type'))];
    if(request()->has('branch_ids')) {
        $selectedBranchNames = $branches->whereIn('id',$selectedBranchIds)->pluck('name');
        $filters[] = [
            'label'=>'Branches',
            'value'=>$selectedBranchIds->count() === $branches->count() ? 'All branches' : $selectedBranchNames->join(', '),
            'removeUrl'=>route('calendar.index',request()->except('branch_ids')),
        ];
    }
    $branchFilterLabel = $selectedBranchIds->count() === $branches->count()
        ? 'All branches'
        : ($selectedBranchIds->count() === 1 ? ($branches->firstWhere('id',$selectedBranchIds->first())?->name ?? '1 branch') : $selectedBranchIds->count().' branches');
@endphp

<x-ui.page-toolbar title="Management Calendar" description="Loan dates, tasks, appointments, payroll, expense dues and document expiries in one branch-scoped calendar." :breadcrumbs="[['label'=>'Dashboard','url'=>route('dashboard')],['label'=>'Calendar']]">
    <x-slot:actions>@can('tasks.view')<a class="mf-btn" href="{{ route('tasks.index') }}">Tasks</a>@endcan</x-slot:actions>
</x-ui.page-toolbar>

<x-ui.table-toolbar
    table-id="calendar-events"
    :filter-names="['from','to','type','branch_ids']"
    :show-search="false"
    :show-export="false"
>
    <x-slot:filters>
        <input
            class="mf-filter-control"
            style="min-width:142px;padding-right:8px;"
            type="date"
            name="from"
            value="{{ $from }}"
            aria-label="Calendar start date"
            title="From date"
        >
        <input
            class="mf-filter-control"
            style="min-width:142px;padding-right:8px;"
            type="date"
            name="to"
            value="{{ $to }}"
            aria-label="Calendar end date"
            title="To date"
        >
        <select class="mf-filter-control" name="type" aria-label="Filter by event type">
            <option value="">All event types</option>
            @foreach($types as $key=>$label)<option value="{{ $key }}" @selected($selectedType===$key)>{{ $label }}</option>@endforeach
        </select>
        <details class="mf-columns-menu">
            <summary class="mf-filter-control flex cursor-pointer items-center justify-between gap-2" style="min-width:150px;">
                <span class="truncate">{{ $branchFilterLabel }}</span>
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:13px;height:13px;flex:0 0 auto;"><path d="m6 9 6 6 6-6"/></svg>
            </summary>
            <div class="mf-columns-popover" style="left:0;right:auto;width:230px;">
                <div class="mf-columns-title">Branches</div>
                @foreach($branches as $branch)
                    <label>
                        <input type="checkbox" name="branch_ids[]" value="{{ $branch->id }}" @checked($selectedBranchIds->contains($branch->id))>
                        <span class="truncate">{{ $branch->name }}</span>
                    </label>
                @endforeach
            </div>
        </details>
    </x-slot:filters>
</x-ui.table-toolbar>

<x-ui.applied-filter-chips :filters="$filters" :clear-url="route('calendar.index')" />

<div class="grid gap-4 lg:grid-cols-3">
    <div class="lg:col-span-2 space-y-3">
        @forelse($eventsByDate as $date=>$dayEvents)
        <div class="mf-card">
            <div class="border-b px-4 py-3"><div class="font-semibold">{{ \Carbon\CarbonImmutable::parse($date)->format('D, d M Y') }}</div><div class="text-xs text-muted-foreground">{{ $dayEvents->count() }} event(s)</div></div>
            <div class="divide-y">
                @foreach($dayEvents as $event)
                <a href="{{ $event['url'] }}" class="block px-4 py-3 hover:bg-muted/40">
                    <div class="flex flex-wrap items-start justify-between gap-2"><div><div class="font-medium">{{ $event['title'] }}</div><div class="mt-0.5 text-xs text-muted-foreground">{{ $event['subtitle'] }}</div></div><span class="mf-badge">{{ $event['type_label'] }}</span></div>
                    <div class="mt-2 flex flex-wrap gap-3 text-xs text-muted-foreground"><span>{{ $event['time'] ?: 'All day' }}</span><span>{{ $event['branch'] }}</span><span>{{ str($event['status'])->replace('_',' ')->headline() }}</span></div>
                </a>
                @endforeach
            </div>
        </div>
        @empty<div class="mf-card mf-card-body text-center text-muted-foreground">No calendar events match the selected period and branch scope.</div>@endforelse
    </div>

    <div class="space-y-4">
        <div class="mf-card mf-card-body"><div class="text-sm font-semibold">Calendar sources</div><div class="mt-3 space-y-2 text-xs text-muted-foreground">@foreach($types as $label)<div>{{ $label }}</div>@endforeach</div></div>
        @can('appointments.create')
        <div class="mf-card mf-card-body">
            <div class="text-sm font-semibold">New customer appointment</div>
            <p class="mt-1 text-xs text-muted-foreground">Schedule a customer visit and optionally assign a staff member.</p>

            <form method="POST" action="{{ route('calendar.appointments.store') }}" class="mf-form mt-4" data-standard-form>
                @csrf

                <div>
                    <label class="mf-field-label" for="appointment-branch">Branch</label>
                    <select id="appointment-branch" class="mf-input" name="branch_id" required>
                        <option value="">Select branch</option>
                        @foreach($branches as $branch)<option value="{{ $branch->id }}">{{ $branch->name }}</option>@endforeach
                    </select>
                </div>

                <div>
                    <label class="mf-field-label" for="appointment-customer">Customer</label>
                    <select id="appointment-customer" class="mf-input" name="customer_id" required>
                        <option value="">Select customer</option>
                        @foreach($customers as $customer)<option value="{{ $customer->id }}">{{ $customer->full_name }} · {{ $customer->customer_number }}</option>@endforeach
                    </select>
                </div>

                <div>
                    <label class="mf-field-label" for="appointment-staff">Assigned staff</label>
                    <select id="appointment-staff" class="mf-input" name="staff_id">
                        <option value="">Unassigned</option>
                        @foreach($staff as $user)<option value="{{ $user->id }}">{{ $user->name }}</option>@endforeach
                    </select>
                </div>

                <div>
                    <label class="mf-field-label" for="appointment-title">Appointment title</label>
                    <input id="appointment-title" class="mf-input" name="title" required placeholder="Enter appointment title">
                </div>

                <div>
                    <label class="mf-field-label" for="appointment-purpose">Purpose</label>
                    <input id="appointment-purpose" class="mf-input" name="purpose" placeholder="Enter purpose">
                </div>

                <div>
                    <label class="mf-field-label" for="appointment-scheduled-at">Date & time</label>
                    <input id="appointment-scheduled-at" class="mf-input" type="datetime-local" name="scheduled_at" required>
                </div>

                <div>
                    <label class="mf-field-label" for="appointment-notes">Notes</label>
                    <textarea id="appointment-notes" class="mf-input" rows="4" name="notes" placeholder="Add optional notes"></textarea>
                </div>

                <button class="mf-btn mf-btn-primary w-full" type="submit">Add appointment</button>
            </form>
        </div>
        @endcan
    </div>
</div>
@endsection