<?php

use Korkz\Demirteknoloji\config\MailConfigure;
use Korkz\Demirteknoloji\Controllers\Admin\ReferencesController;
use Korkz\Demirteknoloji\Controllers\Admin\UserController;
use Korkz\Demirteknoloji\Router\Router;

/**
 * @return array|mixed
 */
function postOrJsonControl(): mixed
{
    if (!empty($_POST)) {
        return $_POST;
    }
    return json_decode(file_get_contents("php://input"));
}

require_once __DIR__ . "/classes.php";
$router = new Router();
$router->prefix("/", function ($router) {
    global $Home;
    global $Contact;
    global $About;
    $router->get(['/', "/index"], function () use ($Home) {
        try {
            $Home->show("index");
        } catch (Exception $exception) {
            print_r($exception);
        }
    });
    $router->get('/contact', function () use ($Contact) {
        try {
            $Contact->show('contact');
        } catch (Exception $exception) {
            print_r($exception);
        }
    });
    $router->get('/about', function () use ($About) {
        try {
            $About->show('about');
        } catch (Exception $exception) {
            print_r($exception);
        }
    });
    global $Projects;
    $urlProjects = $Projects->projects();
    $router->get($urlProjects, function () use ($Projects, $urlProjects) {
        try {
            $page = $_SERVER["SERVER_NAME"] === "localhost" ? str_replace("/" . $_SERVER["HOST_NAMES_SERVER"] . "/", "", $_SERVER["REQUEST_URI"]) : $_SERVER["REQUEST_URI"];
            $Projects->projectShow($page);
        } catch (Exception $exception) {
            print_r($exception);
        }
    });
});
$router->prefix('/admin', function ($router) {
    global $DashBoard;
    global $Auth;
    global $Blank;
    global $Users;
    global $Settings;
    global $References;
    $router->get(['/', '', '/index'], function () use ($DashBoard) {
        try {
            $DashBoard->show(['/', ''], "/admin");
        } catch (Exception $exception) {
            print_r($exception);
        }
    });
    $router->get(["/users","/profile/{username}"],function ($username=null) use ($Users) {
        try {
            if (is_null($username)) {
                $Users->usersShow("/users", "/admin");
            } else {
                $Users->profileShow("/profile","/admin",$username);
            }
        } catch (Exception $exception) {
            print_r($exception);
        }
    });
    $router->post("/profile",function () use ($Users) {
        try {
            $Users->edit(postOrJsonControl());
        } catch (Exception $exception) {
            print_r($exception);
        }
    });
    $router->get("/settings", function () use ($Settings) {
        try {
            $Settings->show("/settings", "/admin");
        } catch (Exception $exception) {
            print_r($exception);
        }
    });
    $router->post("/settings", function () use ($Settings) {
        try {
            $Settings->edit(postOrJsonControl());
        } catch (Exception $exception) {
            print_r($exception);
        }
    });
    $router->get("/references", function () use ($References) {
        try {
            $References->show("/references", "/admin");
        } catch (Exception $exception) {
            print_r($exception);
        }
    });
    $router->post("/reference", function () use ($References) {
        try {
            $add = $References->refAdd(postOrJsonControl(), $_FILES);
            echo json_encode($add);
        } catch (Exception $exception) {
            print_r($exception);
        }
        exit();
    });

    $router->post("/setting/logo", function () use ($Settings) {
        try {
            $Settings->settingFileUploaded(postOrJsonControl(),$_FILES,"logo","setting/logo");
        } catch (Exception $exception) {
            print_r($exception);
        }
    });
    $router->post("/setting/favicon", function () use ($Settings) {
        try {
            $Settings->settingFileUploaded(postOrJsonControl(),$_FILES,"favicon","setting/favicon");
        } catch (Exception $exception) {
            print_r($exception);
        }
    });
    $router->get('/blank', function () use ($Blank) {
        try {
            $Blank->show('/blank', "/admin");
        } catch (Exception $exception) {
            print_r($exception);
        }
    });
    $router->get('/login', function () use ($Auth) {
        try {
            $Auth->show('/login', "/admin");
        } catch (Exception $exception) {
            print_r($exception);
        }
    });
    $router->post('/login', function () use ($Auth) {
        try {
            $Auth->login(postOrJsonControl());
        } catch (Exception $exception) {
           print_r($exception);
        }
    });

    $router->get('/logout', function () use ($Auth) {
        $Auth->logout();
    });

});

