<?php

namespace Build\Models;

class ModuleModel
{
    private \PDO $dbConnection;
    private $table = 'build_modules';

    public function __construct()
    {
        $this->dbConnection = \CfSettings::getInstance()->getConnection();
    }

    public function get($name, $version = null): array|bool
    {
        $where = 'WHERE name LIKE :name ';
        $bind = ['name' => $name];
        if ($version) {
            $where .= ' AND version LIKE :version';
            $bind['version'] = $version;
        } else {
            $where .= ' AND latest IS TRUE';
        }
        $stmt = $this->dbConnection->prepare("SELECT * FROM {$this->table} $where");
        $stmt->execute($bind);
        $module = $stmt->fetch(\PDO::FETCH_ASSOC);
        if ($module) {
            $module['versions'] = json_decode($module['versions'], $associative = true);
            $module['author'] = json_decode($module['author'], $associative = true);
        }
        return $module;
    }
}
