<?php

namespace App\Http\Controllers\branch;

use Session;
use Validator;
use App\Models\User;
use App\Models\Branch;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Crypt;

class BranchAtuthController extends Controller
{
    public function Index(Request $req){
        $data = array();

            if($req->isMethod('post')){


                $validator = Validator::make($req->all(), [
                    'branch_code' => 'required',
                    'password'    => 'required',
                ]);
                if ($validator->fails()) {
                    return redirect()
                        ->back()
                        ->withInput($req->input())
                        ->withErrors($validator->errors());
                }

                $userbefor = Branch::where(['branch_code'=>$req->branch_code])->first();
                // dd(new DateTime('now'));
                $mytime = Carbon::now('Asia/Kolkata');
                // dd($mytime->toDateTimeString());
                if($userbefor){
                    $userbefor->last_login = $mytime->toDateTimeString();
                $userbefor->save();
                }
                $user = Branch::where(['branch_code'=>$req->branch_code])->first();

                if($user) {
                        if(!Hash::check($req->password, $user->password)){
                            $data['error'] = "Password does not match";
                        }else{
                            Session::forget('operatorsession');
                            Session::forget('adminsession');
                            $req->session()->put('branchsession', $user);
                            return  redirect('branch/dashboard');
                        }
                }else{
                    $data['error'] = "Branch Code and Password is not matched";
                }
            }

            if(session()->has('branchsession')){
                return  redirect('branch/dashboard');
            }else{
                return view('branch.index', ['data'=>$data]);
            }
    }

    public function logout(Request $request){


        // $request->session()->flush();
        Session::forget('branchsession');
        return redirect('/branch-login');
    }

}
