<?php

namespace App\Http\Controllers\branch;


use Validator;
use App\Models\User;
use App\Models\Branch;
use App\Models\Operator;
use App\Models\Registrar;
use App\Models\Attendance;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\{Hash, Session,DB};

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();
            if(!empty($userbefor) && $userbefor->status==0){
                $data['error'] = "Your account is inactive. Contact your administrator to activate it.";
                return view('branch.index', ['data' => $data]);
            }
            // 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)
    {
        Session::forget('branchsession');
        return redirect('/branch-login');
    }


    public function attendance()
    {   
        if(DB::table('model_has_permissions_branch')->where([['branch_code',Session::get('branchsession')->branch_code ],['model_id','54']])->first()){
             $assing = 1;
        } else {
            return redirect()->route('branch.not.access')->with('error', 'This Model not Assing!');
        }
        $branch_code = Session::get('branchsession')->branch_code;
        $carbonDate = Carbon::now('Asia/Kolkata');
        $attendance = Attendance::where([['branch_code', $branch_code], ['date', $carbonDate->format('Y-m-d')]])->first();
        $attendances = Attendance::where([['branch_code', $branch_code]])->latest()->limit(10)->get();
        return view('branch.attendance.index', compact('attendance', 'attendances'));
    }
    public function attendancePost(Request $request)
    {   
        $branch_code = Session::get('branchsession')->branch_code;
        $attendance = new Attendance();
        $carbonDate = Carbon::now('Asia/Kolkata');
        // Format the Carbon instance as desired        
        $attendance->message_morning = $request->message ?? 'Good Morning';
        $attendance->date = $carbonDate->format('Y-m-d');
        $attendance->in_time  = $carbonDate->format('H:i:s');
        $attendance->branch_code  = $branch_code;
        $attendance->save();
        return redirect()->back()->with([
            'message' => 'Good Morning!',
            'alert-type' => 'success'
        ]);
    }
    public function attendancePostNight(Request $request)
    {   
        
        $branch_code = Session::get('branchsession')->branch_code;
        $carbonDate = Carbon::now('Asia/Kolkata');

        $attendance = Attendance::where([['branch_code', $branch_code], ['date', $carbonDate->format('Y-m-d')]])->first();
        $startTimeStr = $attendance->in_time;
        $endTimeStr   = $carbonDate->format('H:i:s');
        // Convert string times to DateTime objects
        $startTime = \DateTime::createFromFormat('H:i:s', $startTimeStr);
        $endTime = \DateTime::createFromFormat('H:i:s', $endTimeStr);

        // Calculate the difference between the two times
        $timeDifference = $startTime->diff($endTime);

        // Get the difference in hours
        $hours = $timeDifference->h + ($timeDifference->i / 60);
        
        $attendance->message_night = $request->message ?? 'Good Night';
        $attendance->out_time  = $carbonDate->format('H:i:s');
        $attendance->persent_type = $hours;
        $attendance->save();
        return redirect()->back()->with([
            'message' => 'Good Night!',
            'alert-type' => 'success'
        ]);
    }

    public function attendanceOperator(Request $req)
    {   
        if(DB::table('model_has_permissions_branch')->where([['branch_code',Session::get('branchsession')->branch_code ],['model_id','89']])->first()){
             $assing = 1;
        } else {
            //  dd('jjll');
            return redirect()->route('branch.not.access')->with('error', 'This Model not Assing!');
        }
        $branch_code = Session::get('branchsession')->branch_code;
        $operatorList = Operator::where([['branch_id',$branch_code]])->get();
        $District = Operator::where([['branch_id',$branch_code]])->pluck('District')->unique();
        $state = Operator::where([['branch_id',$branch_code]])->pluck('State')->unique();
        
        $registrars = Registrar::all();
        $carbonDate = Carbon::now('Asia/Kolkata');
        $attendances = Attendance::where([['branch_code', null]])->with(['Operator']);
                    if(isset($req->operator_code)){
                        $attendances =  $attendances->where('operator_Code', $req->operator_code);
                    }
                $attendances =  $attendances->orderBy('date', 'DESC')->paginate(30);
        return view('branch.attendance.operator', compact('attendances', 'registrars','branch_code', 'state',  'operatorList', 'District'));
    }
}
