<?php

namespace App\Livewire\Dashboard\Mailbox;

use Illuminate\Support\Facades\Session;
use Illuminate\Routing\Redirector;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Date;
use App\ColorPicker;
use App\Models\Log;
use App\Models\Premium;
use App\Models\PremiumEmail;
use App\Models\UsageLog;
use App\Models\ZEmail;
use Exception;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;

class Inbox extends Component
{
    use ColorPicker;

    public $messages = [];

    public $deleted = [];

    public $error = '';

    public $email;

    public $initial = false;

    public $type;

    public $overflow = false;

    public $messageId;

    public $list = false;

    public $emails;

    public $mailboxHistory;

    public $emailsHistory;

    public $username;

    public $domain;

    public $domains;

    public $action;

    public $email_limit = 20;

    public bool $premium = true;

    private $isSubscribed;

    protected $listeners = ['updateEmail' => 'syncEmail', 'getEmail' => 'generateEmail', 'fetchMessages' => 'fetch', 'setMessageId' => 'setMessageId'];

    public function mount(): void
    {
        $this->premium = Session::get('isInboxTypePremium', true);

        if ($this->premium) {
            $this->domains = json_decode((string) config('app.settings.configuration_settings'))->premium_domains ?? [];
            $this->email = Premium::getEmail();
            $this->emails = Premium::getEmails();
            $this->initial = false;
            $this->checkMultipleEmails();
            $this->validateDomainInEmail();
        } else {
            $this->domains = json_decode((string) config('app.settings.configuration_settings'))->domains ?? [];
            $this->email = ZEmail::getEmail();
            $this->emails = ZEmail::getEmails();
            $this->initial = false;
            $this->checkMultipleEmails();
            $this->validateDomainInEmail();
        }

        $this->emailsHistory = array_reverse(PremiumEmail::parseEmail(\auth()->user()->id)['data']) ?? [];

        $subscriptionCheck = auth()->user()->subscribedToProduct(config('app.plans')[0]['product_id']);
        Session::put('isSubscribed', $subscriptionCheck);
        if ($subscriptionCheck) {
            try {
                $result = auth()->user()->subscriptions()->where(['stripe_status' => 'active'])->orderByDesc('updated_at')->first();
                $userPriceID = $result['items'][0]['stripe_price'];

                $mailboxLimit = $this->email_limit;
                foreach (config('app.plans') as $plan) {
                    if ($plan['pricing_id'] === $userPriceID) {
                        $mailboxLimit = $plan['mailbox_limit'];
                        break;
                    }
                }
                $this->email_limit = $mailboxLimit;

            } catch (Exception $e) {
                \Illuminate\Support\Facades\Log::error($e->getMessage());
            }
        }

        if ($this->premium) {
            $mailboxHistory = UsageLog::query()->where(['user_id' => auth()->user()->id])->first();
            $this->mailboxHistory = $mailboxHistory->emails_created_history ?? [];
        } else {
            $this->mailboxHistory = ZEmail::getEmails() ?? [];
        }

    }

    private function checkMultipleEmails(): void
    {
        if (count($this->emails) === 0) {
            $this->emails = [$this->email];
        }
        $this->list = count($this->emails) > 1;
    }

    public function switchEmail($email)
    {
        try {
            if ($email != null) {
                $data = explode('@', (string) $email);
                if (isset($data[1])) {
                    $domain = $data[1];
                    if ($this->premium) {
                        $domains = json_decode((string) config('app.settings.configuration_settings'))->premium_domains ?? [];
                    } else {
                        $domains = json_decode((string) config('app.settings.configuration_settings'))->domains ?? [];
                    }
                    if (! in_array($domain, $domains)) {
                        return $this->showAlert('error', __('This mailbox can not be recovered.'));
                    }
                }
            }
        } catch (Exception $exception) {
            \Illuminate\Support\Facades\Log::error($exception->getMessage());
        }

        return to_route('switchP', ['email' => $email]);
    }

    public function syncEmail(): void
    {
        $this->email = Premium::getEmail();
        $this->emails = Premium::getEmails();
        if (count($this->emails) === 0) {
            $this->dispatch('getEmail');
        }
        $this->checkMultipleEmails();
        $this->dispatch('syncMailbox', $this->email);
        $this->dispatch('fetchMessages');
    }

    public function generateEmail(): void
    {
        if ($this->email == null) {
            Premium::generateRandomEmail();
        }
        $this->checkMultipleEmails();
        $this->dispatch('updateEmail');
    }

