<?php

namespace app\modules\module_shop\controllers;

use app\modules\module_shop\models\forms\CreateModuleShopForm;
use app\modules\module_shop\models\ModuleShop;
use app\modules\module_shop\services\ModuleShopService;
use Cassandra\Date;
use JetBrains\PhpStorm\NoReturn;
use kernel\AdminController;
use kernel\app_modules\tag\services\TagService;
use kernel\FileUpload;
use kernel\Flash;
use kernel\helpers\Debug;
use kernel\services\ModuleService;
use mysql_xdevapi\Exception;
use ZipArchive;

class ModuleShopController extends AdminController
{
    protected ModuleShopService $moduleShopService;

    protected function init(): void
    {
        parent::init();
        $this->cgView->viewPath = APP_DIR . "/modules/module_shop/views/";
        $this->moduleShopService = new ModuleShopService();
    }

    public function actionCreate(): void
    {
        $this->cgView->render("form.php");
    }

    /**
     * @throws \Exception
     */
    #[NoReturn] public function actionAdd(): void
    {
        $moduleShopForm = new CreateModuleShopForm();
        $moduleShopForm->load($_REQUEST);

        if (isset($_FILES['path_to_archive']) && $_FILES['path_to_archive']['error'] === UPLOAD_ERR_OK) {
            $file = new FileUpload($_FILES['path_to_archive'], ['zip', 'rar', 'itguild']);
            $file->upload();
            $moduleShopForm->setItem('path_to_archive', $file->getUploadFile());
        }

        $tmpThemeDir = md5(time());
        $zip = new ZipArchive;
        $res = $zip->open(ROOT_DIR . $moduleShopForm->getItem('path_to_archive'));
        if ($res === TRUE) {
            if (!is_dir(RESOURCES_DIR . '/tmp/ms/')) {
                mkdir(RESOURCES_DIR . '/tmp/ms/');
            }
            $tmpModuleShopDirFull = RESOURCES_DIR . '/tmp/ms/' . $tmpThemeDir . "/";
            $zip->extractTo($tmpModuleShopDirFull);
            $zip->close();

            if (file_exists($tmpModuleShopDirFull . "app/manifest.json")){
                $moduleInfo = $this->moduleShopService->getModuleInfo($tmpModuleShopDirFull . "app");
                $moduleShopForm->load($moduleInfo);
            }
            else {
                throw new \Exception("Manifest.json file not found");
            }
        }
        else {
            throw new \Exception("zip not found");
        }

        if ($moduleShopForm->validate()) {
            $module = $this->moduleShopService->create($moduleShopForm);
            if ($module) {
                Flash::setMessage("success", "Модуль " . $moduleShopForm->getItem("name") . " добавлен.");
                $this->redirect("/admin/module_shop/" . $module->id);
            }
        }
        Flash::setMessage("error", "Ошибка добавления модуля: <br>" . $moduleShopForm->getErrorsStr());
        $this->redirect("/admin/module_shop/create");
    }

    public function actionIndex(int $page_number = 1): void
    {
        $this->cgView->render("index.php", ['page_number' => $page_number]);
    }

    public function actionView(int $id): void
    {

        $module = ModuleShop::find($id);
        if (!$module) {
            throw new Exception("The module not found");
        }
        $this->cgView->render("view.php", ['module' => $module]);
    }


    public function actionDelete(int $id): void
    {
        $module = ModuleShop::find($id);
        if (!$module) {
            throw new Exception("The module not found");
        }
        $name = $module->name;

        $module->delete();
        Flash::setMessage("success", "Модуль " . $name . " удален.");
        $this->redirect("/admin/module_shop");
    }

    public function actionPack(int $id): void
    {
        $module = ModuleShop::find($id);
        if (!$module) {
            throw new Exception("The module not found");
        }
        $this->moduleShopService->packModule($module);
    }
}