<?php

namespace kernel\modules\admin_themes\controllers;

use DirectoryIterator;
use JetBrains\PhpStorm\NoReturn;
use kernel\AdminController;
use kernel\helpers\Debug;
use kernel\models\Option;
use kernel\Request;

class AdminThemeController extends AdminController
{
    protected function init(): void
    {
        parent::init();
        $this->cgView->viewPath = KERNEL_MODULES_DIR . "/admin_themes/views/";
    }

    public function actionIndex(): void
    {
        $admin_theme_paths = Option::where("key", "admin_theme_paths")->first();

        $dirs = [];
        if ($admin_theme_paths){
            $path = json_decode($admin_theme_paths->value);
            foreach ($path->paths as $p){
                $dirs[] = getConst($p);
            }
        }

        $info_to_table = [];
        $meta = [];
        $meta['columns'] = [
            "preview" => "Превью",
            "name" => "Название",
            "author" => "Автор",
            "version" => "Версия",
            "description" => "Описание"
        ];
        $meta['params'] = ["class" => "table table-bordered"];
        $meta['perPage'] = 10;
        $meta['baseUrl'] = "/admin/settings/admin-themes";
        $meta['currentPage'] = 1;

        $info_to_table['meta'] = $meta;

        $themes_info = [];
        foreach ($dirs as $dir){
            $i = 1;
            foreach (new DirectoryIterator($dir) as $fileInfo) {
                $info = [];
                if($fileInfo->isDot()) continue;
                $info['id'] = $i;
                $themes_info[] = array_merge($info, $this->adminThemeService->getAdminThemeInfo($fileInfo->getPathname()));
                $i++;
            }
        }
        $info_to_table['meta']['total'] = count($themes_info);
        $info_to_table['data'] = $themes_info;

        $this->cgView->render("index.php", ['json' => json_encode($info_to_table, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)]);
    }

    #[NoReturn] public function actionActivate(): void
    {
        $request = new Request();
        $this->adminThemeService->setActiveAdminTheme($request->get("p"));

        $this->cgView->render("view.php", ['data' => $this->adminThemeService->getAdminThemeInfo($request->get("p"))]);
    }

}