<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Http\Requests\Web\ForgetRequest;
use App\Http\Requests\Web\LoginRequest;
use App\Http\Requests\Web\RegistCompanyRequest;
use App\Http\Requests\Web\RegistRequest;
use App\Http\Requests\Web\ResetRequest;
use App\Http\Requests\Web\VerifyRequest;
use App\Models\Country;
use App\Models\Page;
use App\Models\User;
use App\Models\UserDescription;
use App\Models\UserLink;
use App\Models\UserPhoto;
use App\Services\Auth\Login\LoginEmailPhoneService;
use App\Services\Auth\Login\LoginEmailService;
use App\Services\Auth\Login\LoginPhoneService;
use App\Services\Auth\Login\LoginService;
use App\Services\Auth\OTP\OTPService;
use App\Services\Response\ResponseService;
use App\Services\Upload\ImageService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Illuminate\View\View;

class AuthController extends Controller
{

    private $view = 'web.pages.auth.';

    public function login() : View
    {
        $title = __('web.login');
        $action = route('login_check');
        $page = Page::withDescription(13)->first();
        $target = __('web.'.settings('login_status'));
        $forget_action = route('forgetpassword');
        $regist_action = route('regist');
        return view($this->view . 'login', get_defined_vars());
    }

    public function check(LoginRequest $request) : JsonResponse
    {
        $status = settings('login_status');

        switch ($status)
        {
            case 'email':
                $login = new LoginEmailService();
                break;
            case 'phone':
                $login = new LoginPhoneService();
                break;
            default:
                $login = new LoginEmailPhoneService();
                break;
        }
        $login = new LoginService($login);
        $response = $login->authLogin($request->all());

        return ResponseService::response($response);
    }

    /**
     * view of register
     * @return view
     */
    public function regist(): View
    {
        $title = __('web.regist');
        $action = route('registing');
        $login_action = route('login');
        $countries = Country::withDescription()->cursor();
        $page = Page::withDescription(17)->first();
        return view($this->view . 'regist', get_defined_vars());
    }

    /**
     * Function for Web login to the cms.
     *
     * @param RegistRequest $request
     * @return RedirectResponse
     * @throws Exception
     */
    public function registing(RegistRequest $request): JsonResponse
    {
        $content = $request->all();
        $content['role'] = 'user';
        $content['photo'] = 'user.png';
        $content['currency_id'] = $request->country_id;
        $user = User::create($content);
        $user->update(['password'=>bcrypt($request->password)]);
        if($request->hasFile('photo'))
        {
            $image = ImageService::uploadImage($request->photo);
            $user->update(['photo'=>$image]);
        }
        $content['target'] = $user->email;
        $login = new LoginService(new LoginEmailService());
        $response = $login->authLogin($content);
        return ResponseService::response($response);
    }



    public function registCompany(): View
    {
        $title = __('web.regist_company');
        $action = route('registing.company');
        $login_action = route('login');
        $page = Page::withDescription(17)->first();
        return view($this->view . 'regist_company', get_defined_vars());
    }

    /**
     * Function for Web login to the cms.
     *
     * @param RegistRequest $request
     * @return RedirectResponse
     * @throws Exception
     */
    public function registingCompany(RegistCompanyRequest $request): JsonResponse
    {
        $content = $request->all();
        $content['role'] = 'company';
        $content['photo'] = 'user.png';
        $content['active_account'] = 'inactive';
        $content['currency_id'] = 1;
        $user = User::create($content);
        $user->update(['password'=>bcrypt($request->password)]);

        $certificate_commercial = ImageService::uploadImage($request->certificate_commercial);
        $tax_certificate = ImageService::uploadImage($request->tax_certificate);
        $company_exhibition = ImageService::uploadImage($request->company_exhibition);
        $company_showroom = ImageService::uploadImage($request->company_showroom);
        $user->update([
            'certificate_commercial' => $certificate_commercial,
            'tax_certificate' => $tax_certificate,
            'company_exhibition' => $company_exhibition,
            'company_showroom' => $company_showroom
        ]);

        if(isset($request->photos))
        {
            foreach ($request->photos as $photo)
            {
                $image = ImageService::uploadImage($photo);
                UserPhoto::create([
                    'photo'=>$image,
                    'user_id'=>$user->id
                ]);
            }
        }
        if(isset($request->links))
        {
            foreach ($request->links as $link)
            {
                UserLink::create([
                    'link'=>$link,
                    'user_id'=>$user->id
                ]);
            }
        }
        foreach (languages() as $lang)
        {
            $data=[
                'user_id'=> $user->id,
                'language_id'=> $lang->id,
                'name'=> $request['name_'.$lang->local],
                'purchasing'=> $request['purchasing_'.$lang->local],
            ];
            UserDescription::create($data);
        }


        $content['target'] = $user->email;
        $login = new LoginService(new LoginEmailService());
        $response = $login->authLogin($content);
        $response['data'] = [];
        $response['data']['url'] = route('profile');
        $response['data']['request_id'] = $user->id;
        return ResponseService::response($response);
    }

