<?php

declare(strict_types=1);

namespace App\Models;

use Core\Database;

final class Dependent
{
    public static function replaceForAdmission(int $admissionId, array $dependents): void
    {
        $db = Database::connection();
        $db->prepare('DELETE FROM dependents WHERE admission_id = :id')->execute(['id' => $admissionId]);
        if (empty($dependents)) return;
        $sql = 'INSERT INTO dependents (admission_id, full_name, birth_date, cpf, birth_city, has_disability, created_at, updated_at)
                VALUES (:admission_id, :full_name, :birth_date, :cpf, :birth_city, :has_disability, NOW(), NOW())';
        $st = $db->prepare($sql);
        foreach ($dependents as $dep) {
            $st->execute([
                'admission_id' => $admissionId,
                'full_name' => $dep['full_name'],
                'birth_date' => $dep['birth_date'],
                'cpf' => preg_replace('/\D/', '', (string)$dep['cpf']),
                'birth_city' => $dep['birth_city'],
                'has_disability' => (int)($dep['has_disability'] ?? 0),
            ]);
        }
    }

    public static function forAdmission(int $admissionId): array
    {
        $st = Database::connection()->prepare('SELECT * FROM dependents WHERE admission_id = :id ORDER BY id ASC');
        $st->execute(['id' => $admissionId]);
        return $st->fetchAll() ?: [];
    }
}