$router->prefix('/api', function($router) {

    $router->post('/LangChanges', function () {
        $data = postOrJsonControl();
        $lang = $data->lang;
        $_SESSION["lang"] = $lang;
        echo json_encode($data);
        exit();
    });
    global $DashBoard;
    $router->post('/Countries', function () use ($DashBoard){
      $DashBoard->countriesChanged(postOrJsonControl());
    });
    $router->post('/ThemeMode', function () {
        $data = postOrJsonControl();
        $themeMode = $data->themeMode;
        $_SESSION["theme_mode"] = $themeMode == "dark" ? "theme-dark" : "";
        echo json_encode($data);
        exit();
    });
    $router->post('/ThemeColor', function () {
        $data = postOrJsonControl();
        $themeColor = $data->themeColor;
        $themeColor = match ($themeColor) {
            "purple" => "theme-purple",
            "cyan" => "theme-cyan",
            "green" => "theme-green",
            "orange" => "theme-orange",
            "blush" => "theme-blush",
            default => "theme-blue",
        };
        $_SESSION["theme_color"] = $themeColor;
        echo json_encode($data);
        exit();
    });
    $router->post('/Users', [UserController::class,"users"]);
    global $Users;
    $router->post('/UserCreate', function () use ($Users) {
        try {
            $Users->userCreate(postOrJsonControl());
        } catch (Exception $exception) {
            print_r($exception);
        }
    });
    $router->post('/PasswordConfirm', function () use ($Users) {
        $Users->passwordConfirm(postOrJsonControl());
    });
    global $Settings;
    $router->post(["/dropzone-logo", "/dropzone-fav"], function () use ($Settings) {
        echo json_encode(["path" => $Settings->settingFileQuery(postOrJsonControl())]);
        exit();
    });
    global $References;
    $router->post("/ReferenceTranslate", function () use ($References) {
        echo json_encode($References->refTranslate(postOrJsonControl()));
        exit();
    });

    $router->post('/References', [ReferencesController::class,"references"]);

    $router->post("/SendMail", function () use ($Settings) {
        try {
            $name = htmlspecialchars($_POST["name"]);
            $email = htmlspecialchars($_POST["email"]);
            $subject = htmlspecialchars($_POST["subject"]);
            $message = htmlspecialchars($_POST["message"]);
            $Mail = new MailConfigure();
// extra kullanım örneği
//            $mailer = [
//                "setFrom" => [
//                    "mail" => "hakan.gasaray@gmail.com",
//                    "name" => "Hakan Gasaray"
//                ],
//                "addAddress" => [
//                    [
//                        "mail" => "hakan.gasaray@gmail.com",
//                        "name" => "Hakan Gasaray"
//                    ],
//                    [
//                        "mail" => "hakan.hizmet.54.gs@gmail.com",
//                        "name" => "Korkmaz"
//                    ]
//                ],
//                "addReplyTo" => [
//                    [
//                        "mail" => "hakan.gasaray@gmail.com",
//                        "name" => "Hakan Gasaray"
//                     ]
//                ],
//                "addCC" => [
//                    [
//                        "mail" => "hakan.gasaray@gmail.com",
//                        "name" => "Hakan Gasaray"
//                    ],
//                    [
//                        "mail" => "hakan.hizmet.54.gs@gmail.com",
//                        "name" => "Korkmaz"
//                    ]
//                ],
//                "addBCC" => [
//                    [
//                        "mail" => "hakan.gasaray@gmail.com",
//                        "name" => "Hakan Gasaray"
//                    ]
//                ],
//                "addAttachment" => [
//                    [
//                        "path" => "path/to/file",
//                        "name" => "",
//                        "encoding" => "base64",
//                        "type" => "",
//                        "disposition" => "attachment"
//                    ]
//                ],
//                "isHTML" => true,
//                "Subject" =>"Test-".time(),
//                "Body" =>"<p>
//                        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquam cumque delectus dolor error
//                        eveniet fugit harum in incidunt ipsa iure iusto nostrum, possimus quas quidem repellendus
//                        suscipit ullam unde veritatis!
//                        </p>",
//                "AltBody" => "Alt yazım"
//            ];
            $mailer = [
                "setFrom" => [
                    "mail" => "_mainaccount@aysunberilkaraman.com",
                    "name" => "aysunberilkaraman"
                ],
                "addAddress" => [
                    [
                        "mail" => $email,
                        "name" => $name
                    ]
                ], "isHTML" => true, "Subject" => $subject, "Body" => "<p>
$message
<hr>
Eposta Adresi: $email
<br>
Adı Soyadı: $name
</p>"];
            if ($Mail->mailSender($mailer)) {
                if ($_SESSION["lang"] === "tr") {
                    $messages = "Form başarıyla gönderildi";
                } else {
                    $messages = "Form submitted successfully";

                }
                $result = ["conclusion" => "success", "message" => $messages];

            } else {
                if ($_SESSION["lang"] === "tr") {
                    $messages = "Form gönderilemedi beklenmedik bir problem oluştu";
                } else {
                    $messages = "The form could not be submitted, an unexpected problem occurred.";
                }
                $result = ["conclusion" => "error", "message" => $messages];

            }
            echo json_encode($result);

        } catch (Exception $exception) {
            print_r($exception);
            exit();
        }
        exit();
    });

});
$router->dispatch();
