<?php

declare(strict_types=1);

namespace App\Modules\Settings;

use App\Core\Http\ToggleableRepositoryTrait;
use PDO;

final class EmailTemplateRepository
{
    use ToggleableRepositoryTrait;
    public function __construct(
        private readonly PDO $pdo
    ) {
    }

    /**
     * @return list<array<string, mixed>>
     */
    public function listAll(): array
    {
        $statement = $this->pdo->prepare(
            'SELECT t.id, t.name, t.subject, t.mailbox_id, t.attachment_1, t.is_active, t.created_at, t.updated_at,
                    m.name AS mailbox_name
             FROM email_templates t
             LEFT JOIN email_mailboxes m ON m.id = t.mailbox_id
             ORDER BY t.name ASC'
        );
        $statement->execute();
        $rows = $statement->fetchAll(PDO::FETCH_ASSOC);

        return is_array($rows) ? $rows : [];
    }

    /**
     * @return array<string, mixed>|null
     */
    public function findById(int $id): ?array
    {
        $statement = $this->pdo->prepare(
            'SELECT id, name, subject, body_html, mailbox_id, attachment_1, is_active, created_at, updated_at
             FROM email_templates
             WHERE id = :id'
        );
        $statement->execute(['id' => $id]);
        $row = $statement->fetch(PDO::FETCH_ASSOC);

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

    /**
     * @return list<array<string, mixed>>
     */
    public function listActive(): array
    {
        $statement = $this->pdo->prepare(
            'SELECT id, name, subject, mailbox_id, attachment_1
             FROM email_templates
             WHERE is_active = 1
             ORDER BY name ASC'
        );
        $statement->execute();
        $rows = $statement->fetchAll(PDO::FETCH_ASSOC);

        return is_array($rows) ? $rows : [];
    }

    /**
     * @param array<string, mixed> $data
     */
    public function save(array $data): void
    {
        $id = isset($data['id']) && $data['id'] !== '' ? (int) $data['id'] : null;

        $mailboxId = isset($data['mailbox_id']) && $data['mailbox_id'] !== '' && $data['mailbox_id'] !== '0'
            ? (int) $data['mailbox_id']
            : null;

        $attachment1 = isset($data['attachment_1']) && $data['attachment_1'] !== ''
            ? (string) $data['attachment_1']
            : null;

        $params = [
            'name' => trim((string) ($data['name'] ?? '')),
            'subject' => trim((string) ($data['subject'] ?? '')),
            'body_html' => (string) ($data['body_html'] ?? ''),
            'mailbox_id' => $mailboxId,
            'attachment_1' => $attachment1,
            'is_active' => isset($data['is_active']) ? 1 : 0,
        ];

        if ($id !== null) {
            $params['id'] = $id;
            $statement = $this->pdo->prepare(
                'UPDATE email_templates
                 SET name = :name, subject = :subject, body_html = :body_html,
                     mailbox_id = :mailbox_id, attachment_1 = :attachment_1, is_active = :is_active
                 WHERE id = :id'
            );
        } else {
            $statement = $this->pdo->prepare(
                'INSERT INTO email_templates (name, subject, body_html, mailbox_id, attachment_1, is_active)
                 VALUES (:name, :subject, :body_html, :mailbox_id, :attachment_1, :is_active)'
            );
        }

        $statement->execute($params);
    }

    public function delete(int $id): void
    {
        $statement = $this->pdo->prepare('DELETE FROM email_templates WHERE id = :id');
        $statement->execute(['id' => $id]);
    }

    public function toggleStatus(int $id): void
    {
        $this->toggleActive('email_templates', $id);
    }

    public function duplicate(int $id): void
    {
        $source = $this->findById($id);
        if ($source === null) {
            throw new \RuntimeException('Szablon nie istnieje');
        }

        $statement = $this->pdo->prepare(
            'INSERT INTO email_templates (name, subject, body_html, mailbox_id, attachment_1, is_active)
             VALUES (:name, :subject, :body_html, :mailbox_id, :attachment_1, 0)'
        );
        $statement->execute([
            'name' => 'Kopia — ' . $source['name'],
            'subject' => $source['subject'],
            'body_html' => $source['body_html'],
            'mailbox_id' => $source['mailbox_id'],
            'attachment_1' => $source['attachment_1'],
        ]);
    }
}
