<?php

namespace App\Http\Controllers\Api\V1;

use App\Domain\Identity\Models\Person;
use App\Domain\Identity\Services\PersonService;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ProfileController extends Controller
{
    public function show(Request $request): JsonResponse
    {
        $user = $request->user();
        $person = $user->person_id ? Person::find($user->person_id) : null;

        return response()->json([
            'data' => [
                'user' => [
                    'id' => $user->id,
                    'name' => $user->name,
                    'name_ar' => $user->name_ar,
                    'email' => $user->email,
                    'phone' => $user->phone,
                ],
                'person' => $person ? [
                    'name' => $person->name,
                    'name_ar' => $person->name_ar,
                    'email' => $person->email,
                    'phone' => $person->phone,
                    'phone_secondary' => $person->phone_secondary,
                    'date_of_birth' => $person->date_of_birth?->toDateString(),
                    'gender' => $person->gender,
                    'nationality' => $person->nationality,
                    'address' => $person->address,
                    'city' => $person->city,
                    'governorate' => $person->governorate,
                    'blood_type' => $person->blood_type,
                    'medical_notes' => $person->medical_notes,
                    'photo_url' => $person->photo_path ? asset('storage/' . $person->photo_path) : null,
                    'emergency_contact' => [
                        'name' => $person->emergency_contact_name,
                        'phone' => $person->emergency_contact_phone,
                        'relation' => $person->emergency_contact_relation,
                    ],
                ] : null,
            ],
        ]);
    }

    public function update(Request $request, PersonService $personService): JsonResponse
    {
        $request->validate([
            'phone_secondary' => 'nullable|string|max:20',
            'address' => 'nullable|string|max:255',
            'city' => 'nullable|string|max:100',
            'emergency_contact_name' => 'nullable|string|max:100',
            'emergency_contact_phone' => 'nullable|string|max:20',
            'emergency_contact_relation' => 'nullable|string|max:50',
            'medical_notes' => 'nullable|string|max:500',
        ]);

        $user = $request->user();

        if (!$user->person_id) {
            return response()->json([
                'error' => 'no_profile',
                'message' => 'لا يوجد ملف شخصي مرتبط بحسابك',
            ], 404);
        }

        $person = Person::findOrFail($user->person_id);

        $allowedFields = [
            'phone_secondary', 'address', 'city',
            'emergency_contact_name', 'emergency_contact_phone', 'emergency_contact_relation',
            'medical_notes',
        ];

        $data = $request->only($allowedFields);
        $data = array_filter($data, fn ($v) => $v !== null);

        if (empty($data)) {
            return response()->json([
                'error' => 'no_changes',
                'message' => 'لا توجد بيانات لتحديثها',
            ], 422);
        }

        $personService->update($person, $data, $user);

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

    public function uploadPhoto(Request $request): JsonResponse
    {
        $request->validate([
            'photo' => 'required|image|mimes:jpeg,jpg,png|max:5120',
            'target' => 'nullable|in:profile,participant',
            'participant_uuid' => 'nullable|string',
        ]);

        $user = $request->user();
        $file = $request->file('photo');
        $target = $request->input('target', 'profile');

        if ($target === 'participant' && $request->participant_uuid) {
            return $this->uploadParticipantPhoto($user, $request->participant_uuid, $file);
        }

        if (!$user->person_id) {
            return response()->json([
                'error' => 'no_profile',
                'message' => 'لا يوجد ملف شخصي مرتبط بحسابك',
            ], 404);
        }

        $person = Person::findOrFail($user->person_id);

        if ($person->photo_path) {
            Storage::disk('public')->delete($person->photo_path);
        }

        $path = $file->store('photos/profiles', 'public');
        $person->update(['photo_path' => $path]);

        return response()->json([
            'success' => true,
            'message' => 'تم رفع الصورة بنجاح',
            'data' => [
                'photo_url' => asset('storage/' . $path),
            ],
        ]);
    }

    private function uploadParticipantPhoto($user, string $participantUuid, $file): JsonResponse
    {
        $participant = \App\Domain\Participant\Models\Participant::where('uuid', $participantUuid)->first();

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

        $personId = $user->person_id;
        if (!$personId) {
            abort(403);
        }

        $authorized = false;
        if ($participant->person_id === $personId) {
            $authorized = true;
        } else {
            $guardian = \App\Domain\Identity\Models\Guardian::where('person_id', $personId)->first();
            if ($guardian && $guardian->participants()->where('participants.id', $participant->id)->exists()) {
                $authorized = true;
            }
        }

        if (!$authorized) {
            return response()->json(['error' => 'unauthorized', 'message' => 'غير مصرح'], 403);
        }

        if ($participant->photo_path) {
            Storage::disk('public')->delete($participant->photo_path);
        }

        $path = $file->store('photos/participants', 'public');
        $participant->update(['photo_path' => $path]);

        return response()->json([
            'success' => true,
            'message' => 'تم رفع صورة المشترك بنجاح',
            'data' => [
                'photo_url' => asset('storage/' . $path),
            ],
        ]);
    }
}
