<?php
namespace CAE\Models;

use CAE\Lib\Database;

class PromptTemplate
{
    private Database $db;

    public function __construct()
    {
        $this->db = Database::getInstance();
    }

    public function all(): array
    {
        return $this->db->fetchAll(
            "SELECT pt.*, p.name AS page_type_name
             FROM prompt_templates pt
             LEFT JOIN page_types p ON p.id = pt.page_type_id
             ORDER BY p.name, pt.version DESC"
        );
    }

    public function find(int $id): ?array
    {
        $row = $this->db->fetch(
            "SELECT pt.*, p.name AS page_type_name
             FROM prompt_templates pt
             LEFT JOIN page_types p ON p.id = pt.page_type_id
             WHERE pt.id = ?",
            [$id]
        );
        return $row ? $this->decode($row) : null;
    }

    public function findActiveForPageType(int $pageTypeId): ?array
    {
        $row = $this->db->fetch(
            "SELECT * FROM prompt_templates
             WHERE page_type_id = ? AND is_active = 1
             ORDER BY version DESC LIMIT 1",
            [$pageTypeId]
        );
        return $row ? $this->decode($row) : null;
    }

    public function forPageType(int $pageTypeId): array
    {
        return $this->db->fetchAll(
            "SELECT * FROM prompt_templates WHERE page_type_id = ? ORDER BY version DESC",
            [$pageTypeId]
        );
    }

    public function create(array $data): int
    {
        $data = $this->encode($data);
        $data['created_at'] = date('Y-m-d H:i:s');
        $data['updated_at'] = date('Y-m-d H:i:s');
        return $this->db->insert('prompt_templates', $data);
    }

    public function update(int $id, array $data): bool
    {
        $data = $this->encode($data);
        $data['updated_at'] = date('Y-m-d H:i:s');
        return $this->db->update('prompt_templates', $data, 'id = :id', ['id' => $id]);
    }

    public function delete(int $id): bool
    {
        return $this->db->delete('prompt_templates', 'id = ?', [$id]);
    }

    private function encode(array $data): array
    {
        if (isset($data['variables']) && is_array($data['variables'])) {
            $data['variables'] = json_encode($data['variables']);
        }
        return $data;
    }

    private function decode(array $row): array
    {
        if (!empty($row['variables']) && is_string($row['variables'])) {
            $row['variables'] = json_decode($row['variables'], true) ?? [];
        }
        return $row;
    }
}
