<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Session;
use Carbon\Carbon;
use Illuminate\Support\Facades\Validator;
use App\Rules\NotZeroOrEmpty;


use Schema;

class TimeController extends Controller
{


 /**
     * Create a new controller instance.
     *
     * @return void
     */
   // public $obj;

   
   public function __construct()
   {
       $this->middleware('auth');

       Validator::extend('unique_columns', function ($attribute, $value, $parameters, $validator) {
        $table = $parameters[0];
        $columns = array_slice($parameters, 1, -1); // Exclude the last parameter which is optionalRecordId
        $optionalRecordId = end($parameters);
    
        $query = \DB::table($table);
    
        foreach ($columns as $column) {
            $query->where($column, $validator->getData()[$column]);
        }
    // dd($optionalRecordId);
        // Exclude the specified records from the query if an update is being performed
        $arr=explode('`~`',$optionalRecordId);
        if ($optionalRecordId !== null && sizeof($arr)>1) {
           // $arr=explode('`~`',$optionalRecordId);
            $query->where($arr[0], '!=', "$arr[1]");
        } 
        $sqlQuery = $query->toSql();
        $bindings = $query->getBindings();
      //  dd($sqlQuery, $bindings);
        return $query->count() === 0;
     });

   }

   /**
    * Show the application dashboard.
    *
    * @return \Illuminate\Contracts\Support\Renderable
    */


    public function op_schedule(Request $request){

      $dateString = $request->sh_date;
      $carbonDate = Carbon::createFromFormat('d/M/Y', $dateString);
      $formattedDate = $carbonDate->format('Y-m-d');
      $Co_ID=Session::get('Co_ID');
      $USession=Session::get('USession');
      $Br_ID=$request->Br_ID;
      $Sec_ID=$request->Sec_ID;
      $Ts_ID=$request->Ts_ID;
      $SchID=$request->SchID;
      $ESH=$request->ESH;
      if ($SchID==0) {
        $arr=array(
          'Sch_Co_ID'=>$Co_ID,
          'Sch_Br_ID'=>$Br_ID,
          'Sch_Sec_ID'=>$Sec_ID,
          'Sch_Date'=>$formattedDate,
          'Sch_Ts_ID'=>$Ts_ID,
          'Sch_Status'=>0,
          'Status'=>0,
          'Session'=>$USession
        );
        DB::transaction(function () use ($arr,&$SchID) {
         // $Sch_ID=DB::table('schedule_details')->count()+1; 
          $SchID = DB::table('schedule_master')->max('Sch_ID')+1;
          $arr['Sch_ID']=$SchID;
         DB::table('schedule_master')->insertGetId($arr);  
        
            
      });
      }
     
    
        DB::table('schedule_details')->where('Sch_Det_ID', $SchID)->delete();
        foreach ($ESH as $key => $value) {
          $value['Sch_Det_ID']=$SchID;
          $value['Session']=$USession;
          $resp= DB::table('schedule_details')->insert($value); 
        }
      
       if($resp){
        $flg=1;
        $msg="Scheduled Sucessfully";
       }else{
        $flg=0;
        $msg="Scheduling  Faild";
       }

     
            

      
      
      return json_encode(array('flag'=>$flg,'msg'=>$msg));
      

    }

    public function Delete_schedule(Request $request){
DB::table('schedule_details')->where('Sch_Det_ID', $request->sch_id)->delete();
DB::table('schedule_master')->where('Sch_ID', $request->sch_id)->delete();
$userExists = DB::table('schedule_master')->where('Sch_ID', $request->sch_id)->exists();
if ($userExists) {
 return 1;
} else {
 return 0;
}
    }

