<?php

namespace App\Http\Controllers\Api\Parents;

use App\Http\Controllers\Api\BaseApiController;
use App\Http\Requests\Parents\ParentAttendanceRequest;
use App\Http\Requests\Parents\ParentEnrollmentActionRequest;
use App\Http\Requests\Parents\ParentEnrollmentRequest;
use App\Http\Requests\Parents\ParentEmergencyContactRequest;
use App\Http\Requests\Parents\ParentEventParticipationRequest;
use App\Http\Requests\Parents\ParentInvoiceRequest;
use App\Http\Requests\Parents\ParentProfileUpdateRequest;
use App\Http\Requests\Parents\ParentRegistrationRequest;
use App\Http\Requests\Parents\ParentStudentUpdateRequest;
use App\Http\Resources\Parents\ParentAttendanceResource;
use App\Http\Resources\Parents\ParentEmergencyContactResource;
use App\Http\Resources\Parents\ParentStudentResource;
use App\Http\Resources\Invoices\InvoiceResource;
use App\Services\Parents\ParentAttendanceService;
use App\Services\Parents\ParentEmergencyContactService;
use App\Services\Parents\ParentEnrollmentService;
use App\Services\Parents\ParentEventParticipationService;
use App\Services\Parents\ParentInvoiceService;
use App\Services\Parents\ParentProfileService;
use App\Services\Parents\ParentRegistrationService;
use Illuminate\Http\JsonResponse;

class ParentController extends BaseApiController
{
    public function __construct(
        private ParentAttendanceService $attendanceService,
        private ParentInvoiceService $invoiceService,
        private ParentEnrollmentService $enrollmentService,
        private ParentRegistrationService $registrationService,
        private ParentEmergencyContactService $emergencyContactService,
        private ParentProfileService $profileService,
        private ParentEventParticipationService $eventService
    ) {
        parent::__construct();
    }

    public function attendance(ParentAttendanceRequest $request): JsonResponse
    {
        $parentId = (int) (auth()->id() ?? 0);
        if ($parentId <= 0) {
            return response()->json(['ok' => false, 'message' => 'Unauthorized.'], 401);
        }

        $data = $this->attendanceService->listAttendance($parentId, $request->validated()['school_year'] ?? null);

        return response()->json([
            'ok' => true,
            'attendance' => ParentAttendanceResource::collection($data['attendance']),
            'schoolYears' => $data['schoolYears'],
            'selectedYear' => $data['selectedYear'],
        ]);
    }

    public function invoices(ParentInvoiceRequest $request): JsonResponse
    {
        $parentId = (int) (auth()->id() ?? 0);
        if ($parentId <= 0) {
            return response()->json(['ok' => false, 'message' => 'Unauthorized.'], 401);
        }

        $schoolYear = $request->validated()['school_year'] ?? null;
        $rows = $this->invoiceService->listInvoices($parentId, $schoolYear);

        return response()->json([
            'ok' => true,
            'invoices' => InvoiceResource::collection($rows),
        ]);
    }

    public function enrollments(ParentEnrollmentRequest $request): JsonResponse
    {
        $parentId = (int) (auth()->id() ?? 0);
        if ($parentId <= 0) {
            return response()->json(['ok' => false, 'message' => 'Unauthorized.'], 401);
        }

        $data = $this->enrollmentService->overview($parentId, $request->validated()['school_year'] ?? null);

        return response()->json([
            'ok' => true,
            'students' => ParentStudentResource::collection($data['students']),
            'schoolYears' => $data['schoolYears'],
            'selectedYear' => $data['selectedYear'],
            'withdrawalDeadline' => $data['withdrawalDeadline'],
            'lastDayOfRegistration' => $data['lastDayOfRegistration'],
            'schoolStartDate' => $data['schoolStartDate'],
        ]);
    }

    public function updateEnrollments(ParentEnrollmentActionRequest $request): JsonResponse
    {
        $parentId = (int) (auth()->id() ?? 0);
        if ($parentId <= 0) {
            return response()->json(['ok' => false, 'message' => 'Unauthorized.'], 401);
        }

        $payload = $request->validated();
        $result = $this->enrollmentService->updateEnrollment(
            $parentId,
            $payload['enroll'] ?? [],
            $payload['withdraw'] ?? []
        );

        return response()->json([
            'ok' => true,
            'enrolled' => $result['enrolled'],
            'withdrawn' => $result['withdrawn'],
        ]);
    }

    public function registration(): JsonResponse
    {
        $parentId = (int) (auth()->id() ?? 0);
        if ($parentId <= 0) {
            return response()->json(['ok' => false, 'message' => 'Unauthorized.'], 401);
        }

        $data = $this->registrationService->overview($parentId);

        return response()->json([
            'ok' => true,
            'parent' => $data['parent'],
            'existingKids' => ParentStudentResource::collection($data['existingKids']),
            'emergencies' => ParentEmergencyContactResource::collection($data['emergencies']),
            'maxChilds' => $data['maxChilds'],
            'maxEmergency' => $data['maxEmergency'],
            'lastDayOfRegistration' => $data['lastDayOfRegistration'],
            'registrationAgeDeadline' => $data['registrationAgeDeadline'],
        ]);
    }

