<?php

declare(strict_types=1);

namespace App\Models;

use Core\Database;

final class AcademicInfo
{
    public static function replaceForAdmission(int $admissionId, ?array $academic): void
    {
        Database::connection()->prepare('DELETE FROM academic_infos WHERE admission_id = :id')->execute(['id' => $admissionId]);
        if (!$academic) return;
        $sql = 'INSERT INTO academic_infos (
            admission_id, internship_nature, academic_level, institution_name, institution_cnpj, institution_address,
            institution_neighborhood, institution_number, institution_zip, institution_city, institution_state,
            advisor_name, semester, study_shift, course_name, registration_number, created_at, updated_at
        ) VALUES (
            :admission_id, :internship_nature, :academic_level, :institution_name, :institution_cnpj, :institution_address,
            :institution_neighborhood, :institution_number, :institution_zip, :institution_city, :institution_state,
            :advisor_name, :semester, :study_shift, :course_name, :registration_number, NOW(), NOW()
        )';
        Database::connection()->prepare($sql)->execute([
            'admission_id' => $admissionId,
            'internship_nature' => trim((string) ($academic['internship_nature'] ?? '')),
            'academic_level' => trim((string) ($academic['academic_level'] ?? '')),
            'institution_name' => trim((string) ($academic['institution_name'] ?? '')),
            'institution_cnpj' => preg_replace('/\D/', '', (string) ($academic['institution_cnpj'] ?? '')),
            'institution_address' => trim((string) ($academic['institution_address'] ?? '')),
            'institution_neighborhood' => trim((string) ($academic['institution_neighborhood'] ?? '')),
            'institution_number' => trim((string) ($academic['institution_number'] ?? '')),
            'institution_zip' => preg_replace('/\D/', '', (string) ($academic['institution_zip'] ?? '')),
            'institution_city' => trim((string) ($academic['institution_city'] ?? '')),
            'institution_state' => strtoupper(trim((string) ($academic['institution_state'] ?? ''))),
            'advisor_name' => trim((string) ($academic['advisor_name'] ?? '')),
            'semester' => trim((string) ($academic['semester'] ?? '')),
            'study_shift' => trim((string) ($academic['study_shift'] ?? '')),
            'course_name' => trim((string) ($academic['course_name'] ?? '')),
            'registration_number' => trim((string) ($academic['registration_number'] ?? '')),
        ]);
    }

    public static function forAdmission(int $admissionId): ?array
    {
        $st = Database::connection()->prepare('SELECT * FROM academic_infos WHERE admission_id = :id LIMIT 1');
        $st->execute(['id' => $admissionId]);
        return $st->fetch() ?: null;
    }
}