    /**
     * Web logout.
     * @return RedirectResponse
     */
    public function logout(): RedirectResponse
    {
        Auth::logout();
        return redirect(route('login'));
    }



    /**
     * forgetpassword
     *
     * @return view
     */
    public function forgetpassword(): View
    {
        $title = __('web.forgetpassword');
        $action = route('forgettingpassword');
        $login_action = route('login');
        $target = __('web.'.settings('resetpassword_status'));
        $page = Page::withDescription()->find(14);

        return view($this->view.'forgetpassword',get_defined_vars());
    }

    /**
     * Verify Email Forget Password
     *
     * @param Request $request
     * @return view
     */
    public function forgettingpassword(ForgetRequest $request): JsonResponse
    {
        $response =
            [
                'status' => 200,
                'data'=> route('verify').'?target='.$request->target,
                'message' => '',
            ];
        return ResponseService::response($response);
    }

    public function verify(ForgetRequest $request)
    {
        $url = request()->url();
        $title = __('web.verify');
        $page = Page::withDescription()->find(15);

        $target = $request->target;
        $type = is_numeric($target) ? 'phone' : 'email';
        $user = User::where($type,$target)->first();
        Session::put('target',$target);
        if(!$user)
        {
            return redirect(route('forgetpassword'))->with('error',__('web.checkinput'));
        }
        $content =
            [
                'target'=>$target,
                'type'=>$type
            ];
        $send_code = OTPService::SendOTP($content);
        $status = $send_code['status'];
        if($status != 200)
        {
            session()->flash('error',$send_code['message']);
            return redirect(route('forgetpassword'))->with('error',$send_code['message']);
        }

        $action = route('verifying');

        return view($this->view.'verify',get_defined_vars());
    }

    public function verifying(VerifyRequest $request): JsonResponse
    {
        $target = Session::get('target');

        if(!$target)
        {
            $error = __('web.error_resend');
            return ResponseService::responseFail([$error]);
        }

        $type = is_numeric($target) ? 'phone' : 'email';
        $content =
            [
                'target'=>$target,
                'type'=>$type,
                'code'=>$request->code
            ];
        $send_code = OTPService::CheckOTP($content);

        return ResponseService::response($send_code);
    }

    /**
     * reset password
     *
     * @param Request $request
     * @return view
     */
    public function resetPassword(Request $request)
    {
        $target = Session::get('target');

        if(!$target)
        {
            return redirect(route('forgetpassword'))->with('error',__('web.email_req'));
        }
        $page = Page::withDescription(16)->first();
        $title = __('web.resetpassword');
        $action = route('resetting');
        return view($this->view.'resetpassword',get_defined_vars());
    }

    /**
     * reseting password
     *
     * @param Request $request
     * @return view
     */
    public function resetting(ResetRequest $request): JsonResponse
    {
        $target = Session::get('target');
        $type = is_numeric($target) ? 'phone' : 'email';

        $user = User::where($type,$target)->first();

        Session::forget('target');

        $user->update(['password'=>bcrypt($request->password)]);

        $request->merge(['target'=>$user->email]);
        $login = new LoginService(new LoginEmailService());
        $response = $login->authLogin($request->all());
        return ResponseService::response($response);
    }

}