    public function op_employee(Request $request)
    { 

      
        $hidden_status=$request->hidden_status;
        $row_id=$request->row_id;
        $Co_ID=Session::get('Co_ID');
        $row_id=$request->row_id;
        $Em_Name=$request->Em_Name;
        $Em_Code=$request->Em_Code;
        $Em_Br_ID=$request->Em_Br_ID;
        $Em_Sec_Id=$request->Em_Sec_Id;
        $Em_Place=$request->Em_Place;
        $EM_Dep_IDS=$request->EM_Dep_IDS;
        $USession=Session::get('USession');
        $fn_strt_time=date('H:i:s');
       if($hidden_status!=2){
        $validator = Validator::make($request->all(), [         
            'Em_Name' => 'required',
            'Em_Code' => 'required',
            'Em_Br_ID' => 'required',
            'Em_Sec_Id' => 'required',
            'EM_Dep_IDS' => 'required'
         
        ],[
            
            'Em_Name.required' => ' Employee Name is mandatory',
            'Em_Code.required' => 'Employee Code is mandatory',
            'Em_Br_ID.required' => 'Branch is mandatory',
            'Em_Sec_Id.required' => 'Section is mandatory',
            'EM_Dep_IDS.required' => 'Department is mandatory'
        ]);
      }else{
        $validator = Validator::make($request->all(), [],[]);
      }


        if ($validator->fails()) {
            $errors = $validator->errors()->toArray();
            return response()->json(['errors' => $errors], 422);
        }else{ 

          $arr=array(

            'Em_Co_ID'=>$Co_ID,
            'Em_Br_ID'=>$Em_Br_ID,
            'Em_Name'=>$Em_Name,
            'Em_Code'=>$Em_Code,
            'Em_Place'=>$Em_Place,
            'Em_Sec_Id'=>$Em_Sec_Id,
            'EM_Dep_IDS'=>$EM_Dep_IDS,
            'Status'=>0,
            'Session'=>$USession
          );
          if($hidden_status==0){
            
            DB::transaction(function () use ($arr,&$msg,&$flag) {
             $Em_ID= DB::select("call Last_Insert_ID('Em_ID','employee_master','1');");
             if ( $Em_ID[0]->max_value==null) {
              $max_day=0;
          } else{
            $max_day=$Em_ID[0]->max_value;
          }
              $arr['Em_ID']=$max_day+1;
             $resp= DB::table('employee_master')->insert($arr); 
             if($resp){
              $flag=1;
              $msg=" Employee master insert Successfully";
             }else{
              $flag=0;
              $msg=" Employee master Insertion Faild";
             }
            });
        
          }else if($hidden_status==1){
                
            $userUpdated = DB::table('employee_master')
            ->where('Em_ID', $row_id)
            ->update($arr);
            if( $userUpdated){
              $flag=1;
              $msg=" Employee master Updated Successfully";
             }else{
              $flag=0;
              $msg=" Employee master Updation Faild";
             }

         }else if($hidden_status==2){
                
          $dds = DB::table('schedule_details as SD')
          ->join('schedule_master as SM', 'SM.Sch_ID', '=', 'SD.Sch_Det_ID')
          ->where('SD.Sch_Em_ID',  $row_id)
          ->where('SM.Sch_Date', '>=', Carbon::now())
          ->selectRaw('GROUP_CONCAT(DISTINCT SM.Sch_Date) as DDS')
          ->pluck('DDS')
          ->first();
          if($dds==null){
          $userUpdated = DB::table('employee_master')
          ->where('Em_ID', $row_id)
          ->update(['status'=>'1','Session'=>$USession,'Cancel_Date'=>date('Y-m-d')]);
          if( $userUpdated){
            $flag=1;
            $msg=" Employee master Deleted Successfully";
           }else{
            $flag=0;
            $msg=" Employee master Deletion Faild";
           }
          }else{
            $flag=0;
            $msg=" Employee master Deletion Faild(Sheduled For ". $dds.")";
          }

       }

       

         return json_encode(array('flag'=>$flag,'msg'=>$msg));
        }
    
    }




    public function op_leave(Request $request)
    { 

      
        $hidden_status=$request->hidden_status;
        $row_id=$request->row_id;
        $Co_ID=Session::get('Co_ID');
        $row_id=$request->row_id;
        $Lv_Em_ID=$request->Lv_Em_ID;
        $em_id=$request->em_id;
        $Lv_Br_ID=$request->Lv_Br_ID;
        $Lv_Date=$request->Lv_Date;
        $USession=Session::get('USession');
        $fn_strt_time=date('H:i:s');
       if($hidden_status!=2){
        $validator = Validator::make($request->all(), [         
            'Lv_Em_ID' => 'required',
            'Lv_Br_ID' => 'required',
            'Lv_Date' => 'required'
         
        ],[
            
            'Lv_Em_ID.required' => ' Employee Name is mandatory',
            'Lv_Date.required' => 'Leave Date is mandatory',
            'Lv_Br_ID.required' => 'Branch is mandatory'
        ]);
      }else{
        $validator = Validator::make($request->all(), [],[]);
      }


        if ($validator->fails()) {
            $errors = $validator->errors()->toArray();
            return response()->json(['errors' => $errors], 422);
        }else{ 

          $arr=array(

            'Lv_Co_ID'=>$Co_ID,
            'Lv_Em_ID'=>$em_id,
            'Lv_Br_ID'=>$Lv_Br_ID,
            'Lv_Date'=>$Lv_Date,
            'Lv_Status'=>1,
            'Status'=>0,
            'Session'=>$USession
          );
          if($hidden_status==0){
            
          
             $resp= DB::table('leave_marker')->insert($arr); 
             if($resp){
              $flag=1;
              $msg=" Leave  insert Successfully";
             }else{
              $flag=0;
              $msg=" Leave Insertion Faild";
             }
          
        
          }else if($hidden_status==1){
                
            $userUpdated = DB::table('leave_marker')
            ->where('Em_ID', $row_id)
            ->update($arr);
            if( $userUpdated){
              $flag=1;
              $msg=" Employee master Updated Successfully";
             }else{
              $flag=0;
              $msg=" Employee master Updation Faild";
             }

         }else if($hidden_status==2){
            $rarr=explode('~',$row_id);
          $userUpdated = DB::table('leave_marker')
          ->where('Lv_Em_ID', $rarr['0'])
          ->where('Lv_Br_ID', $rarr['1'])
          ->where('Lv_Date', $rarr['2'])
          ->update(['status'=>'1', 'Lv_Status'=>1 ,'Session'=>$USession]);
          if( $userUpdated){
            $flag=1;
            $msg=" Employee Leave Deleted Successfully";
           }else{
            $flag=1;
            $msg=" Employee Leave Deletion Faild";
           }

       }

       

         return json_encode(array('flag'=>$flag,'msg'=>$msg));
        }
    
    }



}
