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

class Attendance extends CI_Controller {
     public function __construct()
    {
        parent::__construct();
         $this->userInfo = $this->user_model->userInfo("first_name,last_name");
    }
    public function userInfo($c="")
	{
	    if($c=="")
            $c = "*";
        $admin = json_decode(base64_decode($this->session->admin),true);
        //var_dump($admin);
        $id = $admin['id'];
        $q = $this->db->query("SELECT $c FROM `admin` WHERE `id`='$id'");
        
        return @$q->result_array()[0];
	}
	
	public function view_leave_allocation()
	{
	    $data['menu'] = $this->load_model->menu();
        $data['base_url'] = base_url();
        $data['userInfo'] = $this->userInfo;
        $b=$this->user_model->getbranch();
        $data['general_types']=$this->db->select('*')
                                        ->from('leave_types')
                                        ->where('branch',$b)
                                        ->where('is_delete',0)
                                        ->get()->result_array();
                                        
        $teachers=$this->db->select('*')
                           ->from('leave_allocation')
                           ->where('leave_allocation.is_delete',0)
                           ->where('leave_allocation.branch',$b)
                           ->where('leave_allocation.type',"teacher")
                           ->group_by('bothid')
                           ->get()->result_array();
                           
        $staff=$this->db->select('*')
                           ->from('leave_allocation')
                           ->where('leave_allocation.is_delete',0)
                           ->where('leave_allocation.branch',$b)
                           ->where('leave_allocation.type',"staff")
                           ->group_by('bothid')
                           ->get()->result_array();      
                           
        $data['lev_type']=array_merge($teachers,$staff);                   
         
        $this->load->view('header',$data);
        $this->load->view('sidebar',$data);
        $this->load->view("attendance/view_allocation",$data);
        // $this->load->view("footer");
	}
	
	public function leave_allocation()
	{
        $data['menu'] = $this->load_model->menu();
        $data['base_url'] = base_url();
        $data['userInfo'] = $this->userInfo;
        $b=$this->user_model->getbranch();
        $data['lev_type']=$this->db->select('*')
                                   ->from('leave_types')
                                   ->where('is_delete',0)
                                   ->where('branch',$b)
                                   ->get()->result_array();
        $this->load->view('header',$data);
        $this->load->view('sidebar',$data);
        $this->load->view("attendance/leave_allocation",$data);
        $this->load->view("footer");
	}
	
