<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models;
use App\Utilities\ApiCalls;
use Session;
use Illuminate\Validation\Rules\Password;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Hash;

class ClientsLoginController extends Controller
{
    public function index(){
        $data = [
            'page_title' => 'User Login'
        ];
        return view('client-auth.login', $data);

    }
    public function activation_show($hash){
        #check if activation hash exist and it has not expired
        $check_activation = Models\ClientSession::where('activation_hash', $hash)->firstOrFail();
        // dump($check_activation);
        $elapsedMinutes = now()->diffInMinutes($check_activation->activation_start_time);
        if ($elapsedMinutes > 30) {
            // code...
            // $elapsedDays = Carbon::parse($stringDate)->diffInDays();
            // OR using the now() helper 
            
            // $isExpired = $check_activation->activation_start_time->diffInMinutes() > 30;
            $data = [
                'page_title' => 'Client Activation Expired'
            ];
            return view('client-auth.activation-notfound', $data);
        }
        $data = [
            'page_title' => 'Client Activation',
            'hash' => $hash
        ];
        return view('client-auth.activation-form', $data);

    }
    public function activation(Request $request){
        $this->validate($request,             [
            'password' => 'required',
            // 'password' => ['required', 'min:8', 'confirmed']
            'password' => ['required','confirmed', Password::min(8)->letters()->numbers(),]
        ]);
        if ($request->filled('activation_hash')) {
            return redirect()->back()->withErrors(['Your Activation request can not be handled. Try again']);
        }

        $client = Models\ClientSession::where('activation_hash', $request->hash)->firstOrFail();
        if ($client->activation_status == 'ACTIVATED') {
            return redirect()->back()->withErrors(['Your Activation request can not be handled. Try again']);
        }

        $create_client_url = "clients/$client->client_id/status";
        $client_arr = ['status' => 'ACTIVE'];
        $result = ApiCalls::CurlPatch(json_encode($client_arr), $create_client_url);


        $name = $client->name;
        // $client->client_id = $result->id;
        $client->activation_status = 'ACTIVATED';
        $client->password = Hash::make($request->password);
        $client->save();

        
        \Log::info($name . ' Successfully activated their account at : ' . date('Y-m-d H:i:s'));
        Session::flash('success_message', 'You have successfully activated your account, login to get started');
        return redirect(url('/'));
        
    }

    
    public function handleLogin(Request $request){

        $this->validate($request, ['email' => 'required', 'password' => 'required']);
        $logged_in = '';
        
        $client = Models\ClientSession::where('email', $request->email)->first();
        // dump($client);
        if ($client == false) {
            return redirect()->back()->withErrors(['Invalid credentials']);
        }

        $client_url = "clients/" . $client->client_id;
        $result = ApiCalls::CurlGet($client_url);
        // dd($result);
        $result_arr = json_decode($result, true);        
        $logged_in = $result_arr;
        // dd($logged_in);
        $request->session()->regenerate(true);
        $request->session()->put('current_user.user_id', $logged_in['id']);
        $request->session()->put('current_user.org_id', $logged_in['id']);
        $request->session()->put('current_user.ucm_org_id', $client->ucm_org_id);
        $request->session()->put('current_user.name', $logged_in['name']);
        $request->session()->put('current_user.email', $logged_in['email']);
        $request->session()->put('current_user.role', $client['role']);
        $request->session()->put('current_user.phoneNumber', $logged_in['phoneNumber']);
        $request->session()->put('current_user.status', $logged_in['status']);
        $request->session()->put('current_user.createdAt', $logged_in['createdAt']);
        $request->session()->put('current_user.updatedAt', $logged_in['updatedAt']);
        // dd('after session');

        \Log::info($logged_in['name']. ' Successfully logged in at : ' . date('Y-m-d H:i:s'));
        return redirect(url('/'));
    }
    public function handle_logout(Request $request) {
        $user_id = session('current_user.id');
        $name = session('current_user.name');


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

        \Log::info($name . ' Successfully logged out at : ' . date('Y-m-d H:i:s'));
        Session::flash('success_message', 'You have successfully logged out!');
        return redirect("/");
    }
}
