@extends('layouts.app-shell')
@section('bottomnav')
    <a href="{{ route('partner.dashboard') }}"><span class="ic">📊</span><span>Home</span></a>
    <a href="{{ route('partner.bookings') }}"><span class="ic">📋</span><span>Bookings</span></a>
    <a href="{{ route('partner.schedule') }}"><span class="ic">📅</span><span>Schedule</span></a>
    <a href="{{ route('partner.team') }}"><span class="ic">👥</span><span>Team</span></a>
    <a href="{{ route('partner.profile') }}"><span class="ic">👤</span><span>Profile</span></a>
@endsection
@section('title', 'Visit #' . $visit->id)
@section('sidebar')
    <a href="{{ route('partner.dashboard') }}"><span class="ic">📊</span> Dashboard</a>
    <a href="{{ route('partner.bookings') }}"><span class="ic">📋</span> My bookings</a>
    <a href="{{ route('partner.schedule') }}"><span class="ic">📅</span> Schedule</a>
    <a href="{{ route('partner.attendance') }}"><span class="ic">📍</span> Attendance</a>
    <a href="{{ route('partner.leaves') }}"><span class="ic">🏖</span> Leaves</a>
    <a href="{{ route('partner.team') }}"><span class="ic">👥</span> My team</a>
    <a href="{{ route('partner.earnings') }}"><span class="ic">💰</span> Earnings</a>
    <a href="{{ route('partner.profile') }}"><span class="ic">👤</span> Profile</a>
    <a href="{{ route('logout') }}" onclick="event.preventDefault(); document.getElementById('lo').submit()"><span class="ic">⤴</span> Logout</a>
    <form id="lo" method="POST" action="{{ route('logout') }}" style="display:none">@csrf</form>
@endsection
@section('content')

@if(session('success'))
    <div class="alert alert-success" style="margin-bottom: 18px;">{{ session('success') }}</div>
@endif
@if(session('error'))
    <div class="alert alert-error" style="margin-bottom: 18px;">{{ session('error') }}</div>
@endif

@php
    $visit->load(['booking.service', 'booking.customer', 'booking.area', 'booking.photos', 'teamMember']);
    $teamMembers = $profile->activeTeamMembers()->orderBy('name')->get();
    $photos = $visit->booking->photos->where('visit_id', $visit->id);
    $flow = ['accepted' => 'on_the_way', 'on_the_way' => 'arrived', 'arrived' => 'in_progress', 'in_progress' => 'completed'];
    $next = $flow[$visit->status] ?? null;
    $commission = \App\Services\CommissionService::forVisit($visit);
    $commissionPercent = \App\Services\CommissionService::effectivePercentFor($profile);
@endphp

<div class="flex-between mb-3">
    <div>
        <a href="{{ route('partner.schedule') }}" class="btn btn-ghost btn-sm">← Schedule</a>
        <h2 style="font-size: 22px; font-weight: 700; margin-top: 8px;">Visit #{{ $visit->id }}</h2>
        <p class="muted" style="font-size: 13px;">{{ $visit->scheduled_date->format('D, d M Y') }} · {{ $visit->scheduled_slot }}</p>
    </div>
    <span class="pill pill-{{ $visit->status_color }}" style="font-size: 13px; padding: 6px 14px;">{{ str_replace('_', ' ', $visit->status) }}</span>
</div>

