<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class staff extends CI_Controller {

    private $userInfo = array();
 
    public function __construct()
    {
        parent::__construct();
        $this->load->model("user_model");
        $this->load->model("staff_model");
        $this->load->model('Teacher_model');
        $this->user_model->check_login("admin");

        $this->userInfo = $this->user_model->userInfo("first_name,last_name");
    }

    public function index($date='')
    {
        $this->user_model->check_permissions("staff/index");
        
        $data['is_super'] = $this->user_model->is_super();
        $data['menu'] = $this->load_model->menu();
         $data['department']=$this->db->where('department.is_delete',0)->get('department')->result_array();   
        $this->db->select("id,name"); 
        $this->db->from('branch');
        
        $this->db->where('is_delete','0');
       if(!$this->user_model->is_super()){
        $branch=$this->user_model->getbranch();
        $this->db->where('id',$branch);
       } 
        if($this->user_model->is_super())
            $data['branch'] = $this->db->query("SELECT id,name FROM `branch` where is_delete='0'")->result_array();
        else
            $data['branch'] = $this->db->query("SELECT id,name FROM `branch`  where is_delete='0' AND id='".$branch."'")->result_array();
             $query = $this->db->get();
        $data['base_url'] = base_url();
        $data['userInfo'] = $this->userInfo;
        $this->load->view('header',$data);
        $this->load->view('sidebar',$data);
        
        $this->load->view('staff/staff_add',$data);
    }
    
     public function editStaffAttStatus($date='')
    {
        $this->user_model->check_permissions("Staff/editStaffAttStatus");
        $data['userInfo'] = $this->userInfo;
        $data['base_url'] = base_url();
        $data['menu'] = $this->load_model->menu();
                $branchid=$this->user_model->getbranch();

        if($date=='')
        $data['date'] = date('Y-m-d');
        else
        $data['date'] = $date;

        $attendance = $this->db->where('is_deleted',0)->where('date',$data['date'])->where('status_id',1)->get('staffatt')->result_array();
        if($attendance){
            $staff_ids = array_column($attendance,"staff_id");
            $this->db->where_not_in('staff.id',$staff_ids);
        }
        $data['staff'] = $this->db->select('staff.*,department.name')->where('staff.status',0)->where('staff.is_delete',0)->where('staff.branch',$branchid)->join('department','staff.dpt=department.id','left')->get('staff')->result_array();

        $this->load->view('header',$data);
		$this->load->view('sidebar',$data);
        $this->load->view('staff/staffAttEdit',$data);
    }

    public function updateStaffAtt()
    {
        if($this->input->post()){
            $post = $this->input->post();
            //echo "<pre>";print_r($post);exit;
            $update_arr = array();
            $this->db->where('date',$post['date'])->where('status_id!=',1)->delete('staffatt');
            foreach ($post['staff'] as $key => $value) {
                if(!empty($value)){
                    $update_arr[]=array(
                                    'staff_id'=>$key,
                                    'date'=>$post['date'],
                                    'status_id'=>$value
                                );
                }
            }
            if(!empty($update_arr))
            $this->db->insert_batch('staffatt',$update_arr);
            
            redirect("Staff/editStaffAttStatus/".$post['date']);
        }
    }
    
   public function fetch_staffatt_selected_datewise()
    {
            $data['staff']=$this->db->query("
            SELECT staff.firstname, staffatt.*, department.name, staff.designation 
FROM `staffatt`
INNER JOIN staff ON staffatt.staff_id=staff.id
inner join department on staff.department = department.id
WHERE staffatt.date >= '2017-10-15' 
AND  staffatt.date <= '2017-10-20'
AND staffatt.is_deleted=0
ORDER BY(date)
            ")->result_array();
         
            
        
            $data['base_url'] = base_url();
            $data['userInfo'] = $this->userInfo;
           
            $this->load->view('report/staff_date_wise_attt',$data);
    
       
    }
      public function staffatt_view1($date='')
    {
        $this->user_model->check_permissions("staff/staffatt_view1");  
        $data['menu'] = $this->load_model->menu();
        $branch=$this->user_model->getBranch();
        $data['base_url'] = base_url();
        $data['userInfo'] = $this->userInfo;
        
        if($date==''){
            $date=date('Y-m-d');
        }
        $data['date'] = $date;
        
        $branchid=$this->user_model->getbranch();
        
        $query = $this->db->query("SELECT staff.firstname,staff.lastname,staff.designation,staffatt.id,staffatt.date,staffatt.check_in,staffatt.check_out FROM `staffatt` inner join `staff` on staffatt.staff_id = staff.id WHERE staff.branch = '$branch' AND staffatt.date='".$date."' AND staff.status='0'  AND staffatt.is_deleted='0'");
        $data['staffatt'] = $query->result_array();
        $this->load->view('header',$data);
        $this->load->view('sidebar',$data);
        $this->load->view('staff/staffatt_view1',$data);
    }
    
   public function show($q="all",$p=1)
    {
        $this->user_model->check_permissions("staff/show");
        $data['edit_delete']=$this->user_model->checkEditDelete('staff/show');
        //"<pre>";print_r($data['edit_delete']);exit;
        $data['is_super'] = $this->user_model->is_super();
        $data['menu'] = $this->load_model->menu();
        $branch=$this->user_model->getbranch();
         

        // $q = urldecode($q);
        // $p = $p<1?1:$p;
        // $per_page = 10;
        // $offset = ($p - 1) * $per_page;
        $data['base_url'] = base_url();
        $data['userInfo'] = $this->userInfo;
        
        // $sq1 = "";
        // if($q!="all")
        // {
        //     $sq1 .= "AND (firstname like '%".$q."%' OR "; 
        //     $sq1 .= "lastname like '%".$q."%' OR "; 
        //     $sq1 .= "designation like '%".$q."%' OR "; 
        //     $sq1 .= "contact like '%".$q."%' )";
        // }
        // $total = $this->db->query("SELECT count(*) as total FROM `staff` where status='0' AND branch=$branch $sq1")->result_array()[0]['total'];
        //  if($total<=$offset)
        //  {
        //             $query = $this->db->query("SELECT id,designation,contact,qualification,doj,dob,salery FROM `staff` WHERE branch = '$branch' AND status='0' $sq1 LIMIT 0, $per_page");
        //         $p=1;
        //         }else
        $query = $this->db->query("SELECT staff.id,firstname,lastname,designation,contact,qualification,doj,dob,salery,department.name FROM `staff` LEFT JOIN `department` on staff.dpt=department.id WHERE branch = '$branch' AND status='0'  and staff.is_delete='0' ");// $sq1 LIMIT $offset, $per_page

        
        // $data['q'] = $q;
        // $data['curr'] = $p;
        // $data['searchq'] = $q;

        $data['staff'] = $query->result_array();
        // $data['end'] = ceil($total / $per_page);
        $this->load->view('header',$data);
        $this->load->view('sidebar',$data);
        $this->load->view('staff/staff_view',$data);
    }

    public function save()
    {
        $data = $this->input->post();
        $data['dob']= date('Y-m-d',strtotime($data['dob']));
                  $data['doj']= date('Y-m-d',strtotime($data['doj']));


        $db_insert = $this->staff_model->save($data);
        redirect("staff/index","refresh");
    }
    
    public function edit()
    {

             $data['menu'] = $this->load_model->menu();
             $data['department']=$this->db->where('is_delete',0)->get('department')->result_array();  
              $id = explode(SALT,json_decode(base64_decode($this->uri->segment(3))))[0]; 
              
               $increments=$this->db->select('sum(amount) as amount')
                                       ->from('increments')
                                       ->where('refrence',"staff")
                                       ->where('bothid',$id)
                                       ->where('is_del',0)
                                       ->get()->row_array()['amount'];
                if(!empty($increments)) 
                {
                    $data['increment']=$increments;
                }else
                {
                    $data['increment']=0;
                }

             $data['values']= $this->db->where('id',$id)->get('staff')->result_array()[0];
             $data['userInfo'] = $this->userInfo;
            $data['base_url'] = base_url();
            $branch=$this->user_model->getbranch();
            $data['branch']=$this->user_model->getbranch();
                if($this->user_model->is_super())
                    $data['branch'] = $this->db->select("name,id")->from("branch")->get()->result_array();
            else
                $data['branch'] = $this->db->select("name,id")->from("branch")->where("id",$branch)->get()->result_array();
            
             
             $this->load->view('header',$data);
             $this->load->view('sidebar',$data);
        
             $this->load->view('staff/staff_edit',$data);


     

      
    }

    
    public function update()
    {
         if($this->input->post()){
        $data = $this->input->post();
        $db_update = $this->staff_model->update($data);
        redirect("staff/index","refresh");}
else{ redirect("staff/index","refresh"); }


     }
    public function status($q="all",$p=1)
     {
        $this->user_model->check_permissions("staff/status");
        $data['is_super'] = $this->user_model->is_super();
        $data['menu'] = $this->load_model->menu();
        $data['base_url'] = base_url();
        $data['userInfo'] = $this->userInfo;
         
        //$q = urldecode($q);
        //$p = $p<1?1:$p;
        //$per_page = 10;
        // $offset = ($p - 1) * $per_page;
        $branch=$this->user_model->getBranch();
        
        //  $sq1 = "";
        // if($q!="all")
        // {
        //     $sq1 .= "AND (firstname like '%".$q."%' OR "; 
        //     $sq1 .= "lastname like '%".$q."%' OR "; 
        //     $sq1 .= "designation like '%".$q."%' OR ";
        //     $sq1 .= "status.name like '%".$q."%' OR "; 
        //     $sq1 .= "contact like '%".$q."%' )";
        // }
        // $total = $this->db->query("SELECT count(*) as total FROM `staff` inner join `status` on staff.status = status.id where status!='0' AND staff.branch=$branch $sq1")->result_array()[0]['total'];
        //  if($total<=$offset)
        //  {
        //             $query = $this->db->query("SELECT staff.id,staff.firstname,staff.lastname,staff.designation,staff.contact,staff.qualification,staff.doj,staff.dob,staff.salery,status.name FROM `staff` inner join `status` on staff.status = status.id WHERE staff.branch = '$branch' AND status!='0' $sq1 LIMIT 0, $per_page");
        //         $p=1;
        //         }else
        $query = $this->db->query("SELECT staff.id,staff.firstname,staff.lastname,staff.designation,staff.rol,staff.dol,staff.contact,staff.qualification,staff.doj,staff.dob,staff.salery,status.name FROM `staff` inner join `status` on staff.status = status.id WHERE staff.branch = '$branch' AND status!='0'  ");//$sq1 LIMIT $offset, $per_page

        
        // $data['q'] = $q;
        // $data['curr'] = $p;
        // $data['searchq'] = $q;
        
        $data['staffs'] = $query->result_array();
        // $data['end'] = ceil($total / $per_page);
        $this->load->view('header',$data);
        $this->load->view('sidebar',$data);
        $this->load->view('staff/status',$data);


    }
    public function status_update()
    {
        if($this->input->post())
         {
           $data=$this->input->post();
           $this->staff_model->status_update($data);
           redirect('staff/status');
         }
         else
         {
           redirect('staff/status');
         }
    }
    public function rollback()
    {
        if($this->uri->segment(3))
        {
                $data = $this->uri->segment(3);
                $this->staff_model->rollback($data);
                redirect('staff/status','refresh');
         }
         else
         {
                redirect('staff/status','refresh');
            
         }       
    }
    public function staffatt_add()
    {
        $this->user_model->check_permissions("staff/staffatt_add"); 
        $data['menu'] = $this->load_model->menu();
        $data['base_url'] = base_url();
        $data['userInfo'] = $this->userInfo;
        $branchid=$this->user_model->getBranch();
        $data['staff']=$this->staff_model->all($branchid);
        $data['Attendancestatus']=$this->db->select('*')
                                           ->from('leave_types')
                                           ->where('branch',$branchid)
                                           ->order_by('id',"ASC")
                                           ->get()->result_array();
        $this->load->view('header',$data);
		$this->load->view('sidebar',$data);
        $this->load->view('staff/staffatt_add',$data);
    }
    public function staffatt_upd($id, $date, $status)
    {
        
  $data=array(
       'date'=>date('Y-m-d',strtotime($date)),
        'status_id' => $status
  );
 
        $this->db->where('id',$id);
        $s=$this->db->update('staffatt',$data);
 
        $branch=$this->user_model->getbranch();
        if($this->user_model->is_super()){
                $query = $this->db->query("SELECT staff.firstname,staff.lastname,staff.contact,staff.designation,leave_types.name as status,staffatt.id,branch.name as b_name,staffatt.date FROM `staffatt` inner join `staff` on staffatt.staff_id = staff.id inner join `leave_types` on leave_types.id = staffatt.status_id inner join `branch` on branch.id=staff.branch WHERE staff.status='0'  AND staffatt.is_deleted='0' ORDER BY date DESC");
        }
        else{
        $query = $this->db->query("SELECT staff.firstname,staff.lastname,staff.contact,staff.designation,leave_types.name as status,staffatt.id,staffatt.date FROM `staffatt` inner join `staff` on staffatt.staff_id = staff.id inner join `leave_types` on leave_types.id = staffatt.status_id  WHERE staff.branch = '$branch' and leave_types.branch = '$branch' AND staff.status='0'  AND staffatt.is_deleted='0' ORDER BY date DESC");//$sq1 LIMIT $offset, $per_page
        }
        $data['Attendancestatus']=$this->Teacher_model->AttendanceStatus();
        $record = $query->result_array();
        if(!empty($record))
         {
            $i=0; 
            foreach ($record as $key => $value)
            { $i++;
                echo "
                 <tr>
                          <td>$i</td>
                          <td>$value[firstname] "." $value[lastname]</td>
                          <td>$value[contact]</td>";
                          
                          $newdate = date("d-m-Y",strtotime($value['date']));
                          echo "<td>$newdate</td>
                          <td>$value[designation]</td>
                          <td>$value[status]</td>";
                             echo "<td>
                            <a href='' onclick='edit($value[id],event)'>
                            <i class='fa fa-edit'></i></a>";//<a href='' onclick='delete_att($value[id],event)'><i class='fa fa-trash'></a></i>
                             echo "</td>";

                      echo"</tr>";
                        } 
               
            } 
    }
    public function saveatt($p=1)
    {
        $p = explode(SALT,json_decode(base64_decode($p)))[0];
        $id=$this->input->post('staffattid',true);
        if($id>0){
            $td=$this->input->post('status',true);
             $date = date("Y-m-d", strtotime($this->input->post("date",true)));
       	    $data=array('status_id'=>$td,
               'date'=>date('Y-m-d',strtotime($date))
            );
            $check=$this->staff_model->staffattupdate($data,$id);
            if($check==true){
                redirect("staff/staffatt_view/");
                }else
                {
                    echo "Not update";
                 }
         }else
         {
            if($this->input->post())
            {
                $radio=$this->input->post('status',true);
                $date=$this->input->post('date',true);
                $dt=$this->input->post('id',true);
                foreach ($radio as $key => $value) 
                {
                        $data=array('staff_id' =>$key,
                        'status_id'=> $value,
                        'date'=>date('Y-m-d',strtotime($date))
                        );
                        $con= $this->staff_model->staffatt_save($data);
                        
                }
                if($con==true)
                {
                    redirect("staff/staffatt_view/");
                }else
                {
                    echo "not saved";
                }
            }
        }
    }
    public function staffatt_view($q="all")
    {
        $this->user_model->check_permissions("staff/staffatt_view");  
        $data['edit_delete']=$this->user_model->checkEditDelete('staff/staffatt_view');
        $data['menu'] = $this->load_model->menu();
        $total = $this->db->query("SELECT count(*) as total FROM `staffatt`")->result_array()[0]['total'];
        $branch=$this->user_model->getBranch();
        $data['base_url'] = base_url();
        $data['userInfo'] = $this->userInfo;
        
        if($this->user_model->is_super()){
                $query = $this->db->query("SELECT staff.firstname,staff.lastname,staff.contact,staff.designation,leave_types.name as status,staffatt.id,branch.name as b_name,staffatt.date FROM `staffatt` inner join `staff` on staffatt.staff_id = staff.id inner join `leave_types` on leave_types.id = staffatt.status_id inner join `branch` on branch.id=staff.branch WHERE staff.status='0'  AND staffatt.is_deleted='0' ORDER BY date DESC");
        }
        else{
        $query = $this->db->query("SELECT staff.firstname,staff.lastname,staff.contact,staff.designation,leave_types.name as status,staffatt.id,staffatt.date FROM `staffatt` inner join `staff` on staffatt.staff_id = staff.id inner join `leave_types` on leave_types.id = staffatt.status_id  WHERE staff.branch = '$branch' and leave_types.branch= '$branch' AND staff.status='0'  AND staffatt.is_deleted='0' ORDER BY date DESC");//$sq1 LIMIT $offset, $per_page
        }
        $data['statusid']=$this->db->select("*")->from('leave_types')->where('branch',$branch)->get()->result_array();
        $data['staffatt'] = $query->result_array();
        $this->load->view('header',$data);
        $this->load->view('sidebar',$data);
        $this->load->view('staff/staffatt_view',$data);
    }
    public function actions($ref='',$value=0)
    {
        //var_dump($value);die();
        if($ref=="edit"){
            $data['menu'] = $this->load_model->menu();
            $data['base_url'] = base_url();
            $data['userInfo'] = $this->userInfo;
            $data['staffatt']=$this->staff_model->staffatt_edit($value)->result_array()[0];
            $this->load->view('header',$data);
            $this->load->view('sidebar',$data);
            $data['statusid']=$this->db->select("*")->from('attendancestatus')->get()->result_array();
            $this->load->view('staff/staffatt_edit',$data);
         }else if($ref=="del")
         {
                $data['menu'] =$this->load_model->menu();
                $data['base_url'] = base_url();
                $data['userInfo'] = $this->userInfo;
                $check=$this->staff_model->staffatt_del($value);
                    if($check==true)
                    {
                        redirect("staff/staffatt_view/");
                    }else
                    {
                        echo "could not Delete";
                    }
          }
       }
       public function get_record($id, $br){
        $this->db->select('staff.firstname,staff.lastname,staff.branch,staff.contact,staff.designation,leave_types.name as status,leave_types.id as statusid ,staffatt.id,staffatt.date');    
        $this->db->from('staffatt');
        $this->db->join('staff', 'staffatt.staff_id = staff.id');
        $this->db->join('leave_types', 'leave_types.id = staffatt.status_id');
        $this->db->where('staff.branch', $br)->where('leave_types.branch', $br)->where('is_deleted',0 )->where('staffatt.id',$id);
        $query = $this->db->get()->row_array();
        echo json_encode($query);
   }
   public function delete_record($id, $br){
       $data=array('is_deleted' => 1  );
        $this->db->where('id', $id);   
        $this->db->delete('staffatt');
        
        $branch=$this->user_model->getbranch();
        if($this->user_model->is_super()){
                $query = $this->db->query("SELECT staff.firstname,staff.lastname,staff.contact,staff.designation,leave_types.name as status,staffatt.id,branch.name as b_name,staffatt.date FROM `staffatt` inner join `staff` on staffatt.staff_id = staff.id inner join `leave_types` on leave_types.id = staffatt.status_id inner join `branch` on branch.id=staff.branch WHERE staff.status='0'  AND staffatt.is_deleted='0' ORDER BY date DESC");
        }
        else{
        $query = $this->db->query("SELECT staff.firstname,staff.lastname,staff.contact,staff.designation,leave_types.name as status,staffatt.id,staffatt.date FROM `staffatt` inner join `staff` on staffatt.staff_id = staff.id inner join `leave_types` on leave_types.id = staffatt.status_id  WHERE staff.branch = '$branch' and leave_types.branch = '$branch' AND staff.status='0' AND staffatt.is_deleted='0' ORDER BY date DESC");//$sq1 LIMIT $offset, $per_page
        }
        $data['Attendancestatus']=$this->db->select('*')
                                            ->from('leave_types')
                                            ->where('branch',$branch)
                                            ->get()->result_array();
        $record = $query->result_array();
        if(!empty($record))
         {
            $i=0; 
            foreach ($record as $key => $value)
            { $i++;
                echo "
                 <tr>
                          <td>$i</td>
                          <td>$value[firstname] "." $value[lastname]</td>
                          <td>$value[contact]</td>";
                          $newdate = date("d-m-Y",strtotime($value['date']));
                         echo "<td>$newdate</td>
                          <td>$value[designation]</td>
                          <td>$value[status]</td>";
                             echo "<td>
                            <a href='' onclick='edit($value[id],event)'>
                            <i class='fa fa-edit'></i></a> <a href='' onclick='delete_att($value[id],event)'><i class='fa fa-trash'></i></a>";
                             echo "</td>";

                      echo"</tr>";
                        } 
               
            }
   }
   function check_date_att($date,$branch)
   {
       $newdate = date("Y-m-d",strtotime($date));
       //var_dump($newdate);
        $this->db->select('staffatt.*, staff.branch');
	$this->db->from('staffatt');
	$this->db->join('staff', 'staffatt.staff_id = staff.id');
	$this->db->where('date',$newdate);
	$this->db->where('branch',$branch);
	$query = $this->db->get();
	if($query->num_rows() > 0)
			{
				 //var_dump('already');die;
				 $data =  0;
			}
		else{
		    //var_dump('nahi added');
		    $data =  1;
		    }
		echo json_encode($data);
   }
}