<?php

namespace Dashboard\Controllers\Appearance;

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

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

    public function index()
    {
        $themeJsonFile = themePath(true) . '/theme.json';
        if (!file_exists($themeJsonFile))
            redirect("/404");

        $themeJson = json_decode(file_get_contents($themeJsonFile), true);
        $themeName = themeName();

        if (!get("category")) {
          $themeSettingsCategoryKey = array_keys($themeJson["settingsCategories"])[0];
          redirect("?category=$themeSettingsCategoryKey");
        }

        return view('appearance.themes.settings', compact('themeJson', 'themeName'));
    }

    public function update()
    {
        $themeJsonFile = themePath(true) . '/theme.json';
        $themeJson = json_decode(file_get_contents($themeJsonFile), true);
        $themeName = themeName();

				// Update input settings
		    foreach ($_POST as $key => $value) {
			    if (substr($key, 0, 9) == 'settings_') {
				    $settingKey = substr($key, 9);
				    
				    // Check if the setting exists in theme.json
				    $config = $themeJson["settingsCategories"][input("category")]["settings"][$settingKey];
				    if (isset($config)) {
					    // Check if the setting has dependencies (requirements)
					    if (isset($config['requirements'])) {
						    $isRequirementsMet = true;
						    
						    // Verify all dependencies are satisfied
						    foreach ($config['requirements'] as $requiredKey) {
							    $dependencyValue = $_POST["settings_$requiredKey"] ?? null;
							    if ($dependencyValue != '1') {
								    $isRequirementsMet = false;
								    break;
							    }
						    }
								
						    
						    // If dependencies are not met, set default value
						    if (!$isRequirementsMet) {
							    $value = $config['value'] ?? '';
						    }
					    }
					    
					    // Update the setting
					    updateSetting("theme:$themeName:$settingKey", $value);
				    }
			    }
		    }

				// Upload images
        foreach ($_FILES as $key => $value) {
            if (substr($key, 0, 9) == 'settings_') {
                $settingsKey = substr($key, 9);
                $settingsType = $themeJson["settingsCategories"][input("category")]["settings"][$settingsKey]["settings"]["type"];
                if ($settingsType == "image") {
                    if (input()->file($key)->size) {
                        $upload = new Upload($_FILES[$key]);
                        $imageID = md5(uniqid(rand(0, 9999)));
                        $imageDir = "/apps/main/public/images/uploads";
                        if ($upload->uploaded) {
                            $upload->allowed = array("image/*");
                            $upload->file_overwrite = true;
                            $upload->file_new_name_body = $imageID;
                            $upload->process(__ROOT__ . $imageDir);
                            updateSetting("theme:$themeName:$settingsKey", "/assets/core/images/uploads/" . $imageID . "." . $upload->file_dst_name_ext);
                            updateSetting("updatedAt", time());
                            if (!$upload->processed) {
                                return back()->flash("error", t__('An error occupied while uploading an image: %error%', ['%error%' => $upload->error]));
                            }
                        }
                    }
                }
            }
        }

        createLog("THEME_SETTINGS_UPDATED");
        return back()->flash("success", t__('Changes has been saved successfully!'));
    }
}