<?php

declare(strict_types=1);

namespace App\Models;

use App\Core\Model;
use PDO;

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

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

    /** @param array<string,mixed> $data */
    public function save(array $data): void
    {
        $payload = [
            'type_document' => strtoupper(trim((string)$data['type_document'])),
            'document_id' => (int)$data['document_id'],
            'numero_document' => trim((string)$data['numero_document']),
            'destinataire' => trim((string)$data['destinataire']),
            'objet' => trim((string)$data['objet']),
            'envoye_par_id' => $data['envoye_par_id'] !== null
                ? (int)$data['envoye_par_id']
                : null,
            'envoye_par_nom' => trim((string)$data['envoye_par_nom']),
            'date_envoi' => (string)$data['date_envoi'],
        ];

        $existing = $this->find(
            $payload['type_document'],
            $payload['document_id']
        );

        if ($existing === null) {
            $statement = $this->db->prepare(
                'INSERT INTO document_mail_deliveries ('
                . 'type_document, document_id, numero_document, destinataire, '
                . 'objet, envoye_par_id, envoye_par_nom, date_envoi'
                . ') VALUES ('
                . ':type_document, :document_id, :numero_document, :destinataire, '
                . ':objet, :envoye_par_id, :envoye_par_nom, :date_envoi'
                . ')'
            );

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

        $statement = $this->db->prepare(
            'UPDATE document_mail_deliveries SET '
            . 'numero_document = :numero_document, '
            . 'destinataire = :destinataire, '
            . 'objet = :objet, '
            . 'envoye_par_id = :envoye_par_id, '
            . 'envoye_par_nom = :envoye_par_nom, '
            . 'date_envoi = :date_envoi '
            . 'WHERE type_document = :type_document '
            . 'AND document_id = :document_id'
        );

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