<?php

namespace App\Http\Controllers\Api\V1;

use App\Domain\Attendance\Models\AttendanceRecord;
use App\Domain\Participant\Models\Participant;
use App\Domain\Training\Models\TrainingSession;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AbsenceController extends Controller
{
    public function report(Request $request): JsonResponse
    {
        $request->validate([
            'participant_uuid' => 'required|string',
            'session_id' => 'required|integer',
            'reason' => 'required|string|max:500',
        ]);

        $user = $request->user();
        $participant = Participant::where('uuid', $request->participant_uuid)->first();

        if (!$participant) {
            return response()->json([
                'error' => 'participant_not_found',
                'message' => 'المشترك غير موجود',
            ], 404);
        }

        // Verify user is authorized for this participant
        if (!$this->isAuthorized($user, $participant)) {
            return response()->json([
                'error' => 'unauthorized',
                'message' => 'غير مصرح لك بتقديم اعتذار لهذا المشترك',
            ], 403);
        }

        $session = TrainingSession::where('id', $request->session_id)
            ->where('session_date', '>=', now()->toDateString())
            ->whereIn('status', ['scheduled'])
            ->first();

        if (!$session) {
            return response()->json([
                'error' => 'session_not_found',
                'message' => 'الجلسة غير موجودة أو قد انتهت',
            ], 404);
        }

        // Check if attendance record already exists
        $existing = AttendanceRecord::where('training_session_id', $session->id)
            ->where('subject_type', 'App\\Domain\\Participant\\Models\\Participant')
            ->where('subject_id', $participant->id)
            ->first();

        if ($existing && in_array($existing->status->value ?? $existing->status, ['present', 'late', 'absent'])) {
            return response()->json([
                'error' => 'already_marked',
                'message' => 'تم تسجيل الحضور بالفعل لهذه الجلسة',
            ], 422);
        }

        if ($existing) {
            $existing->update([
                'status' => 'excused',
                'notes' => $request->reason,
                'metadata' => array_merge($existing->metadata ?? [], [
                    'excused_by' => 'guardian_app',
                    'excused_at' => now()->toIso8601String(),
                    'user_id' => $user->id,
                ]),
            ]);
        } else {
            AttendanceRecord::create([
                'academy_id' => $participant->academy_id,
                'training_session_id' => $session->id,
                'subject_type' => 'App\\Domain\\Participant\\Models\\Participant',
                'subject_id' => $participant->id,
                'date' => $session->session_date,
                'expected_start' => $session->start_time,
                'expected_end' => $session->end_time,
                'status' => 'excused',
                'notes' => $request->reason,
                'metadata' => [
                    'excused_by' => 'guardian_app',
                    'excused_at' => now()->toIso8601String(),
                    'user_id' => $user->id,
                ],
            ]);
        }

        return response()->json([
            'success' => true,
            'message' => 'تم تسجيل الاعتذار بنجاح',
        ]);
    }

    private function isAuthorized($user, Participant $participant): bool
    {
        $personId = $user->person_id;
        if (!$personId) {
            return false;
        }

        // Direct: user IS the participant
        if ($participant->person_id === $personId) {
            return true;
        }

        // Guardian: user's person is a guardian of this participant
        $guardian = \App\Domain\Identity\Models\Guardian::where('person_id', $personId)->first();
        if ($guardian) {
            return $guardian->participants()->where('participants.id', $participant->id)->exists();
        }

        return false;
    }
}
