@extends('layouts.app-shell')
@section('title', 'Subscription ' . $booking->booking_code)
@section('sidebar')
    @include('admin._sidebar')
@endsection
@section('bottomnav')
    <a href="{{ route('admin.dashboard') }}" class="{{ request()->routeIs('admin.dashboard*') ? 'active' : '' }}"><x-icon name="home" :size="20" /><span>Home</span></a>
    <a href="{{ route('admin.bookings') }}" class="{{ request()->routeIs('admin.bookings*') ? 'active' : '' }}"><x-icon name="bookings" :size="20" /><span>Subs</span></a>
    <a href="{{ route('admin.partners') }}" class="{{ request()->routeIs('admin.partners*') ? 'active' : '' }}"><x-icon name="profile" :size="20" /><span>Partners</span></a>
    <a href="{{ route('admin.services.index') }}" class="{{ request()->routeIs('admin.services*') ? 'active' : '' }}"><x-icon name="services" :size="20" /><span>Catalogue</span></a>
@endsection

@section('content')
<div class="flex-between mb-3">
    <div>
        <a href="{{ route('admin.bookings') }}" class="btn btn-ghost btn-sm">← All subscriptions</a>
        <h2 style="font-size: 22px; font-weight: 700; margin-top: 8px;">{{ $booking->service->name ?? 'Service' }}</h2>
        <p class="muted" style="font-size: 13px;">Booking #{{ $booking->booking_code }} · {{ $booking->customer_name }} · {{ $booking->customer_phone }}</p>
    </div>
    <span class="pill pill-{{ $booking->status_color }}" style="font-size: 13px; padding: 6px 14px;">{{ $booking->display_status }}</span>
</div>

