<?php

namespace Dashboard\Controllers\Appearance;

use Dashboard\Core\Controller;
use Verot\Upload\Upload;
use ZipArchive;

class ThemeAddController extends Controller
{
    public function __construct()
    {
        abort_perm('MANAGE_THEME');
    }

    public function index()
    {
        return view('appearance.themes.add');
    }

    public function add()
    {
        $upload = new Upload($_FILES["themeFile"]);
        $fileID = md5(uniqid(rand(0, 9999)));
        if ($upload->uploaded) {
            $upload->allowed = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
            $upload->file_new_name_body = $fileID;
            $upload->process(__ROOT__ . "/apps/update");
            if ($upload->processed) {
                $themeFilePath = __ROOT__ . '/apps/update';
                $themeZIPFile = $themeFilePath . '/' . $fileID . '.' . $upload->file_dst_name_ext;
                $themeSQLFile = $themeFilePath . '/install.sql';
                $themePHPFile = $themeFilePath . '/install.php';
                $zip = new ZipArchive;
                if ($zip->open($themeZIPFile) === TRUE) {
                    $themeName = "";
                    for ($i = 0; $i < $zip->numFiles; $i++) {
                        if (preg_match("/apps\/main\/app\/views\/themes\/([0-9a-zA-Z-_]+)\//i", $zip->getNameIndex($i), $themePathArray)) {
                            $themeName = $themePathArray[1];
                            break;
                        }
                    }
                    $zip->extractTo(__ROOT__);
                    $zip->close();
                    unlink($themeZIPFile);

                    if (file_exists($themeSQLFile)) {
                        $dbFileContents = file_get_contents($themeSQLFile);
                        $dbUpdate = db()->exec($dbFileContents);
                        unlink($themeSQLFile);
                    }
                    if (file_exists($themePHPFile)) {
                        include $themePHPFile;
                        unlink($themePHPFile);
                    }

                    if ($themeName != "") {
                        $themeJsonFile = __ROOT__ . '/apps/main/app/views/themes/' . $themeName . '/theme.json';
                        if (file_exists($themeJsonFile)) {
                            $themeJson = json_decode(file_get_contents($themeJsonFile), true);
                            $addThemeSettings = db()->prepare("INSERT INTO Settings (name, value) VALUES (?, ?)");
                            foreach ($themeJson["settingsCategories"] as $themeSettingsCategory) {
                                foreach ($themeSettingsCategory["settings"] as $key => $themeSettingsData) {
                                    $addThemeSettings->execute(array("theme:$themeName:" . $key, $themeSettingsData["value"]));
                                }
                            }
                        }
                    }

                    createLog("THEME_SETTINGS_UPDATED");
                    redirect(url('dashboard.appearance.themes.index'));
                }
                else {
                    return back()->flash("error", t__('An error occupied while unzip a file.'));
                }
            } else {
                return back()->flash("error", t__('An error occupied while uploading a file: %error%', ['%error%' => $upload->error]));
            }
        }
        else {
          return back()->flash("error", t__('An error occupied while uploading a file: %error%', ['%error%' => $upload->error]));
        }
    }
}