<?php

namespace App\Models;

use App\Core\Model;

/**
 * ITSWEBER CMS – MarketplaceInstalled Model
 *
 * Tracks packages (themes/plugins) installed via the Marketplace.
 */
class MarketplaceInstalled extends Model
{
    protected static string $table = 'iw_marketplace_installed';

    /**
     * Check if a package slug is already installed via marketplace.
     */
    public static function isInstalled(string $slug): bool
    {
        return static::findBySlug($slug) !== null;
    }

    /**
     * Get all packages that have a newer remote version available.
     */
    public static function getUpdatable(): array
    {
        return static::db()->fetchAll(
            "SELECT * FROM " . static::$table
            . " WHERE remote_version IS NOT NULL AND remote_version != version"
            . " ORDER BY name ASC"
        );
    }

    /**
     * Update the remote_version for a given slug.
     */
    public static function setRemoteVersion(string $slug, string $remoteVersion): void
    {
        static::db()->query(
            "UPDATE " . static::$table . " SET remote_version = :rv WHERE slug = :slug",
            ['rv' => $remoteVersion, 'slug' => $slug]
        );
    }

    /**
     * Get all installed packages as slug => row map for quick lookup.
     */
    public static function getInstalledMap(): array
    {
        $rows = static::all('name', 'ASC');
        $map = [];
        foreach ($rows as $row) {
            $map[$row['slug']] = $row;
        }
        return $map;
    }
}
