<?php

namespace Core\App\Models;

use PDO;

class PluginModel
{
    protected PDO $db;

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

    /**
     * جلب حالة الإضافات من قاعدة البيانات
     * return [slug => bool]
     */
    public function getStates(): array
    {
        $stmt = $this->db->query("
            SELECT slug, is_active
            FROM plugins
        ");

        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $states = [];

        foreach ($rows as $row) {
            $states[$row['slug']] = (bool) $row['is_active'];
        }

        return $states;
    }

    /**
     * جلب جميع الإضافات من filesystem
     * + دمج حالة التفعيل من DB
     */
    public static function all(): array
    {
        $model  = new self();
        $states = $model->getStates();

        $plugins = [];

        foreach (glob(ROOT_PATH . '/plugins/*/plugin.json') as $file) {
            $config = json_decode(file_get_contents($file), true);

            if (!is_array($config) || empty($config['slug'])) {
                continue;
            }

            $slug = $config['slug'];

            $plugins[] = [
                'slug'        => $slug,
                'name'        => $config['name']        ?? $slug,
                'version'     => $config['version']     ?? '1.0.0',
                'description' => $config['description'] ?? '',
                'enabled'     => $states[$slug] ?? false,
            ];
        }

        return $plugins;
    }

    /**
     * ⚠️ Deprecated
     * التفعيل يتم حصريًا عبر PluginManager
     */
    public function enable(string $slug): void
    {
        throw new \RuntimeException(
            'PluginModel::enable() is deprecated. Use PluginManager::enable().'
        );
    }

    /**
     * ⚠️ Deprecated
     * التعطيل يتم حصريًا عبر PluginManager
     */
    public function disable(string $slug): void
    {
        throw new \RuntimeException(
            'PluginModel::disable() is deprecated. Use PluginManager::disable().'
        );
    }
}
