<?php

namespace TechnoArtisan\FilamentCms\Http\Controllers;

use DateTime;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\Log;
use TechnoArtisan\FilamentCms\Enums\ContactRequest as ContactRequestEnum;
use TechnoArtisan\FilamentCms\FilamentCms;
use TechnoArtisan\FilamentCms\Models\ContactRequest;
use TechnoArtisan\FilamentCms\Models\ContactRequestError;
use Throwable;

class WebController extends Controller
{
    public const string DEFAULT_INDEX_HOME = '';

    protected array $variables = [
        'page' => self::DEFAULT_INDEX_HOME,
    ];
//
//    protected function prepareVariables(): void
//    {
//        foreach (WebsiteSettings::all() as $websiteSetting) {
//            $this->variables[$websiteSetting->identifier] = $websiteSetting->value;
//        }
//    }

    public function index(Request $request, string $locale, string $page = self::DEFAULT_INDEX_HOME) // '' = home/index
    {
        $pageKey = $this->getPageKeyFromLocalizedPage($page);

        $this->variables['currentLocale']    = $locale;
        $this->variables['pageKey']          = $pageKey;
        $this->variables['languageSwitcher'] = $this->getPreparedLanguageSelectorData($pageKey);

        $this->processUtd($request);

        return view(
            FilamentCms::getPackageName() . '::theme.' . FilamentCms::getTheme() . '.' . $pageKey,
            $this->variables
        );
    }

    public function contact(Request $request, string $locale)
    {
        $this->processUtd($request);

        $requestOptions = array_keys(fcms__('content-contact.request_options'));
        unset($requestOptions[0]); // remove empty from array

        $validatedData = $request->validate([
            'name'    => 'required|min:3|max:255',
            'email'   => 'required|email',
            'request' => 'required|in:' . implode(',', $requestOptions),
            'message' => 'required|min:10',
            'consent' => 'required',
        ]);

        $validatedData['request'] = ContactRequestEnum::from($validatedData['request']);

        try {
            ContactRequest::create(
                array_merge(
                    $validatedData,
                    [
                        'ip'           => $request->server()['HTTP_X_FORWARDED_FOR'] ?? $request->server()['HTTP_X_REAL_IP'],
                        'user_agent'   => $request->userAgent(),
                        'session_id'   => $request->session()->getId(),
                        'session_data' => $request->session()->get('utd'),
                    ]
                )
            );

            $result = 'success';
        } catch (Throwable $exception) {
            try {
                ContactRequestError::create([
                    'session_id'     => $request->session()->getId(),
                    'exception'      => [
                        'message' => $exception->getMessage(),
                        'code'    => $exception->getCode(),
                        'file'    => $exception->getFile(),
                        'trace'   => $exception->getTrace(),
                    ],
                    'request'        => [
                        'get'    => $request->query(),
                        'post'   => $request->post(),
                        'server' => $request->server(),
                    ],
                    'session'        => $request->session(),
                    'validated_data' => $validatedData ?? null,
                ]);
            } catch (Throwable $exception) {
                Log::error(
                    $exception->getMessage() . ' [' . $exception->getCode() . ']: ' . $exception->getFile()
                );
            }
            $result = 'error';
        }

        return back()->with($result, fcms__('content-contact.' . $result));
    }

    private function getPageKeyFromLocalizedPage(string $page): string
    {
        $localizedRoutes = array_flip(Lang::get(FilamentCms::getPackageName() . '::routes'));

        if (!isset($localizedRoutes[$page])) {
            abort(404);
        }

        return $localizedRoutes[$page];
    }

    private function getPreparedLanguageSelectorData(string $currentPageKey): array
    {
        $data = [];

        foreach (config('filament-cms.locale.available') as $locale) {
            $localizedRoutes = Lang::get(FilamentCms::getPackageName() . '::routes', [], $locale);
            $data[$locale]   = $currentPageKey; #$localizedRoutes[$currentPageKey];

        }

        return $data;
    }

    private function processUtd(Request $request): void
    {
        $key = 'utd';
        $utd = $request->session()->get($key);

        if (null === $utd) {
            $utd = [];
        }

        $utd[new DateTime()->format('Y-m-d H:i:s')] = $request->uri()->toStringable()->toString();

        $request->session()->put($key, $utd);
    }
}
