<?php

namespace App\Livewire\Frontend;

use Illuminate\Routing\Redirector;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Date;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use App\Models\Log;
use App\Models\ZEmail;
use Livewire\Component;

class Action extends Component
{
    public $username;

    public $email;

    public $emails;

    public $domain;

    public $domains;

    public $action;

    public $initial;

    public function mount(): void
    {
        $this->domains = json_decode((string) config('app.settings.configuration_settings'))->domains ?? [];
        $this->email = ZEmail::getEmail();
        $this->emails = ZEmail::getEmails();
        $this->validateDomainInEmail();
    }

    public function create()
    {
        if (! $this->username) {
            return $this->showAlert('error', __('Please enter Username'));
        }
        $this->checkDomainInUsername();
        if (strlen((string) $this->username) < json_decode((string) config('app.settings.configuration_settings'))->custom_username_length_min || strlen((string) $this->username) > json_decode((string) config('app.settings.configuration_settings'))->custom_username_length_max) {
            return $this->showAlert('error', __('Username length cannot be less than').' '.json_decode((string) config('app.settings.configuration_settings'))->custom_username_length_min.' '.__('and greater than').' '.json_decode((string) config('app.settings.configuration_settings'))->custom_username_length_max);
        }
        if (! $this->domain) {
            return $this->showAlert('error', __('Please Select a Domain'));
        }
        if (in_array($this->username, json_decode((string) config('app.settings.configuration_settings'))->forbidden_ids)) {
            return $this->showAlert('error', __('Username not allowed'));
        }
        if (! $this->checkEmailLimit()) {
            return $this->showAlert('error', __('You have reached daily limit of MAX ').json_decode((string) config('app.settings.configuration_settings'))->email_limit.__(' temp mail'));
        }
        if (! $this->checkUsedEmail()) {
            return $this->showAlert('error', __('Sorry! That email is already been used by someone else. Please try a different email address.'));
        }

        $this->email = ZEmail::createCustomEmail($this->username, $this->domain);

        return to_route('mailbox');

    }

    public function random()
    {
        if (! $this->checkEmailLimit()) {
            return $this->showAlert('error', __('You have reached daily limit of maximum ').json_decode((string) config('app.settings.configuration_settings'))->email_limit.__(' temp mail addresses.'));
        }
        $this->email = ZEmail::generateRandomEmail();

        return to_route('mailbox');
    }

    public function gmail()
    {
        if (! $this->checkEmailLimit()) {
            return $this->showAlert('error', __('You have reached daily limit of maximum ').json_decode((string) config('app.settings.configuration_settings'))->email_limit.__(' temp mail addresses.'));
        }
        $this->email = ZEmail::generateRandomGmail();

        return to_route('mailbox');
    }

    public function outlook()
    {
        if (! $this->checkEmailLimit()) {
            return $this->showAlert('error', __('You have reached daily limit of maximum ').json_decode((string) config('app.settings.configuration_settings'))->email_limit.__(' temp mail addresses.'));
        }
        $this->email = ZEmail::generateRandomOutlook();

        return to_route('mailbox');
    }

    public function deleteEmail(): Redirector|RedirectResponse
    {
        return to_route('delete', ['email' => $this->email]);
    }

    private function showAlert(string $type, $message): void
    {
        $check = json_decode((string) config('app.settings.configuration_settings'))->email_limit;
        if (str_contains((string) $message, (string) $check)) {
            $this->dispatch('promotePremium');
        }
        $this->dispatch('showAlert', ['type' => $type, 'message' => $message]);
    }

    private function checkEmailLimit(): bool
    {
        $logs = Log::query()->select('ip', 'email')->where('ip', request()->ip())->where('created_at', '>', Date::now()->subDay())->groupBy('email')->groupBy('ip')->get();
        return count($logs) < json_decode((string) config('app.settings.configuration_settings'))->email_limit;
    }

    private function checkUsedEmail(): bool
    {
        if (json_decode((string) config('app.settings.configuration_settings'))->disable_used_email) {
            $check = Log::query()->where('email', $this->user.'@'.$this->domain)->where('ip', '<>', request()->ip())->count();
            return $check <= 0;
        }

        return true;
    }

    private function checkDomainInUsername(): void
    {
        $parts = explode('@', (string) $this->username);
        if (isset($parts[1])) {
            if (in_array($parts[1], $this->domains)) {
                $this->domain = $parts[1];
            }
            $this->username = $parts[0];
        }
    }

    private function validateDomainInEmail(): void
    {
        $data = explode('@', (string) $this->email);
        if (isset($data[1])) {
            $domain = $data[1];
            $domains = json_decode((string) config('app.settings.configuration_settings'))->domains ?? [];
            if (! in_array($domain, $domains)) {
                $key = array_search($this->email, $this->emails);
                ZEmail::removeEmail($this->email);
                if ($key == 0 && count($this->emails) === 1 && json_decode((string) config('app.settings.configuration_settings'))->after_last_email_delete == 'redirect_to_homepage') {
                    to_route('home');
                } else {
                    to_route('mailbox');
                }
            }
        }
    }

    public function render(): Factory|View
    {
        return view('livewire.frontend.action');
    }
}
