<?php

declare(strict_types=1);

namespace App\Models;

use App\Core\Model;
use PDO;

final class MailTemplate extends Model
{
    /** @return array<string,mixed>|null */
    public function findByType(string $type): ?array
    {
        $statement = $this->db->prepare(
            'SELECT * FROM mail_templates WHERE type_document = :type LIMIT 1'
        );
        $statement->execute(['type' => strtoupper(trim($type))]);
        $row = $statement->fetch(PDO::FETCH_ASSOC);

        return is_array($row) ? $row : null;
    }

    /** @return array<int,array<string,mixed>> */
    public function all(): array
    {
        return $this->db
            ->query('SELECT * FROM mail_templates ORDER BY type_document')
            ->fetchAll(PDO::FETCH_ASSOC);
    }

    /** @param array<string,mixed> $data */
    public function save(array $data): void
    {
        $payload = [
            'type_document' => strtoupper(trim((string)$data['type_document'])),
            'nom' => trim((string)$data['nom']),
            'objet' => trim((string)$data['objet']),
            'contenu_html' => trim((string)$data['contenu_html']),
            'contenu_texte' => trim((string)($data['contenu_texte'] ?? '')),
            'actif' => !empty($data['actif']) ? 1 : 0,
        ];

        $existing = $this->findByType($payload['type_document']);

        if ($existing === null) {
            $statement = $this->db->prepare(
                'INSERT INTO mail_templates ('
                . 'type_document, nom, objet, contenu_html, contenu_texte, actif'
                . ') VALUES ('
                . ':type_document, :nom, :objet, :contenu_html, :contenu_texte, :actif'
                . ')'
            );

            $statement->execute($payload);
            return;
        }

        $statement = $this->db->prepare(
            'UPDATE mail_templates SET '
            . 'nom = :nom, '
            . 'objet = :objet, '
            . 'contenu_html = :contenu_html, '
            . 'contenu_texte = :contenu_texte, '
            . 'actif = :actif '
            . 'WHERE type_document = :type_document'
        );

        $statement->execute($payload);
    }
}
