<?php

namespace Korkz\Demirteknoloji\Controllers\Admin;
use Exception;
use Korkz\Demirteknoloji\Models\Admin\ReferencesModel;
use Korkz\Demirteknoloji\Router\View;
use Korkz\Demirteknoloji\traits\AuthControl;
use Korkz\Demirteknoloji\traits\Lang;
use Korkz\Demirteknoloji\traits\Settings;
use Korkz\Demirteknoloji\traits\TokenAndValidControl;
use Korkz\Demirteknoloji\traits\TokenConfig;
use Korkz\Demirteknoloji\traits\TranslateTrait;
use Ozdemir\Datatables\Datatables;
use Ozdemir\Datatables\DB\MySQL;

class ReferencesController extends ReferencesModel
{
    use AuthControl;
    use Lang;
    use TokenConfig;
    use TokenAndValidControl;
    use Settings;
    use TranslateTrait;

    /**
     * @throws Exception
     */
    public function show(string|array $paths, $prefix): void
    {
        $baseUrl = $this->baseUrl();
        self::checkAccess($paths, $prefix);
        $userCode = isset($_SESSION["userCode"]) ? $this->openKey($_SESSION["userCode"]) : null;
        $user = $this->usersData($userCode);
        $lang = $this->getLang();
        $settings=$this->settingData($lang);
        print $this->views(["baseUrl" => $baseUrl, "tittle" => " Demirteknoloji yönetim paneli", "token" => $this->tokenCreate(), "lang" => $lang, "active" => "references", "themeMode" => $_SESSION["theme_mode"] ?? "", "themeColor" => $_SESSION["theme_color"] ?? "theme-blue", "data" => ["user" => $user, "settings" => $settings,
            "head" => '
                <!-- JQuery DataTable Css -->
                <link rel="stylesheet" href="assets/admin/plugins/jquery-datatable/dataTables.bootstrap4.min.css">
                <!-- SweetAlert2 Css -->
                <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.5/dist/sweetalert2.min.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" => '
                <!-- Jquery DataTable Plugin Js -->
                <script src="assets/admin/bundles/datatablescripts.bundle.js"></script>
                <script src="assets/admin/plugins/jquery-datatable/buttons/dataTables.buttons.min.js"></script>
                <script src="assets/admin/plugins/jquery-datatable/buttons/buttons.bootstrap4.min.js"></script>
                <script src="assets/admin/plugins/jquery-datatable/buttons/buttons.colVis.min.js"></script>
                <script src="assets/admin/plugins/jquery-datatable/buttons/buttons.flash.min.js"></script>
                <script src="assets/admin/plugins/jquery-datatable/buttons/buttons.html5.min.js"></script>
                <script src="assets/admin/plugins/jquery-datatable/buttons/buttons.print.min.js"></script>
                <!-- SweetAlert2 Js -->
                <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.5/dist/sweetalert2.all.min.js"></script>
                <!-- dropzone Plugin Js --> 
                <script src="assets/admin/plugins/dropzone/dropzone.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/references", ["header" => "admin/layout/header", "footer" => "admin/layout/footer"]);
        $content = ob_get_clean();
        return $this->langViews("admin", "references", $content, $lang);
    }

    /**
     * @param $request
     * @return array
     */
    public function refTranslate($request): array
    {
        $text = $request->translateText;
        $lang = $request->toLang;
        return $this->translate($text, $lang);
    }

    /**
     * @param $request
     * @param $requestFile
     * @return array|Exception|mixed
     */
    public function refAdd($request, $requestFile): mixed
    {
        try {
            $reply = $this->langReply("admin", "references", $_SESSION["lang"] ?? "tr");
            $success = $reply["success"]["insert"];
            $errors = $reply["errors"]["insert"];
            $await = true;
            $requestPost = [];
            $result = [];
            $requestTr = [];
            $requestEn = [];
            if (isset($request["brandName_tr"]) && isset($request["brandDescription_tr"]) && isset($request["brandName_en"]) && isset($request["brandDescription_en"])) {
                $brandName_tr = $request["brandName_tr"];
                $brandDescription_tr = $request["brandDescription_tr"];
                $brandName_en = $request["brandName_en"];
                $brandDescription_en = $request["brandDescription_en"];
                $requestTr = ["brandName" => $brandName_tr, "brandDescription" => $brandDescription_tr];
                $requestEn = ["brandName" => $brandName_en, "brandDescription" => $brandDescription_en];
                $requestPost = ["brandName_tr" => $brandName_tr, "brandDescription_tr" => $brandDescription_tr, "brandName_en" => $brandName_en, "brandDescription_en" => $brandDescription_en];

            } elseif (isset($request["brandName_tr"]) && isset($request["brandDescription_tr"])) {
                $brandName_tr = $request["brandName_tr"];
                $brandDescription_tr = $request["brandDescription_tr"];
                $requestTr = ["brandName" => $brandName_tr, "brandDescription" => $brandDescription_tr];
                $requestPost = ["brandName_tr" => $brandName_tr, "brandDescription_tr" => $brandDescription_tr];

            } elseif (isset($request["brandName_en"]) && isset($request["brandDescription_en"])) {
                $brandName_en = $request["brandName_en"];
                $brandDescription_en = $request["brandDescription_en"];
                $requestEn = ["brandName" => $brandName_en, "brandDescription" => $brandDescription_en];
                $requestPost = ["brandName_en" => $brandName_en, "brandDescription_en" => $brandDescription_en];

            } else {
                if (isset($request["brandName_tr"]) && isset($request["brandName_en"])) {
                    $brandName_tr = $request["brandName_tr"];
                    $brandName_en = $request["brandName_en"];
                    $requestTr = ["brandName" => $brandName_tr];
                    $requestEn = ["brandName" => $brandName_en];
                    $requestPost = ["brandName_tr" => $brandName_tr, "brandName_en" => $brandName_en];


                } elseif (isset($request["brandName_tr"])) {
                    $brandName_tr = $request["brandName_tr"];
                    $requestTr = ["brandName" => $brandName_tr];
                    $requestPost = ["brandName_tr" => $brandName_tr];

                } elseif (isset($request["brandName_en"])) {
                    $brandName_en = $request["brandName_en"];
                    $requestEn = ["brandName" => $brandName_en];
                    $requestPost = ["brandName_en" => $brandName_en];

                } else {
                    $result = ["conclusion" => "error", "message" => $errors["messages_2"]];
                    $await = false;
                }

            }
            if ($await) {
                $token = htmlspecialchars($request["token"]);
                $request = ["referenceLogo" => $requestFile["referenceLogo"], ...$requestPost, "token" => $token, "operation" => "refAdd", "location" => "admin", "page" => "references", "lang" => $this->getLang()];
                list($await, $result) = $this->tokenAndValidControl($request);
                if ($await) {
                    $lang = $this->getLang();
                    if ($lang === "tr") {
                        $lang = "tr_TR";
                    } else {
                        $lang = "en_GB";
                    }
                    $option = ["tittle" => "", "max_size" => 0, "type" => "", "uploadPath" => "reference", "allowed" => "image/*", "resize" => ["boolean" => false, "image_x" => 0, "image_y" => 0]];
                    $file = $requestFile["referenceLogo"];
                    $await = $this->refFileUploadedModel($file, $option, $lang, "insert");

                    if ($await) {
                        $requestAdds=$await["requestAdds"];
                        $requestAddsNew = array_map(function($requestAdd) use ($requestTr, $requestEn) {
                            $lang = $requestAdd["lang"];
                            $lastId = $requestAdd["lastInsertId"];
                            $data = ($lang === "tr") ? $requestTr : $requestEn;

                            return [
                                "lastId" => $lastId,
                                ...$data
                            ];
                        }, $requestAdds);

                        $await=$this->refModel($requestAddsNew,"insert");
                        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, "references");

            }
            return $result;
        } catch (Exception $exception) {
          return  $exception;
        }
    }

    /**
     * @return void
     */
    public static function references(): void
    {
        $lang=$_SESSION["lang"] ?? "en";

        $custom = self::langCustomStatic("admin", "references", $lang);
        $button = $custom["custom"]["button_text"];
        $env = self::staticEnv();
        $databaseName = $env["DATABASE_NAME"];
        $config = ['host' => $env["DATABASE_HOST"], 'port' => $env["DATABASE_PORT"], 'username' => $env["DATABASE_USER"], 'password' => $env["DATABASE_PASSWORD"], 'database' => $databaseName];
        $dt = new Datatables(new MySQL($config));
        $dt->query("Select ID,file_path,title,description from $databaseName.dm_references where $databaseName.dm_references.lang='$lang'");

        $dt->add('ref_file_path', function ($data) {
            return '<img src="'.$data["file_path"] .'" alt="'.$data["title"] .'" width="96">';
        });

        $dt->add('ref_action', function ($data) use ($button) {
            return '<a href="javascript:void(0)" class="text-center" > <button class="btn btn-primary w-100">' . $button . '</button></a>';
        });

//        $dt->add('ref_action', function ($data) {
//            if (is_null($data["updated_at"])) {
//                $date = $data["created_at"];
//            } else {
//                $date = $data["created_at"] . "/" . $data["updated_at"];
//            }
//            return $date;
//        });

        echo $dt->generate();
    }

}