<?php

namespace App\Http\Controllers;

use Session;
use Illuminate\Routing\Redirector;
use Illuminate\Http\RedirectResponse;
use App\Models\Premium;
use App\Models\ZEmail;

class AppController extends Controller
{
    public function mailbox($email = null)
    {
        if ($email) {
            $validatedData = validator(['email' => $email], [
                'email' => 'required|email',
            ])->validate();

            if (json_decode((string) config('app.settings.configuration_settings'))->enable_create_from_url) {
                ZEmail::createCustomEmailFull($email);
            }

            return to_route('mailbox');
        }
        if (! ZEmail::getEmail()) {
            return to_route('home');
        }
        if (json_decode((string) config('app.settings.configuration_settings'))->disable_mailbox_slug) {
            return to_route('home');
        }

        return $this->app();
    }

    public function app(): Redirector|RedirectResponse
    {
        return to_route('home');
    }

    public function switch($email): Redirector|RedirectResponse
    {
        ZEmail::setEmail($email);
        if (json_decode((string) config('app.settings.configuration_settings'))->disable_mailbox_slug) {
            return to_route('home');
        }

        return to_route('mailbox');
    }

    public function delete($email = null): Redirector|RedirectResponse
    {
        if ($email) {
            $emails = ZEmail::getEmails();
            ZEmail::removeEmail($email);

            return to_route('mailbox');
        }
        return to_route('home');
    }

    public function switchP($email): Redirector|RedirectResponse
    {
        if (\Illuminate\Support\Facades\Session::get('isInboxTypePremium')) {
            Premium::setEmailP($email);
        } else {
            ZEmail::setEmail($email);
        }
        if (json_decode((string) config('app.settings.configuration_settings'))->disable_mailbox_slug) {
            return to_route('dashboard');
        }

        return to_route('dashboard.premium');
    }

    public function deleteP($email = null): Redirector|RedirectResponse
    {
        if ($email) {
            if (\Illuminate\Support\Facades\Session::get('isInboxTypePremium')) {
                $emails = Premium::getEmails();
                Premium::removeEmail($email);
            } else {
                $emails = ZEmail::getEmails();
                ZEmail::removeEmail($email);
            }

            return to_route('dashboard.premium');
        }
        return to_route('dashboard');
    }

    public function locale($locale)
    {
        if (in_array($locale, config('app.locales'))) {
            session(['locale' => $locale]);

            return back();
        }
        abort(400);
    }
}
