<?php

namespace App\Modules\User\Application\FindOrCreate;

use App\Mail\c_Mail_User;
use App\Modules\Shared\Application\SelectHandler;
use App\Modules\Shared\Domain\DateEnd;
use App\Modules\Shared\Domain\DateStart;
use App\Modules\Shared\Exceptions\ActionRequestException;
use App\Modules\User\Domain\IdUser;
use App\Modules\User\Domain\UserEmail;
use App\Modules\User\Domain\UserLastName;
use App\Modules\User\Domain\UserName;
use App\Modules\User\Domain\UserPhone;
use App\Modules\User\Domain\UserRepository;
use App\Modules\UserCountry\Domain\IdUserCountry;
use App\Providers\BookingMailSender;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Throwable;

final class UserFindOrCreator
{
    public function __construct(private UserRepository $repository) {}

    public function __invoke(
        IdUser $id,
        UserName $name,
        UserLastName $lastName,
        UserEmail $email,
        UserPhone $phone,
        IdUserCountry $idUserCountry,
    ) {
        if ($id->value() !== 0) {
            return $id;
        }
        try {
            $this->repository->clientUserValidate($email);
        } catch (ActionRequestException $action) {
            if ($action->getResponse()->Response_Id !== null) {
                return $action->getResponse()->Response_Id;
            }
        } catch (Throwable $e) {
        }

        $inserted = $this->repository
            ->clientUserInsert($name, $lastName, $email, $phone, $idUserCountry);

        $this->sendUserEmail($email, $inserted[0]->Response_Password);
        return $inserted[0]->Response_Id;
    }

    public function sendUserEmail($User_Email, $User_Password)
    {
        try {
            $variables = [
                "Lang" => 1,
                "User" => $User_Email,
                "Password" => $User_Password,
                'ResourcesUrl' => BookingMailSender::getResourcesUrl()[0]->Credential_Value,
                'WebUrl' => BookingMailSender::getWebUrl()[0]->Credential_Value
            ];

            $oMail_User = new c_Mail_User;
            $oMail_User->Type = 1;
            $oMail_User->Subject = "Your Account Password";
            $oMail_User->Content = $variables;
            if (config('var.SEND_AUTO_ACCESSDATA')) {
                Mail::to($User_Email)->send($oMail_User);
            } else {
                Mail::to(config('var.SEND_EMAIL_ACCESSDATA'))->send($oMail_User);
            }
        } catch (Throwable $ex) {
        }
    }
}