    public function storeRegistration(ParentRegistrationRequest $request): JsonResponse
    {
        $parentId = (int) (auth()->id() ?? 0);
        if ($parentId <= 0) {
            return response()->json(['ok' => false, 'message' => 'Unauthorized.'], 401);
        }

        $payload = $request->validated();
        $result = $this->registrationService->register(
            $parentId,
            $payload['students'] ?? [],
            $payload['emergency_contacts'] ?? []
        );

        return response()->json([
            'ok' => true,
            'created_student_ids' => $result['created_student_ids'],
        ], 201);
    }

    public function updateStudent(ParentStudentUpdateRequest $request, int $studentId): JsonResponse
    {
        $parentId = (int) (auth()->id() ?? 0);
        if ($parentId <= 0) {
            return response()->json(['ok' => false, 'message' => 'Unauthorized.'], 401);
        }

        $this->registrationService->updateStudent($parentId, $studentId, $request->validated());

        return response()->json(['ok' => true]);
    }

    public function deleteStudent(int $studentId): JsonResponse
    {
        $parentId = (int) (auth()->id() ?? 0);
        if ($parentId <= 0) {
            return response()->json(['ok' => false, 'message' => 'Unauthorized.'], 401);
        }

        $this->registrationService->deleteStudent($parentId, $studentId);

        return response()->json(['ok' => true]);
    }

    public function emergencyContacts(): JsonResponse
    {
        $parentId = (int) (auth()->id() ?? 0);
        if ($parentId <= 0) {
            return response()->json(['ok' => false, 'message' => 'Unauthorized.'], 401);
        }

        $rows = $this->emergencyContactService->list($parentId);

        return response()->json([
            'ok' => true,
            'contacts' => ParentEmergencyContactResource::collection($rows),
        ]);
    }

    public function storeEmergencyContact(ParentEmergencyContactRequest $request): JsonResponse
    {
        $parentId = (int) (auth()->id() ?? 0);
        if ($parentId <= 0) {
            return response()->json(['ok' => false, 'message' => 'Unauthorized.'], 401);
        }

        $contact = $this->emergencyContactService->store($parentId, $request->validated());

        return response()->json([
            'ok' => true,
            'contact' => new ParentEmergencyContactResource($contact),
        ], 201);
    }

    public function updateEmergencyContact(ParentEmergencyContactRequest $request, int $contactId): JsonResponse
    {
        $parentId = (int) (auth()->id() ?? 0);
        if ($parentId <= 0) {
            return response()->json(['ok' => false, 'message' => 'Unauthorized.'], 401);
        }

        $contact = $this->emergencyContactService->update($parentId, $contactId, $request->validated());

        return response()->json([
            'ok' => true,
            'contact' => new ParentEmergencyContactResource($contact),
        ]);
    }

    public function profile(): JsonResponse
    {
        $parentId = (int) (auth()->id() ?? 0);
        if ($parentId <= 0) {
            return response()->json(['ok' => false, 'message' => 'Unauthorized.'], 401);
        }

        $profile = $this->profileService->getProfile($parentId);

        return response()->json([
            'ok' => true,
            'profile' => $profile,
        ]);
    }

    public function updateProfile(ParentProfileUpdateRequest $request): JsonResponse
    {
        $parentId = (int) (auth()->id() ?? 0);
        if ($parentId <= 0) {
            return response()->json(['ok' => false, 'message' => 'Unauthorized.'], 401);
        }

        $profile = $this->profileService->updateProfile($parentId, $request->validated());

        return response()->json([
            'ok' => true,
            'profile' => $profile,
        ]);
    }

    public function events(): JsonResponse
    {
        $parentId = (int) (auth()->id() ?? 0);
        if ($parentId <= 0) {
            return response()->json(['ok' => false, 'message' => 'Unauthorized.'], 401);
        }

        $data = $this->eventService->overview($parentId);

        return response()->json([
            'ok' => true,
            'activeEvents' => $data['activeEvents'],
            'charges' => $data['charges'],
            'yourStudents' => $data['yourStudents'],
        ]);
    }

    public function updateParticipation(ParentEventParticipationRequest $request): JsonResponse
    {
        $parentId = (int) (auth()->id() ?? 0);
        if ($parentId <= 0) {
            return response()->json(['ok' => false, 'message' => 'Unauthorized.'], 401);
        }

        $this->eventService->updateParticipation($parentId, $request->validated()['participation'] ?? []);

        return response()->json(['ok' => true]);
    }
}