<div class="grid-2" style="grid-template-columns: 1.4fr 1fr;">
    <div>
        {{-- Visit details --}}
        <div class="panel">
            <div class="panel-head">
                <h3><x-icon name="info" :size="14" style="color: var(--bfk-primary);" /> Visit details</h3>
                <a href="{{ route('partner.booking.show', $visit->booking->booking_code) }}" class="muted" style="font-size: 12px;">Subscription {{ $visit->booking->booking_code }} →</a>
            </div>
            <table class="table">
                <tbody>
                    <tr><td><strong>Service</strong></td><td>{{ $visit->booking->service->name ?? '—' }}</td></tr>
                    <tr><td><strong>Customer</strong></td><td>{{ $visit->booking->customer_name }}<div class="muted" style="font-size: 12px;">{{ $visit->booking->customer_phone }}</div></td></tr>
                    <tr><td><strong>Address</strong></td><td>{{ $visit->booking->address }}<div class="muted" style="font-size: 12px;">{{ $visit->booking->area->name ?? '' }}@if($visit->booking->pincode) · {{ $visit->booking->pincode }}@endif</div></td></tr>
                    <tr><td><strong>Slot</strong></td><td>{{ $visit->scheduled_slot }}</td></tr>
                    <tr><td><strong>Monthly revenue</strong></td><td><strong style="color: var(--bfk-primary);">₹{{ number_format($visit->booking->total_rupees, 0) }}</strong></td></tr>
                    @if($visit->booking->notes)
                    <tr><td><strong>Customer notes</strong></td><td>{{ $visit->booking->notes }}</td></tr>
                    @endif
                    <tr><td><strong>Team assigned</strong></td>
                        <td>
                            @if($visit->teamMember)
                                <span class="pill pill-purple">{{ $visit->teamMember->name }}</span>
                                <form method="POST" action="{{ route('partner.visit.unassignTeam', $visit) }}" style="display:inline; margin-left: 8px;">
                                    @csrf @method('DELETE')
                                    <button class="ic-btn red" title="Unassign"><x-icon name="close" :size="14" /></button>
                                </form>
                            @else
                                <span class="muted">— Self</span>
                            @endif
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        {{-- Status flow + attendance --}}
        <div class="panel">
            <div class="panel-head">
                <h3><x-icon name="pin" :size="14" style="color: var(--bfk-primary);" /> Update status & attendance</h3>
            </div>
            @if($next)
                <p class="muted" style="font-size: 13px; margin-bottom: 14px;">Next step: <strong>{{ str_replace('_', ' ', $next) }}</strong></p>
                <form method="POST" action="{{ route('partner.visit.status', $visit) }}">
                    @csrf
                    <input type="hidden" name="status" value="{{ $next }}">
                    <button class="btn btn-primary"><x-icon name="check" :size="14" /> Mark as {{ str_replace('_', ' ', $next) }}</button>
                </form>
            @elseif($visit->status === 'scheduled')
                <form method="POST" action="{{ route('partner.visit.accept', $visit) }}" style="display:inline">
                    @csrf
                    <button class="btn btn-primary"><x-icon name="check" :size="14" /> Accept visit</button>
                </form>
                <form method="POST" action="{{ route('partner.visit.reject', $visit) }}" style="display:inline; margin-left: 8px;" onsubmit="return confirm('Decline this visit?');">
                    @csrf
                    <button class="btn btn-outline" style="border-color: var(--bfk-red); color: var(--bfk-red);">Decline</button>
                </form>
            @elseif($visit->status === 'completed')
                <div class="alert alert-success">Visit completed on {{ $visit->completed_at?->format('d M Y, h:i A') ?? '—' }}.</div>
            @endif

            <div class="form-section mt-3">
                <div class="ic"><x-icon name="check" :size="14" /></div>
                <h4>Mark attendance + upload proof</h4>
                <span class="sub">Multi-photo, with notes</span>
            </div>
            <form method="POST" action="{{ route('partner.visit.attendance', $visit) }}" enctype="multipart/form-data">
                @csrf
                <div class="form-grid">
                    <div class="field">
                        <label>Status</label>
                        <select name="attendance_status" required>
                            <option value="present" {{ $visit->attendance_status === 'present' ? 'selected' : '' }}>✅ Present (on time)</option>
                            <option value="late" {{ $visit->attendance_status === 'late' ? 'selected' : '' }}>🕐 Late</option>
                            <option value="absent" {{ $visit->attendance_status === 'absent' ? 'selected' : '' }}>❌ Absent</option>
                            <option value="cancelled" {{ $visit->attendance_status === 'cancelled' ? 'selected' : '' }}>🚫 Cancelled</option>
                        </select>
                    </div>
                    <div class="field">
                        <label>Arrival</label>
                        <input type="time" name="arrival_time" value="{{ old('arrival_time', $visit->arrival_time) }}">
                    </div>
                    <div class="field">
                        <label>Departure</label>
                        <input type="time" name="departure_time" value="{{ old('departure_time', $visit->departure_time) }}">
                    </div>
                </div>
                <div class="field">
                    <label>Notes</label>
                    <textarea name="attendance_note" rows="2" placeholder="Any observations…">{{ old('attendance_note', $visit->attendance_note) }}</textarea>
                </div>
                <div class="field">
                    <label>Photos (max 6)</label>
                    <input type="file" name="photos[]" accept="image/*" multiple>
                    <span class="hint">JPG/PNG/WebP. Customer sees photos in real-time.</span>
                </div>
                <button class="btn btn-primary"><x-icon name="check" :size="14" /> Save attendance + photos</button>
            </form>
        </div>

        {{-- Photo proof --}}
        <div class="panel">
            <div class="panel-head">
                <h3><x-icon name="camera" :size="14" style="color: var(--bfk-primary);" /> Photos ({{ $photos->count() }})</h3>
                <span class="muted" style="font-size: 12px;">{{ $visit->photos_count ?? 0 }} of expected {{ $visit->photos_required ? '3-6' : '0' }}</span>
            </div>
            @if($photos->count())
                <div style="display:grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 10px;">
                    @foreach($photos as $p)
                        <a href="{{ asset('storage/' . $p->photo_path) }}" target="_blank" style="display: block;">
                            <img src="{{ asset('storage/' . $p->photo_path) }}" style="width: 100%; height: 120px; object-fit: cover; border-radius: 10px; border: 1px solid var(--bfk-border);" alt="">
                            <div style="font-size: 11px; margin-top: 4px; color: var(--bfk-text-3);">{{ ucfirst($p->stage) }} · {{ $p->created_at->diffForHumans() }}</div>
                        </a>
                    @endforeach
                </div>
            @else
                <div class="empty">
                    <div style="font-size: 32px;">📷</div>
                    <p>No photos uploaded for this visit yet.</p>
                </div>
            @endif
        </div>
    </div>

    <div>
        {{-- Assign team --}}
        <div class="panel">
            <div class="panel-head">
                <h3><x-icon name="profile" :size="14" style="color: var(--bfk-primary);" /> Assign team member</h3>
            </div>
            @if($teamMembers->count())
                @if($visit->teamMember)
                    <div class="alert alert-info" style="display: flex; gap: 10px; align-items: center;">
                        <span class="ic" style="background: currentColor; color: #fff; width: 22px; height: 22px; border-radius: 50%; display: grid; place-items: center; font-weight: 800;">i</span>
                        Currently assigned to <strong>{{ $visit->teamMember->name }}</strong>. Customer sees only your name & photo.
                    </div>
                @endif
                <form method="POST" action="{{ route('partner.visit.assignTeam', $visit) }}">
                    @csrf
                    <div class="field">
                        <label>Pick a team member</label>
                        <select name="team_member_id">
                            <option value="">— Unassign (do it yourself) —</option>
                            @foreach($teamMembers as $m)
                                <option value="{{ $m->id }}" {{ $visit->team_member_id === $m->id ? 'selected' : '' }}>{{ $m->name }} · {{ $m->role }} · {{ $m->phone }}</option>
                            @endforeach
                        </select>
                        <span class="hint">Customers only see your name & photo — never the helper's.</span>
                    </div>
                    <button class="btn btn-primary"><x-icon name="check" :size="14" /> Assign</button>
                </form>
            @else
                <div class="empty">
                    <p>No active team members. <a href="{{ route('partner.team') }}">Add team members →</a></p>
                </div>
            @endif
        </div>

        {{-- Visit status timeline --}}
        <div class="panel">
            <div class="panel-head">
                <h3><x-icon name="calendar" :size="14" style="color: var(--bfk-primary);" /> Visit timeline</h3>
            </div>
            <div style="display: flex; flex-direction: column; gap: 12px;">
                @php $flowList = ['scheduled' => 'Scheduled', 'accepted' => 'Accepted', 'on_the_way' => 'On the way', 'arrived' => 'Arrived', 'in_progress' => 'In progress', 'completed' => 'Completed']; @endphp
                @foreach($flowList as $key => $label)
                    @php $reached = array_search($key, array_keys($flowList)) <= array_search($visit->status, array_keys($flowList)); @endphp
                    <div style="display:flex; align-items:center; gap: 10px;">
                        <div style="width: 28px; height: 28px; border-radius: 50%; display: grid; place-items: center; font-size: 12px; font-weight: 800; {{ $visit->status === $key ? 'background: var(--bfk-primary); color: #fff;' : ($reached ? 'background: var(--bfk-green); color: #fff;' : 'background: var(--bfk-bg-soft); color: var(--bfk-text-3);') }}">
                            @if($reached)✓@else ○@endif
                        </div>
                        <span style="font-size: 13.5px; {{ $reached ? 'color: #111; font-weight: 600;' : 'color: var(--bfk-text-3);' }}">{{ $label }}</span>
                    </div>
                @endforeach
            </div>
        </div>

        {{-- Subscription info --}}
        <div class="panel">
            <div class="panel-head"><h3><x-icon name="bookings" :size="14" style="color: var(--bfk-primary);" /> Subscription</h3></div>
            <table class="table">
                <tbody>
                    <tr><td><strong>Code</strong></td><td><code style="background: var(--bfk-bg-soft); padding: 2px 6px; border-radius: 4px; font-size: 11.5px;">{{ $visit->booking->booking_code }}</code></td></tr>
                    <tr><td><strong>Status</strong></td><td><span class="pill pill-{{ $visit->booking->subscription_status === 'active' ? 'green' : 'orange' }}">{{ ucfirst($visit->booking->subscription_status ?? 'active') }}</span></td></tr>
                    <tr><td><strong>Visits done</strong></td><td>{{ $visit->booking->visits_used }} / {{ $visit->booking->visits_per_period }}</td></tr>
                    <tr><td><strong>Auto-renew</strong></td><td>{{ $visit->booking->auto_renew ? 'Yes' : 'No' }}</td></tr>
                </tbody>
            </table>
        </div>

        {{-- Commission for this visit --}}
        <div class="panel" style="background: linear-gradient(135deg, #fff7f3, #fff3e6); border-left: 4px solid var(--bfk-primary);">
            <div class="panel-head" style="border-color: rgba(255,74,28,0.18);">
                <h3><x-icon name="money" :size="14" style="color: var(--bfk-primary);" /> Your commission</h3>
                <span class="meta" style="font-size: 11px;">@ {{ number_format($commissionPercent, 1) }}%</span>
            </div>
            <div style="display: flex; flex-direction: column; gap: 10px;">
                <div style="display: flex; justify-content: space-between; align-items: center; padding: 8px 10px; background: #fff; border-radius: 8px;">
                    <span style="font-size: 13px; color: var(--bfk-text-2);">Visit share of monthly</span>
                    <strong style="font-size: 14px;">₹{{ number_format($commission['gross_paise']/100, 0) }}</strong>
                </div>
                <div style="display: flex; justify-content: space-between; align-items: center; padding: 8px 10px; background: #fff; border-radius: 8px;">
                    <span style="font-size: 13px; color: var(--bfk-text-2);">Platform cut</span>
                    <strong style="color: var(--bfk-primary);">−₹{{ number_format($commission['platform_paise']/100, 0) }}</strong>
                </div>
                @if($commission['tds_paise'] > 0)
                <div style="display: flex; justify-content: space-between; align-items: center; padding: 8px 10px; background: #fff; border-radius: 8px;">
                    <span style="font-size: 13px; color: var(--bfk-text-2);">TDS</span>
                    <strong style="color: var(--bfk-red);">−₹{{ number_format($commission['tds_paise']/100, 0) }}</strong>
                </div>
                @endif
                <div style="display: flex; justify-content: space-between; align-items: center; padding: 10px 12px; background: linear-gradient(135deg, var(--bfk-green), #22c55e); color: #fff; border-radius: 8px; margin-top: 4px;">
                    <span style="font-size: 13px; font-weight: 600;">You earn when completed</span>
                    <strong style="font-size: 18px;">₹{{ number_format($commission['partner_net_paise']/100, 0) }}</strong>
                </div>
            </div>
            <p class="muted" style="font-size: 11.5px; margin-top: 10px; margin-bottom: 0;">Visit must be marked <strong>completed</strong> with attendance to credit your wallet.</p>
        </div>
    </div>
</div>

@endsection