<?php

namespace Korkz\Demirteknoloji\Controllers\Admin;

use Exception;
use Korkz\Demirteknoloji\Models\Admin\SettingsModel;
use Korkz\Demirteknoloji\Router\View;
use Korkz\Demirteknoloji\traits\AuthControl;
use Korkz\Demirteknoloji\traits\Lang;
use Korkz\Demirteknoloji\traits\Logs;
use Korkz\Demirteknoloji\traits\Settings;
use Korkz\Demirteknoloji\traits\TokenAndValidControl;
use Korkz\Demirteknoloji\traits\TokenConfig;

class SettingsController extends SettingsModel
{
    use AuthControl;
    use TokenConfig;
    use TokenAndValidControl;
    use Lang;
    use Logs;
    use Settings;

    /**
     * @throws Exception
     */
    public function show(string|array $paths, string $prefix): void
    {
        $baseUrl = $this->baseUrl();
        $lang = $this->getLang();
        self::checkAccess($paths, $prefix);
        $userCode = isset($_SESSION["userCode"]) ? $this->openKey($_SESSION["userCode"]) : null;
        $user = $this->usersData($userCode);
        print $this->views(["baseUrl" => $baseUrl, "tittle" => " Demirteknoloji yönetim paneli", "token" => $this->tokenCreate(), "lang" => $lang, "active" => "settings", "themeMode" => $_SESSION["theme_mode"] ?? "", "themeColor" => $_SESSION["theme_color"] ?? "theme-blue", "data" => ["user" => $user, "settings" => $this->settingData($lang, true), "head" => '
                <!-- Bootstrap Tagsinput Css -->
                <link rel="stylesheet" href="assets/admin/plugins/bootstrap-tagsinput/bootstrap-tagsinput.css">
                 <!-- dropzone Css -->
                <link rel="stylesheet" href="assets/admin/plugins/dropzone/dropzone.min.css" type="text/css" />
                <link rel="stylesheet" href="assets/admin/plugins/dropzone/custom-dropzone.css" type="text/css" />', "script" => '
<!-- Bootstrap Tags Input Plugin Js --> 
<script src="assets/admin/plugins/bootstrap-tagsinput/bootstrap-tagsinput.js"></script>
<!-- dropzone Plugin Js --> 
<script src="assets/admin/plugins/dropzone/dropzone.min.js"></script>
<!-- notify Plugin Js --> 
<script src="assets/admin/plugins/notify/notify.min.js"></script>']]);

    }

    /**
     * @param array $dataBinds
     * @return array|string
     */
    private function views(array $dataBinds = []): array|string
    {
        ob_start();
        $lang = "";
        if (!empty($dataBinds)) {
            foreach ($dataBinds as $key => $dataBind) {
                View::bind($key, $dataBind);
                if (str_starts_with($key, "lang")) {
                    $lang = $dataBind;
                }
            }
        }
        View::render("admin/settings", ["header" => "admin/layout/header", "footer" => "admin/layout/footer"]);
        $content = ob_get_clean();
        return $this->langViews("admin", "settings", $content, "$lang");
    }

    /**
     * @param $request
     * @return void
     */
    public function edit($request): void
    {
        try {
            $reply = $this->langReply("admin", "settings", $_SESSION["lang"] ?? "tr");
            $success = $reply["success"];
            $errors = $reply["errors"];
            $tittle = htmlspecialchars($request["tittle"]);
            $keyword = htmlspecialchars($request["keyword"]);
            $description = htmlspecialchars($request["description"]);
            $author = htmlspecialchars($request["author"]);
            $email = htmlspecialchars($request["email"]);
            $phone = htmlspecialchars($request["phone"]);
            $footer_text = htmlspecialchars($request["footer_text"]);
            $setting_lang = htmlspecialchars($request["setting_lang"]);
            $token = htmlspecialchars($request["token"]);
            $request = ["tittle" => $tittle, "keyword" => $keyword, "description" => $description, "author" => $author, "email" => $email, "phone" => $phone, "footer_text" => $footer_text, "setting_lang" => $setting_lang, "token" => $token, "operation" => "settingEdit", "location" => "admin", "page" => "settings", "lang" => $this->getLang()];
            list($await, $result) = $this->tokenAndValidControl($request);
            if ($await) {
                $url = $this->baseUrl();
                $backUrl = !empty($_GET["redirect"]) ? htmlspecialchars($_GET["redirect"]) : $url . "admin";
                $await = $this->editModel($tittle, $keyword, $description, $author, $email, $phone, $footer_text, $setting_lang);
                if ($await) {
                    $result = ["conclusion" => "success", "message" => $success["messages"]];
                } else {
                    $result = ["conclusion" => "error", "message" => $errors["messages"]];
                }
            }
            $this->log($request, "settings-update");
            echo json_encode($result);
            die();
        } catch (Exception $exception) {
            echo json_encode($exception);
            exit();
        }
    }

    /**
     * @param $request
     * @param $requestFile
     * @param $fileToWhere
     * @param $path
     * @return void
     */
    public function settingFileUploaded($request, $requestFile, $fileToWhere, $path): void
    {
        try {
            $reply = $this->langReply("admin", "$path", $_SESSION["lang"] ?? "tr");
            $success = $reply["success"];
            $errors = $reply["errors"];
            $file_languages["file_languages"] = match ($fileToWhere) {
                "logo" => $request["dropzone-logo"],
                "favicon" => $request["dropzone-fav"],
                "default" => []
            };
            $token = htmlspecialchars($request["token"]);
            $request = ["$fileToWhere" => $requestFile["$fileToWhere"], "file_languages" => $file_languages["file_languages"], "token" => $token, "operation" => "setting" . ucwords($fileToWhere), "location" => "admin", "page" => "$path", "lang" => $this->getLang()];
            list($await, $result) = $this->tokenAndValidControl($request);
            if ($await) {
                $lang = $this->getLang();
                if ($lang === "tr") {
                    $lang = "tr_TR";
                } else {
                    $lang = "en_GB";
                }
                if ($fileToWhere === "logo") {
                    $await = true;
                    $option = ["tittle" => "", "max_size" => 1048, "type" => "png", "uploadPath" => "logo", "allowed" => "image/*", "resize" => ["boolean" => false, "image_x" => 0, "image_y" => 0]];
                    $file = $requestFile["$fileToWhere"];
                } elseif ($fileToWhere === "favicon") {
                    $await = true;
                    $option = ["tittle" => "", "max_size" => 1048, "type" => "", "uploadPath" => "favicon", "allowed" => "*", "resize" => ["boolean" => false, "image_x" => 0, "image_y" => 0]];
                    $file = $requestFile["$fileToWhere"];
                } else {
                    $await = false;
                    $option = [];
                    $file = $requestFile[""] = [];

                }
                if ($await) {

                    $await = $this->settingFileUploadedModel($file, $option, $fileToWhere, $lang, $file_languages);
                    if ($await) {
                        $result = ["conclusion" => "success", "message" => $success["messages"]];
                    } else {
                        $result = ["conclusion" => "error", "message" => $errors["messages"]];
                    }
                } else {
                    $result = ["conclusion" => "error", "message" => $errors["messages"]];
                }
            }
            $this->log($request, "setting-$fileToWhere");
            echo json_encode($result);
            die();
        } catch (Exception $exception) {
            echo json_encode($exception);
            exit();
        }
    }

    public function settingFileQuery($request)
    {
        $op = match ($request["op"]) {
            "dropzone-logo" => "Logo",
            "dropzone-fav" => "Favicon",
            "default" => null
        };
        $langRequest = $request["lang"];
        if ($op !== null) {
            $path = $this->getData("settings", [$op], ["Lang" => $langRequest]);
            if ($path) {
                if (!empty($path[0]["$op"])) {
                    $pathDir = $path[0]["$op"];
                } else {
                    $pathDir = null;
                }

            } else {
                $pathDir = null;
            }
        } else {
            $pathDir = null;
        }
        return $pathDir;
    }
}