<?php

namespace App\Livewire\Frontend;

use App\Models\Log;
use App\Models\ZEmail;
use Carbon\Carbon;
use Livewire\Component;

class Action extends Component
{
    public $username, $email, $emails, $domain, $domains, $action, $initial;
    public function mount() {
        $this->domains = json_decode(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($this->username) < json_decode(config('app.settings.configuration_settings'))->custom_username_length_min || strlen($this->username) > json_decode(config('app.settings.configuration_settings'))->custom_username_length_max) {
            return $this->showAlert('error', __('Username length cannot be less than') . ' ' . json_decode(config('app.settings.configuration_settings'))->custom_username_length_min . ' ' . __('and greater than') . ' ' . json_decode(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(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(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 redirect()->route('mailbox');

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

        return redirect()->route('mailbox');
    }

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

    public function deleteEmail()
    {
        return redirect()->route('delete', ['email' => $this->email]);
    }

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

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

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

    private function checkDomainInUsername() {
        $parts = explode('@', $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('@', $this->email);
        if (isset($data[1])) {
            $domain = $data[1];
            $domains = json_decode(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(config('app.settings.configuration_settings'))->after_last_email_delete == 'redirect_to_homepage') {
                    redirect()->route('home');
                } else {
                    redirect()->route('mailbox');
                }
            }
        }
    }
    public function render() {
        return view('livewire.frontend.action');
    }
}
