<?php

namespace App\Services\Students;

use App\Models\ClassSection;
use App\Models\Student;
use App\Models\StudentClass;

class StudentStatusService
{
    public function __construct(private StudentConfigService $configService)
    {
    }

    public function setActive(int $studentId, bool $isActive, ?int $userId = null): array
    {
        $context = $this->configService->context();
        $semester = (string) ($context['semester'] ?? '');
        $schoolYear = (string) ($context['school_year'] ?? '');

        $student = Student::query()->find($studentId);
        if (!$student) {
            return ['ok' => false, 'message' => 'Student not found.'];
        }

        $student->update([
            'is_active' => $isActive ? 1 : 0,
        ]);

        $message = $isActive ? 'Student restored successfully.' : 'Student removed successfully.';

        if ($isActive) {
            $hasCurrentClass = StudentClass::query()
                ->where('student_id', $studentId)
                ->when($semester !== '', fn ($q) => $q->where('semester', $semester))
                ->when($schoolYear !== '', fn ($q) => $q->where('school_year', $schoolYear))
                ->first();

            if (!$hasCurrentClass) {
                $lastClass = StudentClass::query()
                    ->where('student_id', $studentId)
                    ->orderByDesc('updated_at')
                    ->orderByDesc('created_at')
                    ->orderByDesc('id')
                    ->first();

                $restoreClassId = (int) ($lastClass?->class_section_id ?? 0);
                if ($restoreClassId > 0) {
                    StudentClass::query()->create([
                        'student_id' => $studentId,
                        'class_section_id' => $restoreClassId,
                        'semester' => $semester,
                        'school_year' => $schoolYear,
                        'description' => $lastClass?->description,
                        'updated_by' => $userId,
                        'updated_at' => now(),
                        'created_at' => now(),
                    ]);

                    $classLabel = ClassSection::getClassSectionNameBySectionId($restoreClassId);
                    if ($classLabel) {
                        $message .= ' Class assignment restored to ' . $classLabel . '.';
                    }
                } else {
                    $message .= ' No class assignment found for the current term.';
                }
            }
        }

        return [
            'ok' => true,
            'message' => $message,
            'is_active' => $isActive,
        ];
    }
}
