<?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 JetBrains\PhpStorm\NoReturn;
use kernel\AdminController;
use kernel\FileUpload;
use kernel\Flash;
use kernel\helpers\Debug;
use kernel\helpers\Files;
use ZipArchive;

class ModuleShopController extends AdminController
{
    protected ModuleShopService $moduleShopService;
    protected Files $files;

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

    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', 'igm']);
            $file->upload();
            $moduleShopForm->setItem('path_to_archive', $file->getUploadFile());
        }

        $tmpModuleDir = 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/' . $tmpModuleDir . "/";
            $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");
            }
            $this->files->recursiveRemoveDir($tmpModuleShopDirFull);

        }
        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/view/" . $module->id);
            }
        }
        Flash::setMessage("error", "Ошибка добавления модуля: <br>" . $moduleShopForm->getErrorsStr());
        $this->redirect("/admin/module_shop/module/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;
        $dir = $module->path_to_archive;
        $this->files->recursiveRemoveDir(ROOT_DIR .  dirname($dir, 2));


        $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);
    }
}