<?php

namespace Korkz\Demirteknoloji\Controllers\Admin;

use Exception;
use Korkz\Demirteknoloji\Models\Admin\DashBoardModel;
use Korkz\Demirteknoloji\Router\View;
use Korkz\Demirteknoloji\traits\AuthControl;
use Korkz\Demirteknoloji\traits\Lang;
use Korkz\Demirteknoloji\traits\Settings;
use Korkz\Demirteknoloji\traits\TokenConfig;

class DashBoardController extends DashBoardModel
{
    use AuthControl;
    use TokenConfig;
    use Lang;
    use Settings;

    /**
     * @throws Exception
     */
    public function show(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();
        $settings=$this->settingData($lang);
        print $this->views(["baseUrl" => $baseUrl, "tittle" => " Demirteknoloji yönetim paneli", "token" => $this->tokenCreate(), "lang" => $this->getLang(), "active" => "index", "themeMode" => $_SESSION["theme_mode"] ?? "", "themeColor" => $_SESSION["theme_color"] ?? "theme-blue", "data" => ["user" => $user, "settings" => $settings, "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">
                ', "script" => '
                <!-- 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>
                <script src="assets/admin/plugins/notiflix/dist/notiflix-confirm-aio-3.2.6.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/index", ["header" => "admin/layout/header", "footer" => "admin/layout/footer"]);
        $content = ob_get_clean();
        return $this->langViews("admin", "index", $content, "$lang");
    }

    public function countriesChanged($request): void
    {
        $process = $request->process;
        $code = $request->code;
        $result = match ($process) {
            "add" => $this->countriesAdd($code),
            "remove" => $this->countriesRemove($code),
            default => ""
        };
        echo json_encode([$result]);
    }

    private function countriesAdd($code): string
    {
        // JSON dosyasının yolunu belirleyin
        $countriesPath = 'countries.json';
        if (file_exists($countriesPath)) {
            // Varolan JSON dosyasını okuyun
            $countriesData = json_decode(file_get_contents($countriesPath), true);
            // Yeni veriler
            $newCountries = ["$code" => "#253267"];
            // Mevcut verilere yeni verileri ekleyin
            foreach ($countriesData as &$country) {
                $country["values"] = array_merge($country["values"], $newCountries);
            }
            // Güncellenmiş JSON verisini oluşturun
            $updateCountries = json_encode($countriesData, JSON_PRETTY_PRINT);
            // JSON dosyasına veriyi kaydedin
            file_put_contents($countriesPath, $updateCountries);
        } else {
            $countriesData = [["values" => ["$code" => "#253267"]]];
            $jsonOutput = json_encode($countriesData, JSON_PRETTY_PRINT);
            $file = fopen('countries.json', 'w');
            fwrite($file, $jsonOutput);
            fclose($file);

        }
        return 'Yeni veriler başarıyla eklendi ve JSON dosyası güncellendi.';
    }

    private function countriesRemove($code): string
    {
        $jsonData = file_get_contents('countries.json');
        $data = json_decode($jsonData, true);
        $countryCode = $code;
        unset($data[0]['values'][$countryCode]);
        $jsonData = json_encode($data);
        file_put_contents('countries.json', $jsonData);
        return "Veri başarıyla güncellendi.";
    }


}