<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use App\Models\InOut;
use App\CustomClass\Helper;
use Illuminate\Support\Facades\Session;

class AttendanceController extends Controller
{
    public function in(Request $request){
        $user= Auth::user();
        $ip=Helper::getClientIp();
        if($user->assign_ip) {
            if(!preg_match("/\b$ip\b/i", $user->assign_ip)){
                return json_encode(['error'=>'Sorry You are trying in wrong way !']);
            }
        }
        $today= Carbon::today();
        $inTime= date('H:i:s');
        $insert=false;
        $result = InOut::where('user_id',$user->id)->where('date',$today)->orderBy('id','DESC')->take(1)->first();
        if($result){
            if($result->out_time){
                $insert=true; //to be insert into DB
            }else{
                return json_encode(['error'=>'You already IN !']);
            }
        }else{
            $insert=true; //to be insert into DB for the first time at daily
            $reduce= Auth::user()->in_time_reduce;
            $inTime= date('H:i:s', strtotime($inTime . " -$reduce minutes")); // -5 minutes
        }
        if($insert==true){
            $new= new InOut();
            $new->user_id=$user->id;
            $new->client_id=$user->client_id;
            $new->in_time=$inTime;
            $new->in_ip=$ip;
            $new->out_time=null;
            $new->date=$today;
            $new->created_by=$user->id;
            $new->updated_by=$user->id;
            $new->created_at=date('Y-m-d H:i:s');
            $new->updated_at=date('Y-m-d H:i:s');
            $new->save();
            return json_encode(['success'=>'Successfully IN!']);
        }

    }
    public function out(Request $request){
        $user= Auth::user();
        $ip=Helper::getClientIp();
        if($user->assign_ip) {
            if(!preg_match("/\b$ip\b/i", $user->assign_ip)){
                return json_encode(['error'=>'Sorry You are trying in wrong way !']);
            }
        }
        $today= Carbon::today();
        $outTime= date('H:i:s');
        $result = InOut::where('user_id',$user->id)->where('date',$today)->orderBy('id','DESC')->take(1)->first();
        if($result){
            if($outTime<=$result->in_time){
                return json_encode(['error'=>'Sorry You can\'t out now!']);

            }
            $time_calc= (new Carbon($outTime))->diff(new Carbon($result->in_time))->format('%h:%i:%s');
            $time_calc= Helper::timeToSecond($time_calc);
            $result->out_time=$outTime;
            $result->time_calc=$time_calc;
            $result->out_ip=$ip;
            $result->out_comment=$request->out_comment;
            $result->updated_by=$user->id;
            $result->save();
            return json_encode(['success'=>'Successfully OUT!']);
        }else{
            return json_encode(['error'=>'At first you have to IN!']);
        }
    }
    public function updateUserAttendance(Request $request){
        //Old IN/OUT calculation

        for($i=0; $i<$request->max_row; $i++) {
            $inOutId = $request->in_out_id[$i];
            $oldIn = $request->old_in[$i];
            $oldOut = $request->old_out[$i];
            if ($oldOut == null) {
                $timeCalc = null;
            } else {
                $timeCalc = (new Carbon($oldOut))->diff(new Carbon($oldIn))->format('%h:%i:%s');
                $timeCalc= Helper::timeToSecond($timeCalc);
            }
            try {
                $old = InOut::find($inOutId);
                $old->in_time = $oldIn;
                $old->out_time = $oldOut;
                $old->time_calc = $timeCalc;
                $old->updated_by = Auth::id();
                $old->updated_at=date('Y-m-d H:i:s');
                $old->save();
            } catch (\Exception $e) {
                return $e;
            }
        }
        //OLD IN OUT calculation end
        //New IN out calculation Start
        $lengthIn= count($request->in_new);
        $lengthOut= count($request->out_new);
        if($lengthIn==$lengthOut){
            for($j=0;$j<$lengthIn; $j++){
                $inTime=$request->in_new[$j];
                $outTime=$request->out_new[$j];
                if($inTime!=null) {
                    $inTime= date("H:i", strtotime($inTime));
                    if ($outTime == null) {
                        $timeCalc = null;
                    } else {
                        $outTime= date("H:i", strtotime($outTime));
                        $timeCalc = (new Carbon($outTime))->diff(new Carbon($inTime))->format('%h:%i:%s');
                        $timeCalc= Helper::timeToSecond($timeCalc);
                    }
                    $new = new InOut();
                    $new->user_id = $request->userId;
                    $new->client_id = Auth::user()->client_id;
                    $new->in_time = $inTime;
                    $new->out_time = $outTime;
                    $new->time_calc = $timeCalc;
                    $new->date = $request->date;
                    $new->created_by = Auth::id();
                    $new->updated_by = Auth::id();
                    $new->save();
                }

            }
        }
        return redirect()->back()->with('success','Successfully Modified!');

    }
    public function deleteAttendance($id){
        $result = InOut::where('id',$id)
                    ->where('client_id',Auth::user()->client_id)
                    ->delete();
        return redirect()->back()->with('success','Attendance deleted successfully!');
    }
}