	public function emp_depart($type)
    {
      
          $branch=$this->user_model->getbranch();
         if($type=="teacher") 
         {
             $dpt['cls']=$this->db->query("SELECT * FROM `teacher`
             WHERE `branch`=$branch and `status`=0 and `is_delete`=0")->result_array();
         }else
         {
             $dpt['cls']=$this->db->query("SELECT * FROM `staff` 
             WHERE `branch`=$branch and `status`=0 and `is_delete`=0")->result_array();
         }
        
       $lev_type=$this->db->select('*')
                          ->from('leave_types')
                          ->where('is_delete',0)
                          ->where('branch',$branch)
                          ->get()->result_array();              
                
            
      if(!empty($dpt['cls']))
     {             
                 
  foreach ($dpt['cls'] as $key => $value) 
        { 

  $emppp=$value['id'];  
                      
     
     echo "<tr>
        <td><input type='checkbox' name='check[$value[id]]' value='$value[id]'></td>
        <td>$value[firstname] $value[lastname]</td>";
        
         if(!empty($lev_type))
            {
              foreach($lev_type as $row)
                {
                     echo "<td>";
                     echo "<input type='number'  value='0'  name='$row[name][$value[id]][]'>";
                      echo "</td>";
                }
                echo "</tr>";
            }else
            {
                echo "</tr>";
            }
          
          
            }


             }
             echo "record not found..";
    }
    
 public function saveday()
{
if($this->input->post())
{
    $branch=$this->user_model->getbranch();
    $type=$this->input->post('ref');
   $check=$this->input->post('check',true);
   
  if(empty($check))
  {
      $this->session->set_flashdata('errmsg','Please select employee for Allocation..');
      redirect('Attendance/leave_allocation');
  }
  
  $lev_type=$this->db->select('*')
                     ->from('leave_types')
                     ->where('is_delete',0)
                     ->where('branch',$branch)
                     ->get()->result_array(); 
    
  foreach($check as $key=>$value){
      if(!empty($lev_type))
      {
          $up_status=array(
              'status'=>1
              );
        $this->db->where('type',$type)    
                 ->where('bothid',$value)
                 ->update('leave_allocation',$up_status);
          
          foreach($lev_type as $rw)
          {
            
              $lev_id=$rw['name'];
              $nme=$this->input->post($lev_id);
             
              $tot=$nme[$key][0];
              if(!empty($tot))
              {
                  $student_att=array(
                    'type'=>$type,
                	 'bothid'=>$value,
                	 'leave_id'=>$rw['id'],
                	 'branch'=>$branch,
                	 'total_leave'=>$tot
                  ); 
                  $this->db->insert('leave_allocation',$student_att);
              }
             
          }
      }
 }

redirect('Attendance/leave_allocation');

}else
{
    echo "Data not post";
}


}    
	
	public function leave_types()
	{
	   $this->user_model->check_permissions("Attendance/leave_types");
       $data['edit_delete']=$this->user_model->checkEditDelete('Attendance/leave_types');

        
       $data['is_super'] = $this->user_model->is_super();
       $data['menu'] = $this->load_model->menu();
       $b=$this->user_model->getbranch();
        
       $total = $this->db->query("SELECT count(*) as total FROM `leave_types` where branch=$b")->result_array()[0]['total'];
         if($this->user_model->is_super())
         {
            $query = $this->db->query("SELECT * FROM `leave_types` where is_delete=0");
          }else{
            $query = $this->db->query("SELECT * FROM `leave_types` where is_delete=0");
          }
        $data['base_url'] = base_url();
        $data['userInfo'] = $this->userInfo;
        $data['classes'] = $query->result_array();
                // calling view pages
        $this->load->view('header',$data);
        $this->load->view('sidebar',$data);
        $this->load->view('attendance/leave_types',$data); 
	}
	
	 public function fetch_leave(){
        
        $data['is_super'] = $this->user_model->is_super();
        $b=$this->user_model->getbranch();
        
        $total = $this->db->query("SELECT count(*) as total FROM `leave_types` where branch=$b and is_delete=0")->result_array()[0]['total'];
         if($this->user_model->is_super())
         {
            $query = $this->db->query("SELECT leave_types.* FROM `leave_types` inner join `branch` on branch.id=leave_types.branch where leave_types.is_delete=0");
          }else{
            $query = $this->db->query("SELECT * FROM `leave_types` WHERE leave_types.branch = '$b' and is_delete=0");
          }
        $record = $query->result_array();
        if(!empty($record))
         {
            $i=0; 
            foreach ($record as $key => $value)
            { $i++;
                echo "
                 <tr>
                  <td>$i</td>
                  <td>$value[name]</td>
                  <td>$value[mode]</td>
                  <td>$value[total]</td>
                  <td>";
                  echo date('d-m-Y',strtotime($value['start']));
                  echo "</td>
                  <td>";
                  echo date('d-m-Y',strtotime($value['end']));
                  echo"</td>";
                   if($this->user_model->is_super()){
                       
                            $b = $value['branch'];
                            $query = $this->db->select('name')->where('id',$b)->where('is_delete',0)->get('branch')->result_array()[0];
                    echo "<td>$query[name]</td>";
                           } 
                echo"</tr>";
                        } 
               
            }        
         
    }
    
     public function check_editclass($id,$class,$branch)
    {
    $this->db->select();
	$this->db->from('leave_types');
	$this->db->where('id!=',$id);
	$this->db->where('name',$class);
	$this->db->where('branch',$branch);
	$query = $this->db->get();
   
	if($query->num_rows() > 0)
			{
				 $data =  1;
			}
		else{
		    $data =  0;
		    }
		echo json_encode($data);
    }
    
     public function check_class($class,$branch)
    {
    $this->db->select();
	$this->db->from('leave_types');
	$this->db->where('name',$class);
	$this->db->where('branch',$branch);
	$query = $this->db->get();
	if($query->num_rows() > 0)
			{
				 $data =  1;
			}
		else{
		    $data =  0;
		    }
		echo json_encode($data);
    }
    
     public function save_leave($name,$mode,$total,$start,$branch,$end)
    {
         $myname=rawurldecode($name);
         $mymode=rawurldecode($mode);
         $mytotal=rawurldecode($total);
         $mystart=rawurldecode($start);
         $mybranch=rawurldecode($branch);
         $myend=rawurldecode($end);
	 
	        $fields_class = array(
                            'branch' => $mybranch,
                            'name' => $myname,
                            'mode' => $mymode ,
                            'start'=>$mystart,
                            'end'=>$myend,
                            'total'=>$mytotal
                );
              
              $this->db->insert('leave_types',$fields_class);
           
           //Extract  data
           
       $data['is_super'] = $this->user_model->is_super();
       $b=$this->user_model->getbranch();
        
        $total = $this->db->query("SELECT count(*) as total FROM `leave_types` where branch=$b")->result_array()[0]['total'];
         if($this->user_model->is_super())
         {
            $query = $this->db->query("SELECT * FROM `leave_types` inner join `branch` on branch.id=leave_types.branch and leave_types.is_delete=0");
          }else{
            $query = $this->db->query("SELECT * FROM `leave_types` WHERE leave_types.branch = '$b' and is_delete=0");
          }
          $record = $query->result_array();
        if(!empty($record))
         {
            $i=0; 
            foreach ($record as $key => $value)
            { $i++;
           
                echo "
                 <tr>
                          <td>$i</td>
                          <td>$value[name]</td>
                          <td>$value[mode]</td>
                          <td>$value[total]</td>
                          <td>";
                          echo date('d-m-Y',strtotime($value['start']));
                          echo "</td>
                           <td>";
                           echo date('d-m-Y',strtotime($value['end']));
                           echo "</td>";
                  if($this->user_model->is_super()){
                            $branch = $value['branch'];
                            $query = $this->db->select('name')->where('id',$branch)->where('is_delete',0)->get('branch')->result_array()[0];
                    echo "<td>$query[name]</td>";
                          } 

                      echo"</tr>";
                        } 
               
            } 
       
    }
	
	  public function getBranch()
    {
        $role = $this->userInfo('role_id')['role_id'];
        
        $branch = @$this->db->query("SELECT `branch_id` FROM `role` WHERE `id`='$role' AND `is_delete`='0'")->result_array()[0]['branch_id'];
       
        return $branch;
    }
     public function is_super()
    {
        if($this->getBranch()==0)
            return true;
        else
            return false;
    }
     public function sendDetails($name=""){
      
        $user = $this->userInfo("first_name,last_name,contact_no");
        $bid = $this->getBranch();
        
        if($this->is_super())
            $b_name = "(Super)";
        else
            $b_name = $this->db->select("name")->from("branch")->where("id",$bid)->where("is_delete","0")->get()->row()->name;
      //$api = $this->db->select("code")->from("api")->where("branch_id","1")->where("is_delete","0")->get()->row()->code;
        //$this->smsgateway->sendMessageToNumber("+923009318468","Name: ".$user['first_name']." ".$user['last_name']." | ".$user['contact_no']." with username: ".$name." of branch: ".$b_name." has logged in to panel.",$api);
        $message="Name: ".$user['first_name']." ".$user['last_name']." | ".$user['contact_no']." with username: ".$name." of branch: ".$b_name." has logged in to panel";
        //$this->hajanasms->sendOneNumber('923009318468',$message);
        
        }
        
public function login(){
   
    $u= $this->input->post('email');
   
    $p=$this->input->post('pass');
    //"shahbaz123";
    
      $pass = md5($p);
        $login = $this->db->query("SELECT * FROM `admin` WHERE `username`='$u' AND `password`='$pass' AND  is_delete='0' AND role_id > '0'")->row_array();
        if(!empty($login))
        {
            $role=$login['role_id'];
             $branch = @$this->db->query("SELECT `branch_id` FROM `role` WHERE `id`='$role' AND `is_delete`='0'")->result_array()[0]['branch_id'];
             $response=array();
            array_push($response,array("msg"=>"true","bid"=>$branch));
           
           echo json_encode($response); 
        }else
        {
             $response=array();
        array_push($response,array("msg"=>"false"));
      echo json_encode($response);
        }
}

public function getclassesfordb(){

   $data=$this->db->query("select class_name,class_id,branch from demovilla_edusol.class where is_delete=0")->result_array();
   
    $response=array();
    foreach($data as $row){
        array_push($response,array(
        "class_id"=>$row['class_id'],
        "classes"=>$row['class_name'],
         "branch"=>$row['branch'],
        )
        );
    }
    //  var_dump('<pre>',$response);
    //  die();
    echo json_encode($response);
}

public function getclasses(){
       $bid=$this->input->post('branch');
   $data=$this->db->query("select class_name,class_id from demovilla_edusol.class where is_delete=0 and branch=$bid")->result_array();
   
    $response=array();
    foreach($data as $row){
        array_push($response,array(
        "class_id"=>$row['class_id'],
        "classes"=>$row['class_name'],
        )
        );
    }
    //  var_dump('<pre>',$response);
    //  die();
    echo json_encode($response);
}

    
 
 public function getsections(){

    $class=$this->input->post('class');
    //var_dump("af");die;
    $data=$this->db->query("select section_name,section_id,class_id from demovilla_edusol.section where class_id = $class and is_delete=0")->result_array();
    $response=array();
    foreach($data as $row){
        array_push($response,array(
            "section_id"=>$row['section_id'],
        "class_id"=>$row['class_id'],
        "sections"=>$row['section_name'],
        )
        );
    }
    
    echo json_encode($response);
}

public function getsections_for_db(){

    
    //var_dump("af");die;
    $data=$this->db->query("select section_name,section_id,class_id from demovilla_edusol.section where is_delete=0")->result_array();
    $response=array();
    foreach($data as $row){
        array_push($response,array(
            "section_id"=>$row['section_id'],
        "class_id"=>$row['class_id'],
        "sections"=>$row['section_name'],
        )
        );
    }
    
    echo json_encode($response);
}

public function getsubjects(){

    $class=$this->input->post('class');
    $section=$this->input->post('section');
    
    //var_dump("af");die;
    $data=$this->db->query("select id,name from demovilla_edusol.subject where class_id=$class and section_id=$section and is_deleted=0")->result_array();
    $response=array();
    foreach($data as $row){
        array_push($response,array(
            "id"=>$row['id'],
            "subject_name"=>$row['name']
        )
        );
    }
    
    echo json_encode($response);
}



public function getsubjects_for_db(){

    
    //var_dump("af");die;
    $data=$this->db->query("select id,name,section_id,class_id from demovilla_edusol.subject where is_deleted=0")->result_array();
    $response=array();
    foreach($data as $row){
        array_push($response,array(
            "id"=>$row['id'],
            "subject_name"=>$row['name'],
        "class_id"=>$row['class_id'],
        "section_id"=>$row['section_id'],
        )
        );
    }
    
    echo json_encode($response);
}

public function getstudents(){

    $class=$this->input->post('class');
    $section  = $this->input->post('section');
    //var_dump("af");die;
    $data=$this->db->query("select student.student_name,student.grno,student.id 
                             from demovilla_edusol.student 
                            inner join demovilla_edusol.promotion on  student.id = promotion.student_id 
                            where promotion.class_id =$class and promotion.section_id =$section
    and promotion.is_active = 1 and promotion.is_delete=0 and student.status = 0 and student.is_delete = 0")->result_array();
       $response=array();
    foreach($data as $row){
        array_push($response,array(
        "id"=>$row['id'],
        "student_name"=>$row['student_name'],
        "p_no"=>$row['grno'],
 
        )
        );
    }

    echo json_encode($response);
}

public function getstudents_for_db(){

   
    //var_dump("af");die;
    $data=$this->db->query("select student.student_name,student.grno,student.id,section.section_id ,class.class_id from demovilla_edusol.student inner join demovilla_edusol.promotion on student.id = promotion.student_id inner join demovilla_edusol.section on promotion.section_id = section.section_id inner join demovilla_edusol.class on class.class_id = promotion.class_id  and student.branch=1 and promotion.is_active = 1 and promotion.is_delete=0 and student.status = 0 and student.is_delete = 0")->result_array();
   
    $response=array();
    foreach($data as $row){
        array_push($response,array(
        "id"=>$row['id'],
        "student_name"=>$row['student_name'],
        "p_no"=>$row['grno'],
        "class_id"=>$row['class_id'],
        "section_id"=>$row['section_id'],
        )
        );
    }
    
    echo json_encode($response);
}

 
public function markattendance(){
   
    $id=$this->input->post("id");
    $attend=$this->input->post("attend");
    
    $data=json_decode($id,true);
    $data1=json_decode($attend,true);
     
  
    foreach($data as $key=>$value){
        
         $response = array();
        
         $result =$this->db->query("select student.id, promotion.id as p_id,promotion.section_id as section, promotion.class_id as 
         class from demovilla_edusol.student inner join demovilla_edusol.promotion on 
         student.id = promotion.student_id where promotion.is_active = 1 and student.grno =$value[key]")->row_array();
         
          if($data1[$key]['value']="Present")
          {
              $data1[$key]['value']=1;
          }
          else if($data1[$key]['value']="Absent"){
          
              $data1[$key]['value']=2;
          }
          else{
              $data1[$key]['value']=3;
          }
          //$student['status_id'] = 'present';
          $student['student_id'] = $result['id'];
          $student['promotion_id'] = $result['p_id'];

          $student['date'] = date('Y-m-d');
          $student['status_id'] = $data1[$key]['value'];
          
         $cur_date=date('Y-m-d');
         $check=$this->db->select('*')
                         ->from('studentatt')
                         ->where('date',$cur_date)
                         ->where('student_id',$result['id'])
                         ->where('promotion_id',$result['p_id'])
                         ->where('is_deleted',0)
                         ->get()->result_array();
            
     if(empty($check))
         {
            
          $this->db->insert('demovilla_edusol.studentatt',$student);
           
          $response = 'Attendance Marked';
          //$response=$data;
            
         }else
         {
             
          $response='attendence already marked';
            
         }     
     }
     
         echo json_encode($response);
    
    
    
   }
    
    public function synchttendance(){
   
    $id=$this->input->post("id");
    $attend=$this->input->post("attend");
    
    $data=json_decode($id,true);
    $data1=json_decode($attend,true);
     
  
    foreach($data as $key=>$value){
        
         //$result = array();
         $response = array();
         /*$response = $value;
          echo json_encode($response);
          die;*/
         $result =$this->db->query("select student.id, promotion.id as p_id,promotion.section_id as section, promotion.class_id as 
         class from demovilla_edusol.student inner join demovilla_edusol.promotion on 
         student.id = promotion.student_id where promotion.is_active = 1 and student.grno =$value[key]")->row_array();
          
          //$student['student_id'] = 1;
          //$student['promotion_id'] = 2;
          //$student['date'] = '2018-1-02';
          if($data1[$key]['value']="Present")
          {
              $data1[$key]['value']=1;
          }
          else if($data1[$key]['value']="Absent"){
          
              $data1[$key]['value']=2;
          }
          else{
              $data1[$key]['value']=3;
          }
          //$student['status_id'] = 'present';
          $student['student_id'] = $result['id'];
          $student['promotion_id'] = $result['p_id'];
        //  $student['class_id'] = $result['class'];
        //  $student['section_id'] = $result['section'];
          $student['date'] = date('Y-m-d');
          $student['status_id'] = $data1[$key]['value'];
          
         $cur_date=date('Y-m-d');
         $check=$this->db->select('*')
                         ->from('studentatt')
                         ->where('date',$cur_date)
                         ->where('student_id',$result['id'])
                         ->where('promotion_id',$result['p_id'])
                         ->where('is_deleted',0)
                         ->get()->result_array();
            
     if(empty($check))
         {
            
          $this->db->insert('demovilla_edusol.studentatt',$student);
           
          $response = 'Attendance Marked';
          //$response=$data;
            
         }else
         {
             
          $response='attendence already marked';
            
         }     
     }
     
         echo json_encode($response);
    
    
    
   }

public function getstudentsattendance(){
    
    $class=$this->input->post('class');
    $section  = $this->input->post('section');
    //var_dump("af");die;
    $data=$this->db->query("select student_id,
    promotion_id,status_id from 
    demovilla_edusol.studentatt where class_id =$class
    and section_id =$section and is_deleted=0")->result_array();
       $response=array();
    foreach($data as $row){
        array_push($response,array(
        "std_id"=>$row['student_id'],
        "promotion_id"=>$row['promotion_id'],
        "status"=>$row['status_id'],
 
        )
        );
    }

    echo json_encode($response);
   
}
    
}
    

?>