<?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' => $academic['internship_nature'],
            'academic_level' => $academic['academic_level'],
            'institution_name' => $academic['institution_name'],
            'institution_cnpj' => preg_replace('/\D/', '', (string)$academic['institution_cnpj']),
            'institution_address' => $academic['institution_address'],
            'institution_neighborhood' => $academic['institution_neighborhood'],
            'institution_number' => $academic['institution_number'],
            'institution_zip' => preg_replace('/\D/', '', (string)$academic['institution_zip']),
            'institution_city' => $academic['institution_city'],
            'institution_state' => $academic['institution_state'],
            'advisor_name' => $academic['advisor_name'],
            'semester' => $academic['semester'],
            'study_shift' => $academic['study_shift'],
            'course_name' => $academic['course_name'],
            'registration_number' => $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;
    }
}
