<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models;
use Spatie\Activitylog\Models\Activity;
use Illuminate\Support\Str;
use App\Jobs\SendOtpEmailAlert;


class LoginController extends Controller
{
    public function getLoginPage(){
        $designation = Models\Designation::pluck('name', 'id');
        $data = [
            'designation' => $designation
        ];
    	return view('login.index', $data);
    }
    public function resendOtp(){
        if(!request()->session()->has('current_otpuser')){
            return redirect(url('login'))->withErrors("No session found. You need to be logged in!");
        }
        $otp_code = Str::random(6);
        \Log::info($otp_code);
        request()->session()->put('current_otpuser.otp', $otp_code);
        $otp_user = session('current_otpuser');

        $otp_set = [
            'otp' => $otp_code, 
            'email' => $otp_user['email'], 
            'auth_name' => $otp_user['name']
        ];
        dispatch(new SendOtpEmailAlert($otp_set));
        $data = [
            'otp_user_id' => $otp_user['id'],
            'page_title' => 'Login OTP',
            'auth_name' => $otp_user['name']
        ];
        return view('login.otp', $data);
    }
    public function showOtpPage(){
        if(!request()->session()->has('current_otpuser')){
            $random = uniqid();
            return redirect(url('login'))->withErrors("$random | You need to be logged in ");
        }
        $otp_user = session('current_otpuser');
        $data = [
            'otp_user_id' => $otp_user['id'],
            'page_title' => 'Login OTP',
            'auth_name' => $otp_user['name']
        ];
        return view('login.otp', $data);
    }
    public function handleLoginOtp(Request $request){
        $this->validate($request, ['email' => 'required', 'password' => 'required']);
        //system user : $table = "auth_users";
        $logged_in = Models\SystemUser::with('designation_info')->where('email', $request->email)->where('password', md5($request->password))->first();

        if(empty($logged_in)){
          return redirect("/")->withErrors(array("Incorrect Email/Password. Check and try again!"))->withInput();
        }

        $otp_code = Str::random(6);
        $request->session()->regenerate(true);
        $request->session()->put('current_otpuser.id', $logged_in->id);
        $request->session()->put('current_otpuser.otp', $otp_code);
        $request->session()->put('current_otpuser.name', $logged_in->name);
        $request->session()->put('current_otpuser.email', $logged_in->email);
        $request->session()->put('current_otpuser.phone', $logged_in->phone);
        $request->session()->put('current_otpuser.datetime_sent', date('Y-m-d H:i:s'));
        $request->session()->put('current_otpuser.designation', $logged_in->designation_info->name);

        $otp_set = ['otp' => $otp_code, 'email' => $logged_in->email, 'auth_name' => $logged_in->name];
        dispatch(new SendOtpEmailAlert($otp_set));
        return redirect(url('showotp'));
    }
    public function handleLogin(Request $request){
        // dump($request->all());    
    	$this->validate($request, ['otp' => 'required', 'otp_user_id' => 'required']);
        //system user : $table = "auth_users";
        $current_date = date('Y-m-d H:i:s');
        $otp_user = session('current_otpuser');

        $date1 = new \DateTime($otp_user['datetime_sent']);
        $date2 = new \DateTime($current_date);

        $interval = $date1->diff($date2);
        $minutes = ($interval->h * 60) + $interval->i;
        // dd($minutes);
        if($minutes > 2 ){
          return redirect("showotp")->withErrors(array("OTP Time Out. Resend and try again!"));
        }

        $otp_user = session('current_otpuser');
        if(strtoupper($otp_user['otp']) !== strtoupper($request->otp)){

          return redirect("showotp")->withErrors(array("Incorrect OTP. Check and try again!"))->withInput();
        }
    	#$logged_in = Models\SystemUser::with('designation_info')->where('email', $request->email)->where('password', md5($request->password))->first();
        /*
        if(empty($logged_in)){
    	  return redirect("/")->withErrors(array("Incorrect Email/Password. Check and try again!"))->withInput();
    	}
        */
    	$request->session()->regenerate(true);
    	$request->session()->put('current_user.id', $otp_user['id']);
    	$request->session()->put('current_user.name', $otp_user['name']);
    	$request->session()->put('current_user.email', $otp_user['email']);
    	$request->session()->put('current_user.phone', $otp_user['phone']);
        $request->session()->put('current_user.designation', $otp_user['designation']);


        \Log::info($otp_user['name']. ' Successfully logged in at : ' . date('Y-m-d H:i:s'));

        $content = $otp_user['name'] . " Successfully Logged In";
        // dd($content); 
        #activity()->log($otp_user['name']. ' Successfully logged in at : ' . date('Y-m-d H:i:s'));

        $this->logUsersActivity($type = 'staff', $content, $otp_user['id']);
        $this->deleteLoggedUser();
        $this->storeLoggedUser();

        return redirect(url('/'));
        /*
        switch ($otp_user['designation_info']) {
            case 'Administrator':
                return redirect(url('finance')); // change it to a combined dashboard
                break;
            case 'Accounts & Finance':
                return redirect(url('finance'));
                break;

            default:
                return redirect(url('/'));
                break;
        }
        */
    }

    public function handle_logout(Request $request) {
        $this->deleteLoggedUser();
        $user_id = session('current_user.id');
        $username = session('current_user.name');
        $content  = $username . " Logged Out";

        $request->session()->forget('current_user');
        $request->session()->flush();
        $request->session()->regenerate(true);

        #activity()->log($username . " Logged Out : " . date('Y-m-d H:i:s'));
        $this->logUsersActivity($type = 'staff', $content, $user_id);

        return redirect("/");
    }

    public function registerAccount(Request $request){
        dd($request->all());
        $request->validate([
            'name' => 'required',
            'designation' => 'required',
            'email' => 'required',
            'phone' => 'required',
            'password' => 'required',
            'confirm_password' => 'same:password',
        ]);

        $make_account = [
            'name' => $request->name,
            'designation' => $request->designation,
            'email' => $request->email,
            'phone' => $request->phone,
            'password' => md5($request->password)
        ];

        $inserted = Models\Account::create($make_account);
        Session::flash('success_message', 'Account successfully added');
        return redirect(url('/'));
    }
}