    /* Actions */
    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 ').$this->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.'));
        }
        if ($this->premium) {
            $this->email = Premium::createCustomEmail($this->username, $this->domain);
        } else {
            $this->email = ZEmail::createCustomEmail($this->username, $this->domain);
        }

        return to_route('dashboard.premium');

    }

    public function random()
    {

        if (! $this->checkEmailLimit()) {
            return $this->showAlert('error', __('You have reached daily limit of maximum ').$this->email_limit.__(' temp mail addresses.'));
        }
        $this->email = $this->premium ? Premium::generateRandomEmail() : ZEmail::generateRandomEmail();

        return to_route('dashboard.premium');
    }

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

        return to_route('dashboard.premium');
    }

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

        return to_route('dashboard.premium');
    }

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

    private function showAlert(string $type, $message): void
    {
        $this->dispatch('showAlert', ['type' => $type, 'message' => $message]);
    }

    private function checkEmailLimit(): bool
    {
        $logs = Log::query()->select('ip', 'email')->where('user_id', auth()->user()->id)->where('created_at', '>', Date::now()->subDay())->groupBy('email')->groupBy('ip')->get();
        return count($logs) < $this->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
    {
        try {
            if ($this->email != null) {
                $data = explode('@', (string) $this->email);
                if (isset($data[1])) {
                    $domain = $data[1];
                    if ($this->premium) {
                        $domains = json_decode((string) config('app.settings.configuration_settings'))->premium_domains ?? [];
                    } else {
                        $domains = json_decode((string) config('app.settings.configuration_settings'))->domains ?? [];
                    }
                    if (! in_array($domain, $domains)) {
                        $key = array_search($this->email, $this->emails);
                        if ($this->premium) {
                            Premium::removeEmail($this->email);
                        } else {
                            ZEmail::removeEmail($this->email);
                        }
                        to_route('dashboard.premium');
                    }
                }
            }
        } catch (Exception $exception) {
            \Illuminate\Support\Facades\Log::error($exception->getMessage());
        }
    }

    /* Mailbox */

    public function fetch(): void
    {
        try {
            $count = count($this->messages);
            if ($count > 0) {
                $this->messages = [];
            }
            $responses = [];
            if ($this->premium) {
                if (config('app.beta_feature') || ! json_decode((string) config('app.settings.imap_settings'))->premium_cc_check) {
                    $responses = [
                        'to' => Premium::getMessages($this->email, 'to', $this->deleted),
                        'cc' => [
                            'data' => [],
                            'notifications' => [],
                        ],
                    ];
                } else {
                    $responses = [
                        'to' => Premium::getMessages($this->email, 'to', $this->deleted),
                        'cc' => Premium::getMessages($this->email, 'cc', $this->deleted),
                    ];
                }
            } elseif (config('app.beta_feature') || ! json_decode((string) config('app.settings.imap_settings'))->cc_check) {
                $responses = [
                    'to' => ZEmail::getMessages($this->email, 'to', $this->deleted),
                    'cc' => [
                        'data' => [],
                        'notifications' => [],
                    ],
                ];
            } else {
                $responses = [
                    'to' => ZEmail::getMessages($this->email, 'to', $this->deleted),
                    'cc' => ZEmail::getMessages($this->email, 'cc', $this->deleted),
                ];
            }

            $this->deleted = [];
            $this->messages = array_merge($responses['to']['data'], $responses['cc']['data']);
            $notifications = array_merge($responses['to']['notifications'], $responses['cc']['notifications']);

            if (count($notifications)) {
                if (! $this->overflow && count($this->messages) === $count) {
                    $this->overflow = true;
                }
            } else {
                $this->overflow = false;
            }

            foreach ($notifications as $notification) {
                $this->dispatch('showNewMailNotification', $notification);
            }
            Premium::incrementMessagesStats(count($notifications));

            if ($this->email != null && count($this->messages) > 0) {
                foreach ($this->messages as $message) {
                    PremiumEmail::createEmail($message, $this->email);
                }
            }

            $this->emailsHistory = array_reverse(PremiumEmail::parseEmail(\auth()->user()->id)['data']) ?? [];

        } catch (Exception $e) {
            if (Auth::check() && Auth::user()->level == 9) {
                $this->error = $e->getMessage();
            } else {
                $this->error = 'Not able to connect to Mail Server';
            }
        }
        $this->dispatch('stopLoader');
        $this->initial = true;
    }

    public function delete(string $messageId): void
    {

        try {
            $this->deleted[] = $messageId;
            foreach ($this->messages as $key => $message) {
                if ($message['id'] == $messageId) {
                    if ($this->premium) {
                        $directory = public_path('tmp/premium/attachments/').$messageId;
                    } else {
                        $directory = public_path('tmp/attachments/').$messageId;
                    }
                    $this->rrmdir($directory);
                    unset($this->messages[$key]);
                }
            }

        } catch (
            Exception $exception
        ) {
            \Illuminate\Support\Facades\Log::error($exception->getMessage());
        }

    }

    public function toggleMode(): void
    {
        $this->premium = ! $this->premium;
        Session::put('isInboxTypePremium', $this->premium);
        if ($this->premium) {
            $this->domains = json_decode((string) config('app.settings.configuration_settings'))->premium_domains ?? [];
            $this->email = Premium::getEmail();
            $this->emails = Premium::getEmails();
            $this->initial = false;
            $this->checkMultipleEmails();
            $this->validateDomainInEmail();
            $mailboxHistory = UsageLog::query()->where(['user_id' => auth()->user()->id])->first();
            $this->mailboxHistory = $mailboxHistory->emails_created_history ?? [];
            $this->messages = [];

        } else {
            $this->domains = json_decode((string) config('app.settings.configuration_settings'))->domains ?? [];
            $this->email = ZEmail::getEmail();
            $this->emails = ZEmail::getEmails();
            $this->initial = false;
            $this->checkMultipleEmails();
            $this->validateDomainInEmail();
            $this->mailboxHistory = array_reverse(ZEmail::getEmails()) ?? [];
            $this->messages = [];
        }
    }

    public function render()
    {
        if (Session::get('isSubscribed')) {
            return view('livewire.dashboard.mailbox.inbox')->layout('components.layouts.dashboard');
        }
        return view('livewire.dashboard.not-subscribed')->layout('components.layouts.dashboard');
    }

    private function rrmdir(string $dir): void
    {
        if (is_dir($dir)) {
            $objects = scandir($dir);
            foreach ($objects as $object) {
                if ($object !== '.' && $object !== '..') {
                    if (is_dir($dir.DIRECTORY_SEPARATOR.$object) && ! is_link($dir.'/'.$object)) {
                        $this->rrmdir($dir.DIRECTORY_SEPARATOR.$object);
                    } else {
                        unlink($dir.DIRECTORY_SEPARATOR.$object);
                    }
                }
            }
            rmdir($dir);
        }
    }
}
