<?php

namespace Core\App\Models;

use PDO;

class LanguageModel
{
    protected PDO $db;

    public function __construct()
    {
        $this->db = \db();
    }

    public function getAll(): array
    {
        $stmt = $this->db->query("SELECT * FROM languages ORDER BY id ASC");
        return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }

    public function getById(int $id): ?array
    {
        $stmt = $this->db->prepare("SELECT * FROM languages WHERE id = ?");
        $stmt->execute([$id]);
        return $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
    }

    public function getByCode(string $code): ?array
    {
        $stmt = $this->db->prepare("SELECT * FROM languages WHERE code = ?");
        $stmt->execute([$code]);
        return $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
    }

    public function add(string $code, string $name, string $direction, int $isDefault = 0): bool
    {
        if ($isDefault) {
            $this->clearDefault();
        }

        $stmt = $this->db->prepare("
            INSERT INTO languages (code, name, direction, is_default)
            VALUES (?, ?, ?, ?)
        ");

        return $stmt->execute([$code, $name, $direction, $isDefault]);
    }

    public function update(int $id, string $code, string $name, string $direction, int $isDefault = 0): bool
    {
        if ($isDefault) {
            $this->clearDefault();
        }

        $stmt = $this->db->prepare("
            UPDATE languages
            SET code = ?, name = ?, direction = ?, is_default = ?
            WHERE id = ?
        ");

        return $stmt->execute([$code, $name, $direction, $isDefault, $id]);
    }

    public function delete(int $id): bool
    {
        $stmt = $this->db->prepare("DELETE FROM languages WHERE id = ?");
        return $stmt->execute([$id]);
    }

    public function setDefault(int $id): bool
    {
        $this->clearDefault();

        $stmt = $this->db->prepare("
            UPDATE languages
            SET is_default = 1
            WHERE id = ?
        ");

        return $stmt->execute([$id]);
    }

    public function getDefault(): ?array
    {
        $stmt = $this->db->query("SELECT * FROM languages WHERE is_default = 1 LIMIT 1");
        return $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
    }

    protected function clearDefault(): void
    {
        $this->db->exec("UPDATE languages SET is_default = 0");
    }
}
