<?php

namespace App\Http\Controllers\Api\Reports;

use App\Http\Controllers\Api\Core\BaseApiController;
use App\Http\Requests\Reports\ReportCards\ReportCardCompletenessRequest;
use App\Http\Requests\Reports\ReportCards\ReportCardMetaRequest;
use App\Http\Requests\Reports\ReportCards\ReportCardPdfRequest;
use App\Http\Resources\Reports\ReportCards\ReportCardAcknowledgementResource;
use App\Http\Resources\Reports\ReportCards\ReportCardClassSectionResource;
use App\Http\Resources\Reports\ReportCards\ReportCardCompletenessStudentResource;
use App\Http\Resources\Reports\ReportCards\ReportCardStudentMetaResource;
use App\Models\Configuration;
use App\Services\Reports\ReportCards\ReportCardService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Symfony\Component\HttpFoundation\Response;

class ReportCardsController extends BaseApiController
{
    public function __construct(private ReportCardService $service)
    {
        parent::__construct();
    }

    public function meta(ReportCardMetaRequest $request): JsonResponse
    {
        $payload = $request->validated();

        $result = $this->service->meta(
            $payload['school_year'] ?? null,
            $payload['semester'] ?? null
        );

        return $this->success([
            'schoolYears' => $result['schoolYears'] ?? [],
            'selectedYear' => $result['selectedYear'] ?? null,
            'semesters' => $result['semesters'] ?? [],
            'selectedSemester' => $result['selectedSemester'] ?? null,
            'students' => ReportCardStudentMetaResource::collection($result['students'] ?? []),
            'classSections' => ReportCardClassSectionResource::collection($result['classSections'] ?? []),
        ]);
    }

    public function completeness(ReportCardCompletenessRequest $request): JsonResponse
    {
        $payload = $request->validated();
        $schoolYear = $this->resolveSchoolYear($payload['school_year'] ?? null);
        $semester = $this->resolveSemester($payload['semester'] ?? null);
        $classSectionId = (int) ($payload['class_section_id'] ?? 0);

        $result = $this->service->completeness($schoolYear, $semester, $classSectionId);
        if (!($result['ok'] ?? false)) {
            return $this->error($result['message'] ?? 'Unable to generate completeness report.', Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        return $this->success([
            'summary' => $result['summary'] ?? null,
            'students' => ReportCardCompletenessStudentResource::collection($result['students'] ?? []),
            'class_section_name' => $result['class_section_name'] ?? null,
            'class_section_id' => $result['class_section_id'] ?? null,
            'school_year' => $result['school_year'] ?? $schoolYear,
            'semester' => $result['semester'] ?? $semester,
            'roster_semester' => $result['roster_semester'] ?? null,
            'used_fallback' => (bool) ($result['used_fallback'] ?? false),
        ], $result['message'] ?? 'Success');
    }

    public function acknowledgement(Request $request): JsonResponse
    {
        $payload = [
            'student_id' => $request->query('student_id', $request->query('studentId')),
            'school_year' => $request->query('school_year', $request->query('schoolYear')),
            'semester' => $request->query('semester'),
        ];

        $validator = Validator::make($payload, [
            'student_id' => ['required', 'integer', 'min:1'],
            'school_year' => ['nullable', 'string', 'max:20'],
            'semester' => ['nullable', 'string', 'max:20'],
        ]);

        if ($validator->fails()) {
            return $this->error('Validation failed.', Response::HTTP_UNPROCESSABLE_ENTITY, $validator->errors()->toArray());
        }

        $validated = $validator->validated();
        $studentId = (int) ($validated['student_id'] ?? 0);
        $schoolYear = $this->resolveSchoolYear($validated['school_year'] ?? null);
        $semester = $this->resolveSemester($validated['semester'] ?? null);

        $result = $this->service->acknowledgement($studentId, $schoolYear, $semester);

        return $this->success(new ReportCardAcknowledgementResource($result));
    }

    public function studentReport(ReportCardPdfRequest $request, int $studentId)
    {
        try {
            $result = $this->service->generateSingleReport($studentId, $request->validated());
        } catch (\Throwable $e) {
            Log::error('Report card PDF generation failed: ' . $e->getMessage());
            return $this->error('Failed to generate report card.', Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        if (!($result['ok'] ?? false)) {
            return $this->error($result['message'] ?? 'Unable to generate report card.', Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        $disposition = ($request->boolean('download') ? 'attachment' : 'inline');

        return response($result['pdf'], 200, [
            'Content-Type' => 'application/pdf',
            'Content-Disposition' => $disposition . '; filename="' . ($result['filename'] ?? 'ReportCard.pdf') . '"',
            'Cache-Control' => 'private, max-age=0, must-revalidate',
            'Pragma' => 'public',
        ]);
    }

    public function classReport(ReportCardPdfRequest $request, int $classSectionId)
    {
        try {
            $result = $this->service->generateClassReport($classSectionId, $request->validated());
        } catch (\Throwable $e) {
            Log::error('Class report card PDF generation failed: ' . $e->getMessage());
            return $this->error('Failed to generate class report cards.', Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        if (!($result['ok'] ?? false)) {
            return $this->error($result['message'] ?? 'Unable to generate class report cards.', Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        $disposition = ($request->boolean('download') ? 'attachment' : 'inline');

        return response($result['pdf'], 200, [
            'Content-Type' => 'application/pdf',
            'Content-Disposition' => $disposition . '; filename="' . ($result['filename'] ?? 'ClassReportCards.pdf') . '"',
            'Cache-Control' => 'private, max-age=0, must-revalidate',
            'Pragma' => 'public',
        ]);
    }

    private function resolveSchoolYear(?string $schoolYear): string
    {
        $value = trim((string) ($schoolYear ?? ''));
        if ($value !== '') {
            return $value;
        }
        return trim((string) (Configuration::getConfig('school_year') ?? ''));
    }

    private function resolveSemester(?string $semester): string
    {
        $value = trim((string) ($semester ?? ''));
        if ($value !== '') {
            return $value;
        }
        return trim((string) (Configuration::getConfig('semester') ?? ''));
    }
}
