<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use Carbon\Carbon;
use App\ActivityLog;
use Illuminate\Support\Facades\Mail;
use App\Mail\ResetPassword;
use App\Models\Merchant;
use Validator;
use App\Models;
use Session;
use Illuminate\Support\Facades\Hash;


class OrganisationLoginController extends Controller
{
    
    public function login_page(Request $request){

        session(['pre_page' => $request->headers->get('referer')]);

        return view('login.organisation.index');
    }
    //Add user
    public function add_user(){
        dd('foo bar');
        // $password = bcrypt('kweku20');

        // $user = new User;
        // $user->name = 'Kweku Debrah';
        // // $user->lastname = 'Debrah';
        // $user->email='kweku.debrah.emma@gmail.com';
        // $user->password = $password;

        $save = $user->save();

    }

   
    public function register_page(){
        $data = ['page_title' => 'Dealer Sign Up'];
        return view('login.organisation.register',$data);        
    }
    public function register_success(){
        $data = ['page_title' => 'Dealer Sign Successful'];
        return view('login.organisation.register-success',$data);
    }
    public function register(Request $request){
         $this->validate($request, [
            'name' => 'required',
            'phone'=> 'required|unique:organisations,phone',
            'email' => 'required'
        ]);
        $org_arr = $request->except('_token');
        $phone = $this->validatePhoneNumber($request->phone);
        // dd($phone);
        if ($phone == false) {
            Session::flash('error_message', 'Invalid phone number format. Check and try again');
            return redirect()->back()->withInput();
        }
        $org_arr['phone'] = $phone;
        $result = Models\Organisation::create($org_arr);

        if ($result == null) {
            Session::flash('error_message', 'Your request could not be handled at this time. Try again later');
            return redirect()->back()->withInput();
        }
        return redirect('dealer/register-success');
    }

    public function resetpassword(Request $request){

        $this->validate($request, [
            'user_id' => 'required',
            'current_password' => 'required',
            'new_password' => 'required',
            'confirm_password' => 'required'
        ]);


        // if($validator->fails()){
        //     return redirect()->back()->with('login-error', 'Enter required data!');
        // }
        
        $org_user = Models\OrgUser::find($request->user_id);
        if (!Hash::check($request->current_password, $org_user->password)) {
            return redirect()->back()->with('login-error', 'Incorrect current password!');   
        }
        if ($request->input('new_password') !== $request->input('confirm_password')) {
            return redirect()->back()->with('login-error', 'New Passwords do not match!');
        }
        $new_password = Hash::make($request->new_password);
        $user = Models\OrgUser::where('id', $request->user_id)->update([
            'password' => $new_password,
        ]);
        return redirect()->to('organisation/reset-password')->with('login-success', 'Password Changed Successfully, Login to continue');

    }

    public function forgot_page(){
        return view('login.forgot');
    }
    public function resetCreate(){
        $user = session('current_org_user');

        $data = [
            'user' => $user,
            'page_title' => 'Password Reset'
        ];
        return view('organisation.reset', $data);
    }

    public function sendResetMail(Request $request){
        
        // dd($request->all());

        $validator = Validator::make($request->all(), [

            'email' => 'required',
        
        ]);

        if($validator->fails()){

            return redirect()->back()->with('login-error', 'Enter required data!');

        }
        $email = $request->input('email');
        $user = User::where('email', $email)->first();
        if ($user == null ) {
            return redirect()->back()->with('login-error', 'Email Doesnt Exist!');
        }

        $newUser = [

            'name' => $user->name,
            'email' => $email,

        ];

        Mail::to($email)->send(new ResetPassword($newUser));

        return redirect()->to('/confirm-mail');

    }

    public function confirmMail()
    {
        return view('login.confirm');
    }
    public function handleLogin(Request $request){
        // $this->log_query();
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' =>'required'
        ]);
        

        if($validator->fails()){
            return redirect()->back()->with('login-error', 'Email/Password required!');
        }
        $org_user = Models\OrgUser::with('org_info')->where('email', $request->email)->first();
        // dd($org_user);
        if($org_user == null){
            return redirect()->back()->with('login-error', 'Email/Password Incorrect!');
        }

        if (Hash::check($request->password, $org_user->password)) {
            $request->session()->regenerate(true); 
            $request->session()->put('current_org_user.id', $org_user->id);
            $request->session()->put('current_org_user.name', $org_user->name);
            $request->session()->put('current_org_user.email', $org_user->email);
            $request->session()->put('current_org_user.org_id', $org_user->id); //remove this in the next update
            $request->session()->put('current_org_user.org_name', $org_user->org_info->name);
            $request->session()->put('current_org_user.currency', $org_user->org_info->currency);
            
            $desc = [
                'title' => 'Login',
                'data' =>   $org_user->name . ' Successful login'
            ];

            $activity = new ActivityLog;
            $activity->user_id = $request->session()->get('current_org_user.id');
            $activity->user_type = 'organisation';
            $activity->description = json_encode($desc);
            $activity->save();

            return redirect()->to('organisation');
        }
        else{
            return redirect()->back()->with('login-error', 'Email or Password incorrect!');   
        }
    }
    public function logout(){
        session(['current_org_user' => null]);
        // return redirect()->to('/organisation/login');
        return redirect()->to('/');
    }
}
