<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\IndexQueryRequest;
use App\Http\Requests\StudentRequest;
use App\Http\Resources\StudentResource;
use App\Models\Student;
use App\Services\FileStorageService;
use App\Traits\AppHelpers;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;

class StudentController extends Controller
{
    use AppHelpers;

    private FileStorageService $fileStorageService;

    public function __construct(FileStorageService $fileStorageService)
    {
        $this->fileStorageService = $fileStorageService;
    }

    private array $messages = [
        'index'          => 'Lista de Estudiantes obtenidos exitosamente',
        'store'          => 'Estudiante creado exitosamente',
        'show'           => 'Estudiante obtenido exitosamente',
        'update'         => 'Estudiante actualizado exitosamente',
        'destroy'        => 'Estudiante eliminado exitosamente',
        'not_found'      => 'Estudiante no encontrado',
        'cannot_destroy' => 'No se puede eliminar el Estudiante porque está en uso',
    ];

    public function index(IndexQueryRequest $request): JsonResponse
    {
        $students = Student::query()
            ->included()
            ->search()
            ->filter()
            ->sort()
            ->paginated();

        return StudentResource::collection($students)
            ->additional([
                'success' => true,
                'message' => $this->messages['index']
            ])
            ->response();
    }

    public function store(StudentRequest $request): JsonResponse
    {
        $validated = $request->validated();
        $validated['password'] = $validated['document_number'];

        $item = Student::create($validated);

        return StudentResource::make($item)
            ->additional([
                'success' => true,
                'message' => $this->messages['store']
            ])
            ->response()
            ->setStatusCode(201);
    }

    public function show(int $id): JsonResponse
    {
        $item = Student::query()
            ->included()
            ->findOrAbort($id, $this->messages['not_found']);

        return StudentResource::make($item)
            ->additional([
                'success' => true,
                'message' => $this->messages['show']
            ])
            ->response();
    }

    public function update(StudentRequest $request, int $id): JsonResponse
    {
        $item = Student::findOrAbort($id, $this->messages['not_found']);
        $item->update($request->validated());

        return StudentResource::make($item)
            ->additional([
                'success' => true,
                'message' => $this->messages['update']
            ])
            ->response();
    }

    public function destroy(int $id): JsonResponse
    {
        $item = Student::findOrAbort($id, $this->messages['not_found']);

        try {
            DB::beginTransaction();

            $filesToDelete = [
                $item->document_file,
                $item->photo_student,
                $item->school_graduation_certificate,
                $item->photo_profile,
            ];

            $item->delete();

            DB::commit();

            // Eliminar archivos después del commit
            foreach ($filesToDelete as $file) {
                if ($file) {
                    $this->fileStorageService->delete($file, 'local');
                }
            }

            return StudentResource::make($item)
                ->additional([
                    'success' => true,
                    'message' => $this->messages['destroy']
                ])
                ->response();
        } catch (\Exception $e) {
            DB::rollBack();

            return response()->json([
                'success' => false,
                'message' => $this->messages['cannot_destroy'],
                'error' => $e->getMessage(),
            ], 400);
        }
    }

    public function toggleStatus(int $id): JsonResponse
    {
        $item = Student::findOrAbort($id, $this->messages['not_found']);
        $item->update(['active' => !$item->active]);

        return StudentResource::make($item)
            ->additional([
                'success' => true,
                'message' => 'Estado del Estudiante ' . ($item->active ? 'activado' : 'desactivado') . ' exitosamente',
            ])
            ->response();
    }

    public function toggleValidation(int $id): JsonResponse
    {
        $item = Student::findOrAbort($id, $this->messages['not_found']);
        $item->update(['validated_information' => !$item->validated_information]);

        return StudentResource::make($item)
            ->additional([
                'success' => true,
                'message' => 'Información del Estudiante ' . ($item->validated_information ? 'validada' : 'no validada') . ' exitosamente',
            ])
            ->response();
    }

    public function resetPassword(int $id): JsonResponse
    {
        $item = Student::findOrAbort($id, $this->messages['not_found']);

        $item->invalidateToken();
        $item->update(['password' => $item->document_number]);

        return StudentResource::make($item)
            ->additional([
                'success' => true,
                'message' => 'Contraseña del Estudiante restablecida exitosamente',
            ])
            ->response();
    }

    // Detalle de toda la información de un estudiante  de un estudiante para la ficha
    public function studentDetail(int $id): JsonResponse
    {
        $student = Student::with(['enrollments'])->findOrAbort($id, 'Estudiante no Encontrado');
        $activeEnrollment = $this->getActiveEnrollment($student);

        $activeEnrollment->load([
            'student.school',
            'student.residenceDistrict',
            'student.birthDistrict',
            'cycle',
            'career',
            'payments',
            'discountType'
        ]);

        return response()->json([
            'success' => true,
            'data' => $activeEnrollment
        ]);
    }
}
