<?php

namespace Korkz\Demirteknoloji\Controllers\Home;

use Exception;
use Korkz\Demirteknoloji\Models\Home\HomeModel;
use Korkz\Demirteknoloji\Router\View;
use Korkz\Demirteknoloji\traits\Lang;
use Korkz\Demirteknoloji\traits\TokenConfig;

class HomeController extends HomeModel
{
    use TokenConfig;
    use Lang;

    /**
     * @param $page
     * @return void
     * @throws Exception
     */
    public function show($page): void
    {
        $baseUrl = $this->baseUrl();
        $lang = $this->getLang();
        $references=$this->referencesData($lang);
        print $this->views(["baseUrl" => $baseUrl,"token" => $this->tokenCreate(), "lang" => $this->getLang(), "data" => [
            "settings" => $this->settingData($lang),
            "references" => $references,
            "head" => '
                <!-- vectorMap -->
                <link rel="stylesheet" href="assets/js/plugins/jvectormap-2.0.5/jquery-jvectormap-2.0.5.css">
                <link rel="stylesheet" href="assets/js/plugins/jvectormap-2.0.5/vector-map.css">
                ', "footer" => '
                <!-- vectorMap -->
                <script src="assets/js/plugins/jvectormap-2.0.5/jquery-jvectormap-2.0.5.min.js"></script>
                <script src="assets/js/plugins/jvectormap-2.0.5/jquery-jvectormap-world-mill-en.js"></script>
                ',
            "page" => $page]]);

    }

    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("home/index", ["header" => "home/layout/header", "footer" => "home/layout/footer"]);
        $content = ob_get_clean();
        return $this->langViews("home", "index", $content, $lang);
    }

    /**
     * @param string $langActive
     * @return array
     * @throws Exception
     */
    private function settingData(string $langActive): array
    {
        $settings = $this->getData("settings", ["*"], ["Lang" => $langActive]);
        if ($settings) {
            return $settings[0];
        } else {
            return [];
        }
    }

    /**
     * @param string $langActive
     * @return array
     * @throws Exception
     */
    private function referencesData(string $langActive): array
    {
        $references = $this->getData("dm_references", ["file_path,title,description"], ["Lang" => $langActive]);
        if ($references) {
            return $references;
        } else {
            return [];
        }
    }


}