<div class="grid-2" style="grid-template-columns: 1.5fr 1fr; gap: 18px;">
    <div>
        <div class="panel">
            <div class="panel-head"><h3>Subscription details</h3></div>
            <div class="form-grid">
                <div>
                    <div class="muted" style="font-size: 11.5px; text-transform: uppercase; letter-spacing: 0.04em;">Service</div>
                    <strong>{{ $booking->service->name ?? '—' }}</strong>
                </div>
                <div>
                    <div class="muted" style="font-size: 11.5px; text-transform: uppercase; letter-spacing: 0.04em;">Customer</div>
                    <strong>{{ $booking->customer_name }}</strong>
                    <div class="muted" style="font-size: 12px;">{{ $booking->customer_phone }}</div>
                </div>
                <div>
                    <div class="muted" style="font-size: 11.5px; text-transform: uppercase; letter-spacing: 0.04em;">Period</div>
                    <strong>{{ $booking->current_period_start?->format('d M') }} – {{ $booking->current_period_end?->format('d M Y') }}</strong>
                </div>
                <div>
                    <div class="muted" style="font-size: 11.5px; text-transform: uppercase; letter-spacing: 0.04em;">Next renewal</div>
                    <strong>{{ $booking->next_billing_date?->format('d M Y') ?? '—' }}</strong>
                    <div class="muted" style="font-size: 12px;">{{ $booking->auto_renew ? 'Auto-renews' : 'Will not renew' }}</div>
                </div>
                <div>
                    <div class="muted" style="font-size: 11.5px; text-transform: uppercase; letter-spacing: 0.04em;">Monthly</div>
                    <strong style="color: var(--bfk-primary); font-size: 20px;">₹{{ number_format($booking->total_rupees, 0) }}</strong>
                </div>
                <div>
                    <div class="muted" style="font-size: 11.5px; text-transform: uppercase; letter-spacing: 0.04em;">Visits used</div>
                    <strong>{{ $booking->visits_used ?? 0 }} / {{ $booking->visits_per_period ?? 1 }}</strong>
                </div>
                <div style="grid-column: 1 / -1;">
                    <div class="muted" style="font-size: 11.5px; text-transform: uppercase; letter-spacing: 0.04em;">Address</div>
                    <strong>{{ $booking->address }}</strong>
                    <div class="muted" style="font-size: 12px;">{{ $booking->area->name }}@if($booking->pincode) · {{ $booking->pincode }}@endif</div>
                </div>
            </div>
        </div>

        <div class="panel">
            <div class="panel-head">
                <h3>Subscription timeline</h3>
                <span class="muted" style="font-size: 12px;">{{ $booking->visits_per_period }} visit{{ $booking->visits_per_period > 1 ? 's' : '' }} per {{ $booking->billing_period }}</span>
            </div>

            {{-- Next visit callout --}}
            <div class="next-visit-callout">
                <div class="nvc-ic">
                    <x-icon name="calendar" :size="22" />
                </div>
                <div class="nvc-body">
                    @if($nextVisit)
                        <div class="nvc-eyebrow">Next scheduled visit</div>
                        <div class="nvc-when">
                            <strong>{{ $nextVisit->scheduled_date->format('l, d M Y') }}</strong>
                            <span class="nvc-sep">·</span>
                            <span class="nvc-slot">{{ $nextVisit->scheduled_slot }}</span>
                        </div>
                        <div class="nvc-meta">
                            <span class="pill pill-{{ $nextVisit->status_color }}" style="font-size: 10px; padding: 2px 8px;">
                                {{ str_replace('_', ' ', $nextVisit->status) }}
                            </span>
                            <span class="muted">
                                @if($nextVisit->scheduled_date->isToday())
                                    <span class="nvc-today">TODAY</span>
                                @elseif($nextVisit->scheduled_date->isTomorrow())
                                    <span class="nvc-today">TOMORROW</span>
                                @else
                                    in {{ now()->startOfDay()->diffInDays($nextVisit->scheduled_date->startOfDay()) }} days
                                @endif
                            </span>
                            <span class="muted">·</span>
                            <span class="muted">Partner: <strong>{{ $booking->partner?->display_name ?? 'Unassigned' }}</strong></span>
                        </div>
                    @else
                        <div class="nvc-eyebrow">No upcoming visit</div>
                        <strong>Schedule one below to activate the subscription.</strong>
                    @endif
                </div>
                @if($nextVisit)
                    <form method="POST" action="{{ route('admin.bookings.visits.destroy', [$booking, $nextVisit]) }}" onsubmit="return confirm('Cancel this upcoming visit?');">
                        @csrf @method('DELETE')
                        <button type="submit" class="ic-btn ic-delete" title="Cancel upcoming visit">
                            <x-icon name="trash" :size="14" />
                        </button>
                    </form>
                @endif
            </div>

            {{-- Multi-month schedule preview with full date grids --}}
            <div class="schedule-grid">
                @foreach($schedule as $period)
                    <div class="sched-card sched-{{ $period['status'] }}">
                        <div class="sched-head">
                            <strong>{{ $period['label'] }}</strong>
                            <div class="sched-head-right">
                                <span class="muted" style="font-size: 11px; margin-right: 4px;">
                                    {{ $period['stats']['completed'] }}/{{ $period['stats']['total'] }} done
                                </span>
                                @if($period['is_current'])
                                    <span class="pill pill-green" style="font-size: 10px; padding: 2px 8px;">Current</span>
                                @elseif($period['status'] === 'past')
                                    <span class="pill pill-grey" style="font-size: 10px; padding: 2px 8px;">Past</span>
                                @else
                                    <span class="pill pill-gold" style="font-size: 10px; padding: 2px 8px;">Upcoming</span>
                                @endif
                            </div>
                        </div>

                        {{-- Month-grid calendar --}}
                        <div class="sched-cal">
                            <div class="sched-wd-row">
                                @foreach(['Mon','Tue','Wed','Thu','Fri','Sat','Sun'] as $wd)
                                    <div class="sched-wd">{{ $wd }}</div>
                                @endforeach
                            </div>
                            <div class="sched-cal-grid">
                                @foreach($period['cells'] as $cell)
                                    <div class="sched-cell {{ $cell['in_month'] ? '' : 'is-other-month' }} {{ $cell['is_today'] ? 'is-today' : '' }} {{ $cell['visit'] ? 'has-visit' : '' }} sched-visit-{{ $cell['visit']?->status ?? 'none' }}"
                                         @if($cell['visit']) title="{{ $cell['visit']->scheduled_slot }} · {{ ucfirst(str_replace('_',' ', $cell['visit']->status)) }}" @endif>
                                        <span class="sched-cell-num">{{ $cell['date']->format('j') }}</span>
                                        @if($cell['visit'])
                                            <span class="sched-cell-dot"></span>
                                        @endif
                                    </div>
                                @endforeach
                            </div>
                        </div>

                        {{-- Visit list for this month --}}
                        @if($period['visits']->count())
                            <div class="sched-visits-list">
                                @foreach($period['visits'] as $v)
                                    <div class="sched-vis-row sched-vis-{{ $v->status }}">
                                        <div class="sched-vis-main">
                                            <span class="sched-vis-date">{{ $v->scheduled_date->format('d M, D') }}</span>
                                            <span class="sched-vis-slot">{{ $v->scheduled_slot }}</span>
                                        </div>
                                        <span class="pill pill-{{ $v->status_color }}" style="font-size: 10px; padding: 2px 8px;">{{ str_replace('_', ' ', $v->status) }}</span>
                                    </div>
                                @endforeach
                            </div>
                        @else
                            <div class="sched-empty">
                                <span class="muted" style="font-size: 12px;">No visits scheduled</span>
                                @if($period['is_current'] || $period['status'] === 'future')
                                    <button type="button" class="btn btn-ghost btn-sm" onclick="document.getElementById('addVisit-{{ $period['index'] }}').style.display='block'">+ Add visit</button>
                                @endif
                            </div>
                        @endif

                        @if($period['is_current'] || $period['status'] === 'future')
                            <form id="addVisit-{{ $period['index'] }}" method="POST" action="{{ route('admin.bookings.visits.create', $booking) }}" class="sched-add-form" style="display: none;">
                                @csrf
                                <input type="date" name="scheduled_date" value="{{ $period['start']->format('Y-m-d') }}" required min="{{ $period['start']->format('Y-m-d') }}" max="{{ $period['end']->format('Y-m-d') }}">
                                <select name="scheduled_slot" required>
                                    <option value="09:00 AM - 10:00 AM">9–10 AM</option>
                                    <option value="10:00 AM - 11:00 AM" selected>10–11 AM</option>
                                    <option value="11:00 AM - 12:00 PM">11–12 PM</option>
                                    <option value="02:00 PM - 03:00 PM">2–3 PM</option>
                                    <option value="03:00 PM - 04:00 PM">3–4 PM</option>
                                    <option value="04:00 PM - 05:00 PM">4–5 PM</option>
                                    <option value="05:00 PM - 06:00 PM">5–6 PM</option>
                                </select>
                                <button type="submit" class="btn btn-primary btn-sm">Add</button>
                                <button type="button" class="btn btn-ghost btn-sm" onclick="document.getElementById('addVisit-{{ $period['index'] }}').style.display='none'">Cancel</button>
                            </form>
                        @endif
                    </div>
                @endforeach
            </div>

            <div class="muted" style="font-size: 12px; margin-top: 14px; padding-top: 12px; border-top: 1px dashed var(--bfk-border);">
                <x-icon name="info" :size="13" />
                Monthly subscription renews on
                <strong>{{ $booking->next_billing_date?->format('d M Y') ?? '—' }}</strong>
                · {{ $booking->auto_renew ? 'auto-renew enabled' : 'will not auto-renew' }} ·
                {{ $booking->visits->count() }} visit{{ $booking->visits->count() == 1 ? '' : 's' }} scheduled across all periods
            </div>
        </div>

        @if($booking->visits->count())
        <div class="panel">
            <div class="panel-head">
                <h3>All visits ({{ $booking->visits->count() }})</h3>
                <span class="muted" style="font-size: 12px;">Recently updated first</span>
            </div>
            <div class="table-wrap">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Slot</th>
                            <th>Status</th>
                            <th>Started</th>
                            <th>Completed</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($booking->visits->sortByDesc('scheduled_date') as $v)
                            <tr>
                                <td data-label="Date"><strong>{{ $v->scheduled_date->format('d M Y') }}</strong></td>
                                <td data-label="Slot">{{ $v->scheduled_slot }}</td>
                                <td data-label="Status"><span class="pill pill-{{ $v->status_color }}">{{ str_replace('_',' ', $v->status) }}</span></td>
                                <td data-label="Started" class="muted" style="font-size: 12.5px;">{{ $v->started_at?->format('d M H:i') ?? '—' }}</td>
                                <td data-label="Completed" class="muted" style="font-size: 12.5px;">{{ $v->completed_at?->format('d M H:i') ?? '—' }}</td>
                                <td data-label="Actions">
                                    @if(!in_array($v->status, ['completed', 'cancelled']))
                                        <button type="button" class="ic-btn ic-edit" onclick="document.getElementById('editVisit-{{ $v->id }}').style.display='table-row'" title="Reschedule">
                                            <x-icon name="edit" :size="14" />
                                        </button>
                                        <form method="POST" action="{{ route('admin.bookings.visits.destroy', [$booking, $v]) }}" style="display:inline;" onsubmit="return confirm('Cancel this visit?');">
                                            @csrf @method('DELETE')
                                            <button type="submit" class="ic-btn ic-delete" title="Cancel visit">
                                                <x-icon name="trash" :size="14" />
                                            </button>
                                        </form>
                                    @else
                                        <span class="muted" style="font-size: 11px;">—</span>
                                    @endif
                                </td>
                            </tr>
                            @if(!in_array($v->status, ['completed', 'cancelled']))
                                <tr id="editVisit-{{ $v->id }}" style="display:none; background: var(--bfk-bg-soft);">
                                    <td colspan="6">
                                        <form method="POST" action="{{ route('admin.bookings.visits.update', [$booking, $v]) }}" class="inline-form">
                                            @csrf @method('PATCH')
                                            <div class="field" style="display:inline-block; margin-right: 8px;">
                                                <label>New date</label>
                                                <input type="date" name="scheduled_date" value="{{ $v->scheduled_date->format('Y-m-d') }}" required>
                                            </div>
                                            <div class="field" style="display:inline-block; margin-right: 8px;">
                                                <label>Slot</label>
                                                <select name="scheduled_slot" required>
                                                    @php $slots = ['09:00 AM - 10:00 AM', '10:00 AM - 11:00 AM', '11:00 AM - 12:00 PM', '02:00 PM - 03:00 PM', '03:00 PM - 04:00 PM', '04:00 PM - 05:00 PM', '05:00 PM - 06:00 PM']; @endphp
                                                    @foreach($slots as $slot)
                                                        <option value="{{ $slot }}" @selected($v->scheduled_slot === $slot)>{{ $slot }}</option>
                                                    @endforeach
                                                </select>
                                            </div>
                                            <button type="submit" class="btn btn-primary btn-sm">Save</button>
                                            <button type="button" class="btn btn-ghost btn-sm" onclick="document.getElementById('editVisit-{{ $v->id }}').style.display='none'">Cancel</button>
                                        </form>
                                    </td>
                                </tr>
                            @endif
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
        @endif

        @if($booking->photos->count())
            <div class="panel">
                <div class="panel-head"><h3>Visit photos ({{ $booking->photos->count() }})</h3></div>
                <div class="photo-grid">
                    @foreach($booking->photos as $p)
                        <div>
                            <img src="{{ asset('storage/' . $p->photo_path) }}" alt="">
                            <div class="muted" style="font-size: 11.5px; margin-top: 4px;">{{ $p->stage }} · {{ $p->created_at->format('d M H:i') }}</div>
                        </div>
                    @endforeach
                </div>
            </div>
        @endif

        @if($booking->statusLogs && $booking->statusLogs->count())
            <div class="panel">
                <div class="panel-head"><h3>Status history</h3></div>
                <div class="table-wrap">
                    <table class="table">
                        <thead>
                            <tr><th>When</th><th>Status</th><th>Note</th></tr>
                        </thead>
                        <tbody>
                            @foreach($booking->statusLogs as $log)
                                <tr>
                                    <td data-label="When" class="muted">{{ $log->created_at->format('d M H:i') }}</td>
                                    <td data-label="Status"><span class="pill pill-grey">{{ $log->status }}</span></td>
                                    <td data-label="Note">{{ $log->note ?? '—' }}</td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            </div>
        @endif
    </div>

    <div>
        <div class="panel">
            <div class="panel-head"><h3>Assign partner</h3></div>
            @if($booking->partner_id)
                <p>Currently assigned: <strong>{{ $booking->partner?->display_name }}</strong></p>
                <form method="POST" action="{{ route('admin.bookings.assign', $booking) }}" class="mt-2">
                    @csrf
                    <div class="field">
                        <label>Switch partner</label>
                        <select name="partner_id" required>
                            <option value="">Choose a partner...</option>
                            @foreach(\App\Models\PartnerProfile::approved()->with('user')->get() as $p)
                                <option value="{{ $p->id }}" @selected($booking->partner_id === $p->id)>{{ $p->display_name }} ({{ $p->user->phone }})</option>
                            @endforeach
                        </select>
                    </div>
                    <button class="btn btn-primary btn-block">Reassign</button>
                </form>
            @else
                <form method="POST" action="{{ route('admin.bookings.assign', $booking) }}">
                    @csrf
                    <div class="field">
                        <label>Choose partner</label>
                        <select name="partner_id" required>
                            <option value="">Choose a partner...</option>
                            @foreach(\App\Models\PartnerProfile::approved()->with('user')->get() as $p)
                                <option value="{{ $p->id }}">{{ $p->display_name }} ({{ $p->user->phone }})</option>
                            @endforeach
                        </select>
                    </div>
                    <button class="btn btn-primary btn-block">Assign partner</button>
                </form>
            @endif
        </div>

        <div class="panel">
            <div class="panel-head"><h3>Subscription actions</h3></div>
            <form method="POST" action="{{ route('admin.bookings.cancel', $booking) }}" onsubmit="return confirm('Cancel this subscription?');">
                @csrf <button class="btn btn-outline btn-block" style="border-color: var(--bfk-red); color: var(--bfk-red);">Cancel subscription</button>
            </form>
        </div>

        @if($booking->rating)
            <div class="panel">
                <div class="panel-head"><h3>Customer rating</h3></div>
                <div style="color: var(--bfk-gold); font-size: 22px; margin-bottom: 6px;">{{ str_repeat('★', $booking->rating->rating) }}{{ str_repeat('☆', 5 - $booking->rating->rating) }}</div>
                <p class="muted" style="font-size: 13.5px;">{{ $booking->rating->review ?? 'No written review.' }}</p>
            </div>
        @endif
    </div>
</div>
@endsection
