<?php

namespace App\Services;

use App\Models\Student;
use App\Models\Enrollment;
use App\Models\Cycle;
use Illuminate\Support\Facades\DB;

class EnrollmentService
{
    public function registerStudentWithEnrollment(array $data, Cycle $cycle): array
    {
        try {
            DB::beginTransaction();

            $student = Student::where('document_number', $data['document_number'])->first();

            if ($student) {
                // Verificar si ya está matriculado en este ciclo
                $existingEnrollment = Enrollment::where('student_id', $student->id)
                    ->where('cycle_id', $cycle->id)
                    ->exists();

                if ($existingEnrollment) {
                    DB::rollBack();
                    return [
                        'success' => false,
                        'message' => 'El estudiante ya está matriculado en este ciclo',
                    ];
                }

                // Actualizar datos de contacto si proporciona nuevos
                $student->update([
                    'phone_number' => $data['phone_number'] ?? $student->phone_number,
                    'whatsapp_number' => $data['whatsapp_number'] ?? $student->whatsapp_number,
                    'email' => $data['email'] ?? $student->email,
                ]);
            } else {
                // Crear nuevo estudiante
                $student = Student::create([
                    'document_type' => $data['document_type'],
                    'document_number' => $data['document_number'],
                    'names' => $data['names'],
                    'paternal_surname' => $data['paternal_surname'],
                    'maternal_surname' => $data['maternal_surname'],
                    'birth_date' => $data['birth_date'],
                    'gender' => $data['gender'],
                    'phone_number' => $data['phone_number'] ?? null,
                    'whatsapp_number' => $data['whatsapp_number'],
                    'email' => $data['email'],
                    'password' => $data['password'],
                    'active' => true,
                    'validated' => false,
                ]);
            }

            // Generar token
            $student->generateAccessToken(2);
            $student->updateLastLogin();
            $student->refresh();

            // Crear matrícula
            $enrollment = $student->enrollments()->create([
                'cycle_id' => $cycle->id,
                // 'active' => true,
                'status' => 'pending',
                'registration_steps' => ['personal_data'],
            ]);

            DB::commit();

            return [
                'success' => true,
                'message' => 'Información registrada exitosamente',
                'student' => $student,
                'enrollment' => $enrollment,
                'cycle' => $cycle,
            ];
        } catch (\Exception $e) {
            DB::rollBack();

            return [
                'success' => false,
                'message' => 'Error al registrar la información',
                'error' => $e->getMessage(),
            ];
        }
    }
}
