<?php

namespace Korkz\Demirteknoloji\Controllers\Admin;

use Exception;
use Korkz\Demirteknoloji\Models\Admin\UserModel;
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;
use Ozdemir\Datatables\Datatables;
use Ozdemir\Datatables\DB\MySQL;

class UserController extends UserModel
{
    use AuthControl;
    use TokenConfig;
    use TokenAndValidControl;
    use Lang;
    use Logs;
    use Settings;

    public static function users(): void
    {
        $custom = self::langCustomStatic("admin", "users", $_SESSION["lang"] ?? "tr");
        $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 username,username_slug as slug ,created_at,updated_at from $databaseName.users");
        $dt->add('user_action', function ($data) use ($button) {
            return '<a href="admin/profile/' . $data['slug'] . '" class="text-center" > <button class="btn btn-primary w-100">' . $button . '</button></a>';
        });
        $dt->add('user_date', 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();
    }

    /**
     * @throws Exception
     */
    public function profileShow(string|array $paths, string $prefix, $username): void
    {
        $baseUrl = $this->baseUrl();
        self::checkAccess($paths, $prefix);
        $userCode = isset($_SESSION["userCode"]) ? $this->openKey($_SESSION["userCode"]) : null;
        $user = $this->usersData($userCode);
        $profile = $this->getData("users", ["userCode", "username"], ["username_slug" => $username])[0];
        if (!$profile) {
            header("Location:./");
            exit();
        }
        $userCode = $profile["userCode"];
        unset($profile["userCode"]);
        $lang = $this->getLang();
        $profile = [...$profile, "userCode" => $this->locKey("key", $userCode)];
        print $this->views("profile", ["baseUrl" => $baseUrl, "tittle" => "$username - Demirteknoloji yönetim paneli", "token" => $this->tokenCreate(), "lang" => $lang, "themeMode" => $_SESSION["theme_mode"] ?? "", "themeColor" => $_SESSION["theme_color"] ?? "theme-blue", "data" => [$username, "user" => $user, "profile" => $profile, "settings" => $this->settingData($lang),]]);

    }

    private function views(string $page, 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/$page", ["header" => "admin/layout/header", "footer" => "admin/layout/footer"]);
        $content = ob_get_clean();
        return $this->langViews("admin", "$page", $content, $lang);
    }

    /**
     * @throws Exception
     */
    public function usersShow(string|array $paths, string $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();
        print $this->views("users", ["baseUrl" => $baseUrl, "tittle" => " Demirteknoloji yönetim paneli", "token" => $this->tokenCreate(), "lang" => $lang, "active" => "users", "themeMode" => $_SESSION["theme_mode"] ?? "", "themeColor" => $_SESSION["theme_color"] ?? "theme-blue", "data" => ["user" => $user, "settings" => $this->settingData($lang),
            "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">',
            "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>'
        ]]);

    }

    public function passwordConfirm($request): void
    {
        try {
            $userCode = htmlspecialchars($request->userCode);
            $userCode = $this->openKey($userCode);
            $pass = htmlspecialchars($request->password);
            $password = md5($pass);
            $profile = $this->getData("users", ["password"], ["userCode" => $userCode, "password" => $password]);
            if ($profile) {
                echo json_encode(["profileConfirm" => true]);
                exit();
            }
            echo json_encode(["profileConfirm" => false]);
            exit();

        } catch (Exception $exception) {
            echo json_encode($exception);
        }
    }

    public function edit($request): void
    {
        try {
            $reply = $this->langReply("admin", "profile", $_SESSION["lang"] ?? "tr");
            $success = $reply["success"];
            $errors = $reply["errors"];
            $userCode = htmlspecialchars($request["userCode"]);
            $username = htmlspecialchars($request["username"]);
            $userCode = $this->openKey($userCode);
            $password = $request["password_after"] ?? null;
            $token = htmlspecialchars($request["token"]);
            $request = ["username" => $username, "password_after" => $password, "token" => $token, "operation" => "profileEdit", "location" => "admin", "page" => "profile", "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($userCode, $username, $password);
                if ($await) {
                    $result = ["conclusion" => "success", "message" => $success["messages"], "url" => $backUrl, "timeout" => 2000];
                } else {
                    $result = ["conclusion" => "error", "message" => $errors["messages"], "url" => $backUrl, "timeout" => 2000];
                }
            }
            $this->log($request, "user-update");
            echo json_encode($result);
            die();
        } catch (Exception $exception) {
            echo json_encode($exception);
            exit();
        }
    }

    /**
     * @param $request
     * @return void
     */
    public function userCreate($request): void
    {
        try {
            $reply = $this->langReply("admin", "users", $_SESSION["lang"] ?? "tr");
            $success = $reply["success"];
            $errors = $reply["errors"];
            $username = htmlspecialchars($request["username"]);
            $password = $request["password"];
            $token = htmlspecialchars($request["token"]);
            $request = ["username" => $username, "password" => $password, "token" => $token, "operation" => "userCreate", "location" => "admin", "page" => "users", "lang" => $this->getLang()];
            list($await, $result) = $this->tokenAndValidControl($request);
            if ($await) {
                $profile = $this->getData("users", ["*"], ["username_slug" => $this->seo($username)]);
                if ($profile) {
                    $await = false;
                    $result = ["conclusion" => "error", "message" => $errors["messages_2"]];
                }
                if ($await) {
                    $url = $this->baseUrl();
                    $backUrl = $url . "admin/users";
                    $await = $this->userCreateModel($username, $password);
                    if ($await) {
                        $result = ["conclusion" => "success", "message" => $success["messages"], "url" => $backUrl, "timeout" => 2000];
                    } else {
                        $result = ["conclusion" => "error", "message" => $errors["messages"], "url" => $backUrl, "timeout" => 2000];
                    }
                }
            }
            $this->log($request, "user-insert");
            echo json_encode($result);
            die();
        } catch (Exception $exception) {
            echo json_encode($exception);
            exit();
        }
    }
}