<?php
declare(strict_types=1);

namespace App\Models;

use App\Core\Model;

final class DictionaryModel extends Model
{
    public function all(): array
    {
        return $this->db->query("
            SELECT *
            FROM language_dictionary
            ORDER BY dict_key ASC, lang_code ASC
        ")->fetchAll();
    }

    public function findById(int $id): ?array
    {
        $stmt = $this->db->prepare("SELECT * FROM language_dictionary WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $id]);
        $row = $stmt->fetch();
        return $row ?: null;
    }

    public function create(array $data): int
    {
        $stmt = $this->db->prepare("
            INSERT INTO language_dictionary (lang_code, dict_key, dict_value, group_name)
            VALUES (:lang_code, :dict_key, :dict_value, :group_name)
        ");
        $stmt->execute([
            ':lang_code' => $data['lang_code'],
            ':dict_key' => $data['dict_key'],
            ':dict_value' => $data['dict_value'],
            ':group_name' => $data['group_name'] ?: null,
        ]);
        return (int) $this->db->lastInsertId();
    }

    public function update(int $id, array $data): void
    {
        $stmt = $this->db->prepare("
            UPDATE language_dictionary
            SET lang_code = :lang_code,
                dict_key = :dict_key,
                dict_value = :dict_value,
                group_name = :group_name
            WHERE id = :id
        ");
        $stmt->execute([
            ':id' => $id,
            ':lang_code' => $data['lang_code'],
            ':dict_key' => $data['dict_key'],
            ':dict_value' => $data['dict_value'],
            ':group_name' => $data['group_name'] ?: null,
        ]);
    }
}
