@extends('layouts.app-mobile')
@section('title', $booking->service->name ?? 'Booking — Befikreyy App')
@section('apptitle', '')
@section('appheaderright')
<a href="{{ route('app.bookings') }}" class="ah-back" aria-label="Back">‹</a>
@endsection

@section('content')

@if($booking->service && $booking->service->image)
<div class="app-detail-hero" style="background-image: url('/{{ $booking->service->image }}');"></div>
@endif

<div class="app-section app-pad">
    <span class="bk-status-pill bk-pill-{{ $booking->subscription_status }}">{{ ucfirst($booking->subscription_status) }}</span>
    <h1 class="app-detail-title">{{ $booking->service->name ?? 'Service' }}</h1>
    <p class="app-detail-tag">Subscription #{{ $booking->booking_code }}</p>

    <div class="bk-detail-card">
        <div class="bk-detail-row">
            <span>Monthly fee</span>
            <strong>₹{{ number_format($booking->total_rupees, 0) }}</strong>
        </div>
        <div class="bk-detail-row">
            <span>Started</span>
            <strong>{{ $booking->current_period_start ? $booking->current_period_start->format('d M Y') : '—' }}</strong>
        </div>
        <div class="bk-detail-row">
            <span>Next billing</span>
            <strong>{{ $booking->next_billing_date ? $booking->next_billing_date->format('d M Y') : '—' }}</strong>
        </div>
        <div class="bk-detail-row">
            <span>Auto-renew</span>
            <strong>{{ $booking->auto_renew ? 'On' : 'Off' }}</strong>
        </div>
        <div class="bk-detail-row">
            <span>Partner</span>
            <div class="cu-partner-info">
                <div class="cu-partner-avatar">
                    @if($booking->partner?->photo_url)
                        <img src="{{ $booking->partner->photo_url }}" alt="">
                    @else
                        {{ strtoupper(substr($booking->partner?->display_name ?? 'B', 0, 1)) }}
                    @endif
                </div>
                <div>
                    <strong>{{ $booking->partner && $booking->partner->user ? $booking->partner->user->name : 'To be assigned' }}</strong>
                    @if($booking->partner)
                        <div class="muted" style="font-size: 11.5px; margin-top: 2px;">
                            ★ {{ number_format($booking->partner->rating_avg ?? 0, 1) }} ({{ $booking->partner->rating_count ?? 0 }}) · {{ $booking->partner->jobs_done ?? 0 }} jobs
                        </div>
                    @endif
                </div>
            </div>
        </div>
        @if($booking->area)
        <div class="bk-detail-row">
            <span>Area</span>
            <strong>{{ $booking->area->name }}</strong>
        </div>
        @endif
        <div class="bk-detail-row bk-detail-address">
            <span>Address</span>
            <strong>{{ $booking->address }}</strong>
        </div>
    </div>

    <h3 class="app-detail-h3">Daily attendance ({{ $booking->visits->where('attendance_status', 'present')->count() }}/{{ $booking->visits->count() }} days)</h3>

    @php
        $visitsByDate = $booking->visits->keyBy(fn($v) => $v->scheduled_date->format('Y-m-d'));
        $photosByVisit = $booking->photos->whereNotNull('visit_id')->groupBy('visit_id');
    @endphp

    @if($booking->visits && $booking->visits->count())
        <div class="cu-att-timeline">
            @foreach($booking->visits->sortBy('scheduled_date') as $v)
                @php
                    $isPast = $v->scheduled_date->isPast();
                    $isToday = $v->scheduled_date->isToday();
                    $photos = $photosByVisit[$v->id] ?? collect();
                @endphp
                <div class="cu-att-row cu-att-{{ $v->attendance_status }} {{ $isToday ? 'cu-att-today' : '' }}">
                    <div class="cu-att-date">
                        <strong>{{ $v->scheduled_date->format('d') }}</strong>
                        <span>{{ $v->scheduled_date->format('M') }}</span>
                        <span class="cu-att-dow">{{ $v->scheduled_date->format('D') }}</span>
                    </div>
                    <div class="cu-att-line">
                        <span class="cu-att-dot"></span>
                    </div>
                    <div class="cu-att-body">
                        <div class="cu-att-head">
                            <strong>{{ $v->scheduled_slot }}</strong>
                            @if($v->attendance_status === 'present')
                                <span class="cu-att-pill cu-att-pill-green">
                                    <x-icon name="check" :size="11" /> Present
                                </span>
                            @elseif($v->attendance_status === 'absent')
                                <span class="cu-att-pill cu-att-pill-red">
                                    <x-icon name="close" :size="11" /> Absent
                                </span>
                            @elseif($v->attendance_status === 'late')
                                <span class="cu-att-pill cu-att-pill-orange">
                                    <x-icon name="info" :size="11" /> Late
                                </span>
                            @elseif($v->attendance_status === 'cancelled')
                                <span class="cu-att-pill cu-att-pill-grey">
                                    <x-icon name="close" :size="11" /> Cancelled
                                </span>
                            @else
                                <span class="cu-att-pill cu-att-pill-gold">
                                    <x-icon name="calendar" :size="11" /> {{ $isToday ? 'Today' : 'Upcoming' }}
                                </span>
                            @endif
                        </div>
                        @if($v->attendance_status === 'present')
                            <div class="cu-att-meta">
                                @if($v->arrival_time)
                                    <span><x-icon name="info" :size="11" /> In: {{ \Carbon\Carbon::parse($v->arrival_time)->format('h:i A') }}</span>
                                @endif
                                @if($v->departure_time)
                                    <span><x-icon name="info" :size="11" /> Out: {{ \Carbon\Carbon::parse($v->departure_time)->format('h:i A') }}</span>
                                @endif
                            </div>
                            @if($v->attendance_note)
                                <p class="cu-att-note">{{ $v->attendance_note }}</p>
                            @endif
                            @if($photos->count())
                                <div class="cu-att-photos">
                                    @foreach($photos as $p)
                                        <a href="{{ asset('storage/' . $p->photo_path) }}" target="_blank" class="cu-att-photo">
                                            <img src="{{ asset('storage/' . $p->photo_path) }}" alt="" loading="lazy">
                                        </a>
                                    @endforeach
                                </div>
                            @elseif($v->scheduled_date->isPast())
                                <p class="cu-att-no-photo"><x-icon name="camera" :size="11" /> No photos uploaded for this day</p>
                            @endif
                        @elseif($v->attendance_status === 'absent')
                            @if($v->attendance_note)
                                <p class="cu-att-note">Reason: {{ $v->attendance_note }}</p>
                            @else
                                <p class="cu-att-note">{{ $v->auto_absent_marked ? 'Auto-marked absent (no partner attendance)' : 'Marked absent' }}</p>
                            @endif
                        @elseif($isPast && $v->attendance_status === 'pending')
                            <div class="cu-att-meta">
                                <span class="cu-att-pill cu-att-pill-red" style="background: rgba(221,51,51,0.08); color: #d33;">
                                    <x-icon name="info" :size="11" /> Awaiting attendance
                                </span>
                            </div>
                        @endif
                    </div>
                </div>
            @endforeach
        </div>
    @else
        <p class="muted">No visits scheduled yet.</p>
    @endif

    <h3 class="app-detail-h3">Manage subscription</h3>
    <div class="bk-actions">
        @if($booking->subscription_status === 'active')
            <form method="POST" action="{{ route('app.booking.pause', $booking->booking_code) }}">
                @csrf
                <button type="submit" class="btn-app btn-app-outline btn-app-full">⏸ Pause subscription</button>
            </form>
        @elseif($booking->subscription_status === 'paused')
            <form method="POST" action="{{ route('app.booking.resume', $booking->booking_code) }}">
                @csrf
                <button type="submit" class="btn-app btn-app-primary btn-app-full">▶ Resume subscription</button>
            </form>
        @endif

        @if(in_array($booking->subscription_status, ['active', 'paused']))
            <button type="button" class="btn-app btn-app-danger-outline btn-app-full" onclick="document.getElementById('cancelSheet').classList.add('open')">
                ✕ Cancel subscription
            </button>
        @endif
    </div>

    <h3 class="app-detail-h3">Rate this service</h3>
    @if($booking->rating)
        <div class="rate-summary">
            <span class="rate-num">{{ $booking->rating->stars }}</span>
            <span class="rate-stars">
                @for($i=1;$i<=5;$i++)<span class="{{ $i <= $booking->rating->stars ? 'on' : '' }}">★</span>@endfor
            </span>
            <p>{{ $booking->rating->review ?: 'No written review.' }}</p>
        </div>
    @else
        <form method="POST" action="{{ route('app.booking.rate', $booking->booking_code) }}" class="rate-form">
            @csrf
            <div class="rate-stars-input" id="rateStarsInput">
                @for($i=1;$i<=5;$i++)
                    <button type="button" class="rs-btn" data-val="{{ $i }}" onclick="rateSet({{ $i }})">★</button>
                @endfor
            </div>
            <input type="hidden" name="stars" id="rateVal" required>
            <textarea name="review" placeholder="Share your experience (optional)" rows="2"></textarea>
            <button type="submit" class="btn-app btn-app-primary btn-app-full">Submit rating</button>
        </form>
    @endif

</div>

{{-- Cancel confirmation bottom sheet --}}
@if(in_array($booking->subscription_status, ['active', 'paused']))
<div class="bottom-sheet" id="cancelSheet">
    <div class="sheet-backdrop" onclick="document.getElementById('cancelSheet').classList.remove('open')"></div>
    <div class="sheet-content">
        <div class="sheet-handle"></div>
        <h3>Cancel subscription?</h3>
        <p>This will stop all future renewals and cancel any scheduled visits. You can re-subscribe later.</p>
        <form method="POST" action="{{ route('app.booking.cancel', $booking->booking_code) }}">
            @csrf
            <button type="submit" class="btn-app btn-app-danger btn-app-full">Yes, cancel subscription</button>
        </form>
        <button type="button" class="btn-app btn-app-outline btn-app-full" onclick="document.getElementById('cancelSheet').classList.remove('open')" style="margin-top: 8px;">Keep subscription</button>
    </div>
</div>
@endif

@push('scripts')
<script>
function rateSet(n) {
    document.getElementById('rateVal').value = n;
    var btns = document.querySelectorAll('#rateStarsInput .rs-btn');
    btns.forEach(function(b, i) {
        b.classList.toggle('on', i < n);
    });
}
</script>
@endpush

@endsection