<?php
namespace CAE\Models;

use CAE\Lib\Database;

class Project
{
    private Database $db;

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

    public function all(bool $activeOnly = false): array
    {
        $where = $activeOnly ? 'WHERE is_active = 1' : '';
        $rows  = $this->db->fetchAll("SELECT * FROM projects {$where} ORDER BY created_at DESC");
        return array_map([$this, 'decode'], $rows);
    }

    public function find(int $id): ?array
    {
        $row = $this->db->fetch("SELECT * FROM projects WHERE id = ?", [$id]);
        return $row ? $this->decode($row) : null;
    }

    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('projects', $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('projects', $data, 'id = :id', ['id' => $id]);
    }

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

    public function countTopics(int $projectId): int
    {
        return $this->db->count('topics', 'project_id = ?', [$projectId]);
    }

    public function countGeneratedContent(int $projectId): int
    {
        $row = $this->db->fetch(
            "SELECT COUNT(*) AS cnt FROM generated_content gc
             JOIN topics t ON t.id = gc.topic_id
             WHERE t.project_id = ?",
            [$projectId]
        );
        return (int) ($row['cnt'] ?? 0);
    }

    private function encode(array $data): array
    {
        foreach (['brand_config', 'seo_config', 'content_rules'] as $field) {
            if (isset($data[$field]) && is_array($data[$field])) {
                $data[$field] = json_encode($data[$field]);
            }
        }
        return $data;
    }

    private function decode(array $row): array
    {
        foreach (['brand_config', 'seo_config', 'content_rules'] as $field) {
            if (!empty($row[$field]) && is_string($row[$field])) {
                $row[$field] = json_decode($row[$field], true) ?? [];
            }
        }
        return $row;
    }
}
