<?php

namespace App\Http\Controllers\TeamMember;

use App\Http\Controllers\Controller;
use App\Models\PartnerTeamMember;
use App\Models\SubscriptionVisit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;

class TeamMemberController extends Controller
{
    private function ensureMember(): PartnerTeamMember
    {
        $member = PartnerTeamMember::where('user_id', Auth::id())->where('is_active', true)->firstOrFail();
        if ($member->last_login_at === null || $member->last_login_at->lt(now()->subDay())) {
            $member->update(['last_login_at' => now()]);
        }
        return $member;
    }

    public function dashboard()
    {
        $member = $this->ensureMember();
        $today = now()->toDateString();
        $stats = [
            'today' => SubscriptionVisit::where('team_member_id', $member->id)
                ->where('scheduled_date', $today)->count(),
            'upcoming' => SubscriptionVisit::where('team_member_id', $member->id)
                ->where('scheduled_date', '>', $today)
                ->whereIn('status', ['accepted', 'on_the_way', 'arrived', 'in_progress'])
                ->count(),
            'completed' => SubscriptionVisit::where('team_member_id', $member->id)
                ->where('attendance_status', 'present')->count(),
        ];
        $todays = SubscriptionVisit::with(['booking.service', 'booking.customer', 'booking.area'])
            ->where('team_member_id', $member->id)
            ->where('scheduled_date', $today)
            ->orderBy('scheduled_slot')
            ->get();
        $partner = $member->partner;
        return view('teammember.dashboard', compact('member', 'stats', 'todays', 'partner'));
    }

    public function visits(Request $request)
    {
        $member = $this->ensureMember();
        $tab = (string) $request->string('tab', 'upcoming');
        $q = SubscriptionVisit::with(['booking.service', 'booking.customer', 'booking.area'])
            ->where('team_member_id', $member->id);
        $q = match ($tab) {
            'today' => $q->where('scheduled_date', now()->toDateString()),
            'completed' => $q->where('attendance_status', 'present'),
            'cancelled' => $q->whereIn('status', ['cancelled', 'skipped']),
            default => $q->where('scheduled_date', '>=', now()->toDateString())->whereIn('status', ['accepted', 'on_the_way', 'arrived', 'in_progress']),
        };
        $visits = $q->orderBy('scheduled_date')->orderBy('scheduled_slot')->paginate(20);
        return view('teammember.visits', compact('visits', 'tab'));
    }

    public function visit(SubscriptionVisit $visit)
    {
        $member = $this->ensureMember();
        abort_unless($visit->team_member_id === $member->id, 403);
        $visit->load(['booking.service', 'booking.customer', 'booking.area', 'booking.photos']);
        return view('teammember.visit', compact('visit', 'member'));
    }

    public function visitMarkAttendance(Request $request, SubscriptionVisit $visit)
    {
        $member = $this->ensureMember();
        abort_unless($visit->team_member_id === $member->id, 403);

        $data = $request->validate([
            'attendance_status' => ['required', Rule::in(['present', 'absent', 'late'])],
            'arrival_time' => ['nullable', 'date_format:H:i'],
            'departure_time' => ['nullable', 'date_format:H:i'],
            'attendance_note' => ['nullable', 'string', 'max:1000'],
            'photos.*' => ['nullable', 'image', 'max:5120'],
        ]);

        $update = [
            'attendance_status' => $data['attendance_status'],
            'attendance_note' => $data['attendance_note'] ?? null,
        ];
        if ($data['attendance_status'] === 'present') {
            $update['marked_present_at'] = now();
            $update['arrival_time'] = $data['arrival_time'] ?? now()->format('H:i:s');
            $update['departure_time'] = $data['departure_time'] ?? now()->format('H:i:s');
            $update['status'] = 'completed';
            $update['completed_at'] = now();
        } elseif ($data['attendance_status'] === 'absent') {
            $update['auto_absent_marked'] = true;
            $update['auto_absent_at'] = now();
        }

        $visit->update($update);

        if ($request->hasFile('photos')) {
            foreach ($request->file('photos') as $photo) {
                $path = $photo->store('visit_photos/' . date('Y/m'), 'public');
                \App\Models\BookingPhoto::create([
                    'booking_id' => $visit->booking_id,
                    'visit_id' => $visit->id,
                    'stage' => 'team_attendance',
                    'photo_path' => $path,
                    'uploaded_by' => Auth::id(),
                ]);
            }
        }

        return back()->with('success', 'Attendance marked as ' . $data['attendance_status']);
    }

    public function profile()
    {
        $member = $this->ensureMember();
        $partner = $member->partner;
        return view('teammember.profile', compact('member', 'partner'));
    }

    public function help()
    {
        $member = $this->ensureMember();
        return view('teammember.help', compact('member'));
    }
}
