<?php

namespace App\Http\Controllers;

use App\Http\Requests\LoginRequest;
use App\Models\CreditreportProvider;
use App\Models\Permission;
use App\Models\Support;
use App\Models\User;
use App\Models\UserPackage;
use App\Models\VideoSetting;
use App\Utility\ActionLogCreate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\View;

class AuthController extends Controller
{
    private $message;
    private $code;
    private $data;
    public function __construct()
    {
        $this->middleware('guest')->except([
            'userLogout',
            'showRegisterForm',
            'register',
            'authRedirect'
        ]);
        $this->message = 'Fail';
        $this->code = config('constant.API_FAILED_CODE');
        $this->data=[];
    }


    public function secretSignup($id){
//        if($id == '1235346344647fsdfw534545') {
            setSession('isFree', 1);
            return redirect(route('register'));
//        }
//        return back()->withErrors(['message'=>'Invalid URL']);
    }
    public function authRedirect(){
        if(auth()->check()){

            $user_type = auth()->user()->user_type;

            if($user_type == 0){
                return redirect(route('show.manage.clients'));
            }elseif ($user_type == 2){
                $permissions_route_list = getSession('permissions_route_list');
                return redirect(route($permissions_route_list[0]));
            }else {
                return redirect(route('get.clients'));
            }
        }

        return redirect(route('login'));
    }
    public function showLoginForm(){
        unSetSession('isFree');
        return view('auth.login');
    }

    public function login(LoginRequest $request){
        $inputData = $request->only(['email','password']);
        $action='USER_LOGIN';
        $userObjData = (new User())->getAuthenticateUser($inputData['email'],$inputData['password']);
        if(!empty($userObjData)){
            Auth::loginUsingId($userObjData->id);

            if($userObjData->user_type == 0)
            {
                setSession('login',1);
                $this->userAccessDateVerification($userObjData);
//                $this->lastPaymentDateVerification($userObjData);
                $days = getDateDifference($userObjData->last_import_date,'day');
                if($days >= config('constant.PACKAGE_INTERVAL_DAY')){
                    setSession('eligible_for_import',1);
                    $userObjData->is_import = config('constant.IMPORT_REPORT_STATUS.ELIGIBLE');
//                    $userObjData->wave = ($userObjData->wave +1);
//                    $userObjData->last_import_date = getCurrentDateTime();
                    $userObjData->save();
                }
                if($userObjData->is_first_login == 1){
                    setSession('is_first_login',1);
                    setSession('is_first_time_login',true);
                }
                getUserImagesAndDoc($userObjData->id);
                $this->setTrainingVideoLink();
                $this->setReportProviderLink();
                $inputData['id'] = $userObjData->id;
                $inputData['user_type'] = 0;
                $this->setSupport($inputData);
                return redirect(route('show.manage.clients'));
            }else if($userObjData->user_type == 2){
                $permissions_route_list = (new Permission())->getRouteNameListByUserId($userObjData->id);
                setSession('permissions_route_list',$permissions_route_list);
                $inputData['id'] = $userObjData->id;
                $inputData['user_type'] = 1;
                $this->setSupport($inputData);
                return redirect(route($permissions_route_list[0]));
            }
            else{
                $inputData['id'] = $userObjData->id;
                $inputData['user_type'] = 1;
                $this->setSupport($inputData);
                return redirect(route('get.clients'));
            }
        }
        return back()->withErrors(['message'=>'Invalid email or password']);
    }

    public function showRegisterForm(){
        return view('layouts.register');
    }

    public function register(Request $request){
        if($request->ajax()){
            $data = [];
            try {
                DB::beginTransaction();
                $data = $this->ajaxRequestHandle($request->all());
                DB::commit();
            }catch (\Exception $ex){
                DB::rollback();

            }
           return response()->json($data,200);
        }
    }

    public function userLogout(){
        auth()->logout();

        return redirect(route('login'));
    }

    private function ajaxRequestHandle($request){
        $user = app(\App\Models\User::class);

        $response['status'] = false;

        if($request['action'] == "CREATE_ACCOUNT"){
            $inputData['first_name'] = $request['FirstName'];
            $inputData['last_name'] = $request['LastName'];
            $inputData['email'] = $request['Email'];
            $inputData['password'] = $request['Password'];
            if($user->getUserByEmail($inputData['email'])){
                $response['status'] = true;
                $response['message'] = "Email ".$inputData['email']." is already taken";
            }else {

                if ($saved = $user->addUser($inputData)) {
                    $response['status'] = true;
                    session()->put('user_id',$saved->id);
                    session()->put('step',2);
                    $response['html'] = view('register.partials.add_profile')->render();
                }
            }
        }else if($request['action'] == "ADD_PROFILE"){

            $inputData['street_no'] = $request['Street_no'];
            $inputData['street_name'] = $request['Street_name'];
            $inputData['city'] = $request['City'];
            $inputData['state'] = $request['State'];
            $inputData['ssn'] = $request['ssn'];
            $inputData['zip_code'] = $request['Zip'];
            $inputData['phone'] = $request['PhoneNumber'];

            if($user->userupdate($inputData,session()->get('user_id'))){
                $response['status'] = true;
                session()->put('step',3);

                $response['html'] = view('register.partials.credit_report')->render();
            }

        }else if($request['action'] == "CREDIT_REPORT"){
            $comapanyTypeArray = [
                '1'=>3,
                '2'=>3,
                '3'=>1
            ];
            $inputData['package_id'] = $request['package_id'];
            $inputData['user_id'] = session()->get('user_id');

            $userPackage = new UserPackage();
            if($userPackage->setUserPackage($inputData)) {
                $updateData['credit_report_company_type'] = $comapanyTypeArray[$inputData['package_id']];
                $user->userupdate($updateData,$inputData['user_id']);
                $response['status'] = true;
                $response['redirect_url'] = route('login');
            }
        }

        return $response;
    }

    private function setTrainingVideoLink(){
        $key = 'training_video_link';

        unsetCache($key);
        if(empty(getCache($key))){
            $training_video = (new VideoSetting())->getVideoList();
            if(!empty($training_video)) {
                setCache($key, $training_video);
            }
        }
    }

    private function setReportProviderLink(){
        $key = 'credit_report_provider_link';
        unsetCache($key);
        if(empty(getCache($key))){
            $report_provider = (new CreditreportProvider())->getReportProviders();
            if(!empty($report_provider)) {
                setCache($key, $report_provider);
            }
        }

    }

    private function lastPaymentDateVerification($userObjData)
    {
        $days = getDateDifference($userObjData->last_payment_date,'day');
        if($days > config('constant.PAYMENT_INTERVAL_DAY')){
            Auth::user()->update([
                'subscription_status'=>config('constant.SUBSCRIPTION_STATUS.UNSUBSCRIBED'),
            ]);
        }
    }

    private function userAccessDateVerification($userObjData)
    {
        if( getCurrentDateTime() > $userObjData->user_access_end_date){
            Auth::user()->update([
                'subscription_status'=>config('constant.SUBSCRIPTION_STATUS.UNSUBSCRIBED'),
            ]);
        }
    }

    private function setSupport($inputData)
    {
//        $support_data = (new Support())->getSupport($inputData);
//        setSession('new_ticket',$support_data->count());
        $support_data = (new Support())->getNotifcation($inputData['id'],$inputData['user_type'])->toArray();
        setSession('new_ticket',$support_data);
    }
}
