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

class student extends CI_Controller {

    private $userInfo = array();
    public $branch = 0;

    public function __construct()
    {
        parent::__construct();
        $this->load->library('form_validation');
        $this->load->library('hajanasms');
        $this->load->model("user_model");
        $this->load->model("student_model");
        $this->load->model("voucher_model");
        $this->load->model("report_model");
        $this->load->model("Teacher_model");
        $this->load->model("api_model");
        $this->user_model->check_login("admin");
        $this->load->model("generic_model");
        $this->branch=$this->user_model->getbranch();
        $this->userInfo = $this->user_model->userInfo("first_name,last_name");
    }
     public function student_roll_no($class_admited=0,$section_id=0)
    {
       
           $roll_no=$this->student_model->get_student_roll_no($class_admited,$section_id);
            echo $roll_no?$roll_no->roll_no:1;
        
    }
     public function savePicture()
    {
        //set random name for the image, used time() for uniqueness

        $filename =  time() . '.jpg';
        $filepath = './images/';

        //read the raw POST data and save the file with file_put_contents()
        $result = file_put_contents( $filepath.$filename, file_get_contents('php://input') );
        if (!$result) {
            print "ERROR: Failed to write data to $filename, check permissions\n";
            exit();
        }

        echo $filepath.$filename;
    }
    
     public function web_request()
    {
                $this->user_model->check_permissions("student/web_request");
$data['edit_delete']=$this->user_model->checkEditDelete('student/web_request');
    if($this->user_model->is_super()){
        $query = $this->db->query("SELECT addmission_request.*,branch.name as b_name FROM addmission_request JOIN branch on branch.id = addmission_request.branch 
         WHERE  addmission_request.is_delete='0'");
    }
    else{
    	$b=$this->user_model->getbranch();
        $query = $this->db->query("SELECT addmission_request.*,branch.name as b_name FROM addmission_request JOIN branch on branch.id = addmission_request.branch 
         WHERE  addmission_request.is_delete='0' and addmission_request.branch = '$b'");
    }   
    $data['is_super'] = $this->user_model->is_super();
        $data['userInfo'] = $this->userInfo;
        $data['base_url'] = base_url();
        $data['student'] = $query->result_array();
	$data['menu'] = $this->load_model->menu();
        $this->load->view('header',$data);
        $this->load->view('sidebar',$data);
        $this->load->view('student/student_view_reqest',$data);
    }
    
     public function disable_form()
   {
       $data=array(
           'is_delete'=>1
           );
        
        $this->db->update('admission_disable',$data);
        redirect('student/web_request_disable');
            
   }
   
   public function enable_form()
   {
       $data=array(
           'is_delete'=>0
           );
        
        $this->db->update('admission_disable',$data);
        redirect('student/web_request_disable');
            
   }
   
    public function web_request_disable()
   {
    $this->user_model->check_permissions("student/web_request_disable");
    $data['edit_delete']=$this->user_model->checkEditDelete('student/web_request_disable');

            $query = $this->db->query("SELECT admission_disable.* FROM admission_disable");
         
    $data['is_super'] = $this->user_model->is_super();
        $data['userInfo'] = $this->userInfo;
        $data['base_url'] = base_url();
        $data['student'] = $query->result_array();
	$data['menu'] = $this->load_model->menu();
        $this->load->view('header',$data);
        $this->load->view('sidebar',$data);
        $this->load->view('student/web_request_disable',$data);
   }
   
 public function branchAttendance()
    {
        $this->user_model->check_permissions("student/branchAttendance");
        $data['menu'] = $this->load_model->menu();
        $data['base_url'] = base_url();
        $data['userInfo'] = $this->userInfo;
        
        if(!$this->user_model->is_super())
        { 
            $data['branch']=$this->user_model->getBranch(); 
         }else {
            $data['branch']=$this->student_model->getbranch()->result_array();
         }
        
        $data['Attendancestatus']=$this->Teacher_model->AttendanceStatus();
        $this->load->view('header',$data);
		$this->load->view('sidebar',$data);
        $this->load->view('student/branchatt_add',$data);
    }
     public function savebranchatt()
    {
           {
            $id=$this->input->post('studentattid',true);
            if($id>0){
                $td=$this->input->post('status',true);
                $date=$this->input->post('date',true);
                $data=array('status_id'=>$td,
                'date'=>date('Y-m-d',strtotime($date))
                );
                $check=$this->student_model->studentattupdate($data,$id);
                if($check==true){
                    redirect("student/studentatt_show/");
                }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);
                   $pres_message="Dear Parents your child is safely reached at Shah Latif Model High School.\nDate: ".$date."\nThank You\nPrincipal\nSLM 2nd shift";
                    $abs_message="Dear Parents your child is absent from Shah Latif Model High School.\nDate: ".$date."\nThank You\nPrincipal\nSLM 2nd shift";
             
                    $pres_numbers=array();
                    $abs_numbers=array();
                    $abs_student_id=array();
                    foreach($radio as $key => $value) 
                    { 
                        $promotionid=$this->student_model->promotion_id($key);
                        $student_data=$this->student_model->id($key);
                        $data=array('student_id' =>$key,
                        'promotion_id'=>$promotionid,
                        'status_id'=> $value,
                           'date'=>date('Y-m-d',strtotime($date)),
                        
                       
                        );
                        //var_dump($student_data);
                       // die();
                        
                        
                        $con= $this->student_model->studentatt_save($data);
                        if($con && $value!=4) {
                            if($value==1){
                            
                            $pres_numbers[]=$student_data['father_contact'];
                     //       $tokens[]=$student_data['token'];
                             $pres_ids[]=$student_data['stid'];}
                            elseif($value==2){
                        $abs_numbers[]=$student_data['father_contact'];
                       //    $tokens[]=$student_data['token'];
                             $abs_ids[]=$student_data['stid'];
                             }
                       }
                    }
                   // echo "<pre>";print_r($tokens);exit;
                  $msg= array();
                   $tokens=array();
                   // echo "<pre>";print_r($pres_ids);
                    //echo "<pre>";print_r($abs_ids);exit;
                   if(!empty($pres_ids)){
                    foreach($pres_ids as $ids){
                              
$tokens[]=$this->db->select('token')->from('student')->where('id',$ids)->get()->result_array()[0]['token'];
                    //echo "<pre>";print_r($tokens);exit;
                                    
  $msg = array("message" => "Dear Parents your child is safely reached at Shah Latif Model High School \nThank You\nPrincipal\nSLM","id"=>$ids,"topic"=>"attendance" );  
   $this->api_model->send_notification($tokens,$msg);
   $tokens = [];
   }
 }
 
                   if(!empty($abs_ids)){
                    foreach($abs_ids as $ids){
                              
$tokens[]=$this->db->select('token')->from('student')->where('id',$ids)->get()->result_array()[0]['token'];
                                    
  $msg = array("message" => "Dear Parents your child is absent from Shah Latif Model High School \nThank You\nPrincipal\nSLM","id"=>$ids,"topic"=>"attendance" );  
   $this->api_model->send_notification($tokens,$msg);
   $tokens = [];
   }
 }
  //var_dump($msg,$abs_ids);
 // die();

   
   
                    
                    
             
                   
                    if($this->user_model->getBranch()==2) {

                  //  	$this->hajanasms->sendManyNumber($abs_numbers,$abs_message);
                    }
                    if($con==true)
                    {
                      redirect("student/studentatt_show/");
                    }else
                    {
                        echo "not saved";
                    }
                }
            }
        }
        
    }        
      public function mark_holiday()
    {
        $this->user_model->check_permissions("student/mark_holiday");
        $data['menu'] = $this->load_model->menu();
        $data['base_url'] = base_url();
        $data['userInfo'] = $this->userInfo;
          $data['branch']=$this->student_model->getbranch()->result_array();
        
        $data['Attendancestatus']=$this->Teacher_model->AttendanceStatus();
        $this->load->view('header',$data);
	$this->load->view('sidebar',$data);
        $this->load->view('student/mark_holiday',$data);
    }
     public function save_holiday()
    {
           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('student_id' =>$key,
                        'status_id'=> $value,
                        'date'=>$date
                        );
                        $con= $this->student_model->studentatt_save($data);
                    }
                    if($con==true)
                    {
                        redirect("student/mark_holiday","refresh");
                    }else
                    {
                        echo "not saved";
                    }
                }
        }
//     public function mark_holiday()
//     {
//         $this->user_model->check_permissions("student/studentatt_add");
//          $branch = $this->user_model->getBranch();
//         $data['menu'] = $this->load_model->menu();
//         $data['base_url'] = base_url();
//         $data['userInfo'] = $this->userInfo;
        
//       if($this->user_model->is_super())    
//             $data['branch'] = $this->db->query("SELECT * FROM `branch` WHERE `is_delete`='0'")->result_array();
//         else
//             $data['branch'] = $this->db->query("SELECT * FROM `branch` WHERE `is_delete`='0' AND `id`='$branch'")->result_array(); 
        
//         $data['Attendancestatus']=$this->Teacher_model->AttendanceStatus();
//         $this->load->view('header',$data);
// 		$this->load->view('sidebar',$data);
//         $this->load->view('student/mark_holiday',$data); 
//     }
//      public function save_holiday()
//     {
//         if($this->input->post())
//         {

//             $data = $this->input->post();
//             $db_insert = $this->student_model->save_holiday($data);
//             redirect("student/mark_holiday","refresh");
               
//         }
//         else
//         {
//             redirect("student/mark_holiday","refresh");

//         }
//     }
    
     public function show_holiday()
    {
        $this->user_model->check_permissions("student/show_holiday");
// $data['edit_delete']=$this->user_model->checkEditDelete('student/show');
    if($this->user_model->is_super()){
        $query = $this->db->query("SELECT holiday.*,class.class_name,branch.name as b_name FROM holiday JOIN branch on branch.id = holiday.branch_id  JOIN class ON class.class_id=holiday.class_id  WHERE class.is_delete=0 ");
    }
    else{
    	$b=$this->user_model->getbranch();
        $query = $this->db->query("SELECT holiday.*,class.class_name,section.section_name,branch.name as b_name FROM holiday JOIN branch on branch.id = holiday.branch_id  JOIN class ON class.class_id=holiday.class_id JOIN section ON section.section_id=holiday.section_id  WHERE class.is_delete=0 and section.is_delete=0 ");
       $data['branch']=$this->db->select("*")->from("branch")->where('id',$b)->get()->result_array();
    }   
    $data['is_super'] = $this->user_model->is_super();
        $data['userInfo'] = $this->userInfo;
        $data['base_url'] = base_url();
        $data['student'] = $query->result_array();
	$data['menu'] = $this->load_model->menu();
        $this->load->view('header',$data);
        $this->load->view('sidebar',$data);
        $this->load->view('student/show_holiday',$data);
    }

    public function index($date='')
    {
        $this->user_model->check_permissions("student/index");
        $data['menu'] = $this->load_model->menu();
        $data['base_url'] = base_url();
         $data['branch'] = $this->user_model->getbranch();
        $data['userInfo'] = $this->userInfo;
        if($date==''){
              $date = date('d-m-Y');  
            }
            $data['date'] = $date;
        // $this->db->select("grno");
        // $this->db->limit(2);
        // $this->db->order_by('id', 'DESC');
        // $data['last_grno']=$this->db->get('student')->row()->grno;
        $data['is_super'] = $this->user_model->is_super();
        $this->load->view('header',$data);
        $this->load->view('sidebar',$data);
        $this->load->view('student/student_add',$data);
    }
    
        public function add_student_info($date='')
    {
        $this->user_model->check_permissions("student/index");
        $data['menu'] = $this->load_model->menu();
        $data['base_url'] = base_url();
         $data['branch'] = $this->user_model->getbranch();
        $data['userInfo'] = $this->userInfo;
        if($date==''){
              $date = date('d-m-Y');  
            }
            $data['date'] = $date;
        // $this->db->select("grno");
        // $this->db->limit(2);
        // $this->db->order_by('id', 'DESC');
        // $data['last_grno']=$this->db->get('student')->row()->grno;
        $data['is_super'] = $this->user_model->is_super();
        $this->load->view('header',$data);
        $this->load->view('sidebar',$data);
        $this->load->view('student/add_student_info',$data);
    }
    
    
    
     public function check_useredit($id,$sid,$br)
    {
     
    $this->db->select();
	$this->db->from('student');
	$this->db->where('id!=',$id);
	$this->db->where('sid',$sid);
	$this->db->where('branch',$br);
	$this->db->where('is_delete',0);
	$query = $this->db->get();
	
   
	if($query->num_rows() > 0)
			{
				 
				 $data =  1;
			}
		else{
		   
		    $data =  0;
		    }
		echo json_encode($data);
    }
    
    
    public function check_user($sid,$br)
    {
    $this->db->select();
	$this->db->from('student');
	$this->db->where('sid',$sid);
	$this->db->where('branch',$br);
	$this->db->where('is_delete',0);
	$query = $this->db->get();
   
	if($query->num_rows() > 0)
			{
				 
				 $data =  1;
			}
		else{
		   
		    $data =  0;
		    }
		echo json_encode($data);
    }
    
    	public function email() {
    
    $config = Array(
    'protocol' => 'smtp',
    'smtp_host' => 'smtp.gmail.com',
    'smtp_port' => 465,
    $config['smtp_user'] = "samali2448@gmail.com",
    $config['smtp_pass'] = "SuperNational1993",
    'mailtype'  => 'html', 
    'charset'   => 'iso-8859-1'
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");

  $this->email->from("shahidamin1515@gmail.com", "sam ali");
    $this->email->to("samali2448@gmail.com"); 
   // $msg= $this->load->view('Check',array(),TRUE);
    $this->email->subject("None");
    $this->email->message("hellow");
$result = $this->email->send();
  var_dump($result); die();
    }
	
    
    public function ip() 
    {    
        $data = "include zklibrary.php";
        $this->load->view('student/test',$data);
        
        
    }
    
    public function section_wise_form()
    {
      //  $this->user_model->check_permissions("SmsHajana/section_wise_form");
        $branch = $this->user_model->getBranch();
        $data['is_super'] = $this->user_model->is_super();
        $data['menu'] = $this->load_model->menu(); 
        $data['base_url'] = base_url();
        $data['userInfo'] = $this->userInfo;
        if($this->user_model->is_super())    
            $data['branch'] = $this->db->query("SELECT * FROM `branch` WHERE `is_delete`='0'")->result_array();
        else
            $data['branch'] = $this->db->query("SELECT * FROM `branch` WHERE `is_delete`='0' AND `id`='$branch'")->result_array();
        $this->load->view('header',$data);
		$this->load->view('sidebar',$data);
        $this->load->view('student/notice',$data);
    }
    public function save_notice()
    {
    	$data= $this->input->post();
    	 $count = count($data['students']);
          for ($i = 0; $i < $count; $i++) {
          $data['students'][$i];
              
                    
                    $paid   = array (
                    'branch_id'           =>$data['branch'],
                    'class_id'           =>$data['class'],
                    'section_id' =>$data['section'],
                    'student_id' =>$data['students'][$i],
                    'notice'   => $data['msg']
                    );

                    $this->db->insert('student_notice',$paid); 
                      redirect("student/section_wise_form","refresh");
          
          }
    }
    public function view_notice()
    {
     
    $b=$this->user_model->getbranch();
     $query = $this->db->query("SELECT student.*,class.*,section.*,student.id as stid,student_notice.* FROM student_notice JOIN student ON student.id=student_notice.student_id JOIN promotion ON promotion.student_id=student_notice.student_id JOIN class ON promotion.class_id=class.class_id JOIN section ON promotion.section_id=section.section_id WHERE student.branch = '$b' AND student.status='0' AND student.is_delete='0' AND promotion.is_active='1' and class.is_delete=0 and section.is_delete=0");
      $data['base_url'] = base_url();
        $data['userInfo'] = $this->userInfo;
       $data['branch']=$this->db->select("*")->from("branch")->where('id',$b)->get()->result_array();
    
        $data['student'] = $query->result_array();
	$data['menu'] = $this->load_model->menu();
        $this->load->view('header',$data);
        $this->load->view('sidebar',$data);
        $this->load->view('student/view_notice',$data);

    }
    
     public function studentatt_sp()
    {
        $this->user_model->check_permissions("student/studentatt_add");
        $data['menu'] = $this->load_model->menu();
        $data['base_url'] = base_url();
        $data['userInfo'] = $this->userInfo;
        
        if(!$this->user_model->is_super())
        { 
            $data['branch']=$this->user_model->getBranch(); 
         }else {
            $data['branch']=$this->student_model->getbranch()->result_array();
         }
        
        $data['Attendancestatus']=$this->Teacher_model->AttendanceStatus();
        $this->load->view('header',$data);
		$this->load->view('sidebar',$data);
        $this->load->view('student/customatt',$data);
    }
    
    
       public function saveatt_custm()
    {
        
            $id=$this->input->post('mystudents',true);
         
                $st=$this->input->post('status',true);
                
                 $date = date("Y-m-d", strtotime($this->input->post("mydate",true)));
               
                    $pres_message="Dear Parents your child is safely reached at  Thank You Principal SLM";
                    $abs_message="Dear Parents your child is absent from SLM High School  Thank You Principal SLM";
             
                    $pres_numbers=array();
                    $abs_numbers=array();
                    if(!empty($id))
                    {

                    foreach ($id as $key => $value) 
                    { 
                 
                        $promotionid=$this->student_model->promotion_id($value);
                        $student_data=$this->student_model->id($value);
                        $data=array('student_id' =>$value,
                        'promotion_id'=>$promotionid,
                        'status_id'=> $st,
                        'date'=>$date
                        );
                        
                        $con= $this->student_model->studentatt_save($data);
                 
                        if($con=="true") {
                            if($st==1)
                            {
                              
                              $pres_numbers[]=$student_data['father_contact'];
                             
                            }
                            else{
                              if($st==2)
                              {
                               $abs_numbers[]=$student_data['father_contact'];
                              }
                           
                            }
                            
                           
                         }
                                            
                                             
              
                    }
                    //var_dump($pres_numbers);
                   // var_dump($abs_numbers);
                   // die();
    }
                  
                    //  	$this->hajanasms->sendManyNumber($pres_numbers,$pres_message);
                    //   $this->hajanasms->sendManyNumber($abs_numbers,$abs_message);
                    
                    if($con==true)
                    {
                      redirect("student/studentatt_sp/");
                    }else
                    {
                        echo "not saved";
                    }
                
            
        }
        
     public  function getMacLinux() {
   ob_start();  

//Get the ipconfig details using system commond  
system('ipconfig /all');  

// Capture the output into a variable  
$mycomsys=ob_get_contents();  

// Clean (erase) the output buffer  
ob_clean();  

$find_mac = "Physical"; 
//find the "Physical" & Find the position of Physical text  

$pmac = strpos($mycomsys, $find_mac);  
// Get Physical Address  

$macaddress=substr($mycomsys,($pmac+36),17);  
//Display Mac Address  

echo $macaddress; 
}
  
    
    
    
    
    public function view_single_notice()
    {
    
     $b=$this->user_model->getbranch();
    $id = $this->uri->segment(3);
      $query = $this->db->query("SELECT student.*,class.*,section.*,student.id as stid,student_notice.* FROM student_notice JOIN student ON student.id=student_notice.student_id JOIN promotion ON promotion.student_id=student_notice.student_id JOIN class ON promotion.class_id=class.class_id JOIN section ON promotion.section_id=section.section_id WHERE student.branch = '$b' and student_notice.student_id=$id AND student.status='0' AND student.is_delete='0' AND promotion.is_active='1' and class.is_delete=0 and section.is_delete=0"); 
        $data['student'] = $query->row_array();
      
        
        $data['menu'] = $this->load_model->menu();
        $data['base_url'] = base_url();
        $data['userInfo'] = $this->userInfo;
        //var_dump($studentinfo);die();
        $this->load->view('header',$data);
        $this->load->view('sidebar',$data);
        $this->load->view('student/single_notice',$data); 
    	
    }
    public function Card_students()
    {
     
        //load library
		 $this->load->library('zend');
		//load in folder Zend
		 $this->zend->load('Zend/Barcode');
        $classid=$this->input->post('class');
       // var_dump($classid); die();
        //$branchid= $this->user_model->getBranch();
        $branchid=$this->input->post('branch');
        //var_dump($branchid);
        //var_dump($classid);die;
        $data['menu'] = $this->load_model->menu();
        $data['base_url'] = base_url();
        $data['userInfo'] = $this->userInfo;
      // $data["student"]=$this->generic_model->getAllRecords("student",array("is_delete"=>0,"status"=>0,"branch"=>$branchid),"id","DESC");
        $data["student"]=$this->generic_model->getStudentCard($classid,$branchid);
//var_dump($data["student"]);
//die();
         //foreach ($data["student"] as $k => $v) {
          //  $imageResource = Zend_Barcode::draw(
            //    'code39', 'image', array('text'=>$v['sid'],'barHeight'=> 30,'factor'=>1.1), array()
          //  );

            // header('Content-Type: image/png');
           //  imagepng($imageResource,'./assets/barcodes/'.$v['sid'].'.png');
       // }
       
        $this->load->view('header',$data);
        $this->load->view('sidebar',$data);
        $this->load->view('student/cards_student',$data);
    }
    
      public function smslogs()
   {
            $b = $this->user_model->getbranch();
            $data['branch']=$this->db->where('id',$b)->get('branch')->result_array();
            $cSession = curl_init(); 
            //step2
            curl_setopt($cSession,CURLOPT_URL,"http://softvilla.com.pk/api/public/smslog/Softvilla");
            curl_setopt($cSession,CURLOPT_RETURNTRANSFER,true);
            curl_setopt($cSession,CURLOPT_HEADER, false); 
            //step3
            $result=curl_exec($cSession);
            //step4
            curl_close($cSession);
            //step5
            //var_dump($result); die();
            
            $data['sms']=json_decode($result);
           // var_dump($data['sms']); die();
            
            $branchid= $this->user_model->getBranch();
            $data['menu'] = $this->load_model->menu();
            $data['base_url'] = base_url();
            $data['userInfo'] = $this->userInfo;
            $this->load->view('header',$data);
            $this->load->view('sidebar',$data);
            $this->load->view('student/smslogs',$data);

   }
   
       function randomPassword() {
        $alphabet = 'abcdefghijklmnopqrstuvwxyz1234567890';
        $pass = array(); //remember to declare $pass as an array
        $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
        for ($i = 0; $i < 5; $i++) {
            $n = rand(0, $alphaLength);
            $pass[] = $alphabet[$n];
        }
        return implode($pass); //turn the array into a string
    }
    
     public function delete_student($id){
         $data = [
            'is_delete' => '1',
        ];
        $this->db->where('sid', $id);
        $this->db->update('student', $data);
        redirect("student/show","refresh");
     }
    public function show()
    {
        // $students=$this->db->select('id')
        //                   ->from('student')
        //                   ->where('is_delete',0)
        //                   ->where('status',0)
        //                   ->where('branch',1)
        //                   ->get()->result_array();
                          
    //   var_dump('<pre>',$students);
    //   die();
    //   if(!empty($students))
    //   {
    //       foreach($students as $row)
    //       {
    //           $student_id=$row['id'];
    //           $password=$this->randomPassword();

    //           $student_up = array(
    //                 'password'=>md5($password),
    //                 'ch_sh_pas'=>$password    
    //              ); 
                 
    //               $this->db->where('student_id',$student_id)
    //                         ->update('admin',$student_up);
              
               
    //       }
    //   }
       
        $this->user_model->check_permissions("student/show");
$data['edit_delete']=$this->user_model->checkEditDelete('student/show');
    if($this->user_model->is_super()){
        $query = $this->db->query("SELECT student.*,class.*,section.*,status.*,branch.name as b_name,student.id as stid FROM student JOIN branch on branch.id = student.branch JOIN promotion ON promotion.student_id=student.id JOIN class ON promotion.class_id=class.class_id JOIN section ON promotion.section_id=section.section_id LEFT JOIN `status` on student.status = status.id WHERE (student.status='0' || student.status='44') and student.is_delete='0' AND promotion.is_active='1'  AND promotion.is_delete='0' and student.is_delete='0' and class.is_delete=0 and section.is_delete=0 ORDER BY stid DESC");
    }
    else{
    	$b=$this->user_model->getbranch();
        $query = $this->db->query("SELECT student.*,class.*,section.*,status.*,branch.name as b_name,student.id as stid FROM student JOIN branch on branch.id = student.branch  JOIN promotion ON promotion.student_id=student.id JOIN class ON promotion.class_id=class.class_id JOIN section ON promotion.section_id=section.section_id LEFT JOIN `status` on student.status = status.id WHERE (student.status='0' || student.status='44') and student.branch = '$b' and student.is_delete='0' AND promotion.is_active='1' and class.is_delete=0 and section.is_delete=0 ORDER BY stid DESC");
       $data['branch']=$this->db->select("*")->from("branch")->where('id',$b)->get()->result_array();
    }   
    $data['is_super'] = $this->user_model->is_super();
        $data['userInfo'] = $this->userInfo;
        $data['base_url'] = base_url();
        $data['student'] = $query->result_array();
	$data['menu'] = $this->load_model->menu();
        $this->load->view('header',$data);
        $this->load->view('sidebar',$data);
        $this->load->view('student/student_view',$data);
    }

   public function save()
    {

        $this->form_validation->set_rules('sid','SID','required|alpha_numeric|is_unique[student.sid]');
        $this->form_validation->set_message('is_unique', 'The %s is already taken. Try again and fill the form');
        
        //////////////          yahan se comment kiya abi validations ki waja se if/else condition.student ni add horha tha due to validatoions      //////////////////
        
        //if($this->form_validation->run() == TRUE) 
        //{
        
        if(isset($data['webcam_pic'])){
                $url=$data['webcam_pic'];
            }else{
                $url = $this->do_upload();  
            }
            
            $url = $this->do_upload();
            //var_dump($url);die;
            $this->load->library('upload');
            $data = $this->input->post();
              
            $db_insert = $this->student_model->save($data,$url);
            if($db_insert){
            //echo "Hello";exit;
            $this->session->set_flashdata('feedback','Student Registered Successfully');
            $this->session->set_flashdata('feedback_class','alert-success');
            //redirect("voucher/view/".base64_encode(json_encode($db_insert.SALT)),"refresh");
            
            redirect("student/index","refresh");
            }
        //}
        // else{
        //     echo 'error';die();
        //     $this->session->set_flashdata('feedback_failed','Student Failed to Registered. Please try Again..!!!');
        //     $this->session->set_flashdata('feedback_error','alert-danger');
        //     redirect("student/show","refresh");
        //  }
    }
    
      public function save_short_info()
    {

        $this->form_validation->set_rules('sid','SID','required|alpha_numeric|is_unique[student.sid]');
        $this->form_validation->set_message('is_unique', 'The %s is already taken. Try again and fill the form');
        
        
        if(isset($data['webcam_pic'])){
                $url=$data['webcam_pic'];
            }else{
                $url = $this->do_upload();  
            }
            
            $url = $this->do_upload();
            //var_dump($url);die;
            $this->load->library('upload');
            $data = $this->input->post();
              
            $db_insert = $this->student_model->save_short_info($data,$url);
            if($db_insert){
            //echo "Hello";exit;
            $this->session->set_flashdata('feedback','Student Registered Successfully');
            $this->session->set_flashdata('feedback_class','alert-success');
           // redirect("voucher/view/".base64_encode(json_encode($db_insert.SALT)),"refresh");
            redirect("student/add_student_info","refresh");
            }
    }
    
    
    
  public function saveimg()
    {
    //    $result=checkModu
        $this->load->model('generic_model');
  //      $id=decode_uri($this->uri->segment(2));
//        $goTOPage=($this->uri->segment(1));
        //echo $goTOPage; die();
                    $data["img"]=$this->input->post('img');
  //                  $data["price"]=$this->input->post('price');
//                    $data["description"]=$this->input->post('description');

    //                $data["modifiedAt"]=date("Y-m-d h:i:sa");
     //               $data["modifiedBy"]=$this->session->userdata('dekho_userId');
//print_r($data);die();
            $this->generic_model->updateRecord("student",$data,array("id"=>$id));
            $this->session->set_flashdata('success', "price record has been updated successfully");
                    redirect('listpricev');
       
       
    }   
    
    
    
    
    
    
    private function do_upload()
    {
        $type = explode('.', $_FILES["pic"]["name"]);
        $type = $type[count($type)-1];
        $url = "uploads/".uniqid(rand()).'.'.$type;
        if (in_array($type, array("png","jpg","jpeg","gif")))
            if(move_uploaded_file($_FILES["pic"]["tmp_name"], $url))
                return $url;
        return ""; 
    }

  public function edit($id="")
    {
        $data['menu'] = $this->load_model->menu();
        //$id = explode(SALT,json_decode(base64_decode($this->uri->segment(3))))[0];
        $data['val']= $this->student_model->id($id);
        $data['userInfo'] = $this->userInfo;
        $data['base_url'] = base_url();
        $this->load->view('header',$data);
        $this->load->view('sidebar',$data);
        $this->load->view('student/student_edit',$data);  
    }


     public function update()
    {
        $data = $this->input->post();
        // echo "<pre>";print_r($data);die;
        $url = $this->do_upload();
        $this->load->library('upload');
        $check = $this->student_model->update($data,$url);
        if($check==true){
       redirect("student/show","refresh");
        }
       else{echo "Not Save Data";}
    }
  
    public function student_info($sid="")
    {
            $id=$sid;
        $data['studentinfo']=$this->student_model->student_infor($id);
        
        $data['menu'] = $this->load_model->menu();
        $data['base_url'] = base_url();
        $data['userInfo'] = $this->userInfo;
        //var_dump($data['studentinfo']);die();
        $this->load->view('header',$data);
        $this->load->view('sidebar',$data);
        $this->load->view('student/student_info',$data);   
    }
     public function studentatt_add()
    {
        $this->user_model->check_permissions("student/studentatt_add");
        $data['menu'] = $this->load_model->menu();
        $data['base_url'] = base_url();
        $data['userInfo'] = $this->userInfo;
        
        if(!$this->user_model->is_super())
        { 
            $data['branch']=$this->user_model->getBranch(); 
         }else {
            $data['branch']=$this->student_model->getbranch()->result_array();
         }
        
        $data['Attendancestatus']=$this->Teacher_model->AttendanceStatus();
        $this->load->view('header',$data);
		$this->load->view('sidebar',$data);
        $this->load->view('student/studentatt_add',$data);
    }

 public function saveatt()
    {
            $id=$this->input->post('studentattid',true);
            if($id>0){
                $td=$this->input->post('status',true);
                $date=$this->input->post('date',true);
                $data=array('status_id'=>$td,
                'date'=>date('Y-m-d',strtotime($date))
                );
                $check=$this->student_model->studentattupdate($data,$id);
                if($check==true){
                    redirect("student/studentatt_show/");
                }else
                {
                    echo "Not update";
                }
            }
            else {
                if($this->input->post())
                {
                    $b = $this->user_model->getBranch();
                    $b_name = $this->db->select('name')->where('id',$b)->get('branch')->row()->name;
                    $radio=$this->input->post('status',true);
                    $date=$this->input->post('date',true);
                    $dt=$this->input->post('id',true);
                    $pres_message="Dear Parents your child is safely reached at School.\nDate: ".$date."\nThank You\nPrincipal\n$b_name";
                    // $abs_message="Dear Parents your child is absent from School.\nDate: ".$date."\nThank You\nPrincipal\n$b_name";
                    $abs_message = "Dear Parents,\nWe hope that your child is healthy and well as he/she has not come to the school today \nDate: ".$date.".\nThank You,Principal\n$b_name"; 
                    $lve_message="Dear Parents your child is on leave from School.\nDate: ".$date."\nThank You\nPrincipal\n$b_name";
             
                    $pres_numbers=array();
                    $abs_numbers=array();
                    $lve_numbers=array();
                    $abs_student_id=array();
                    $lve_student_id=array();
                    foreach($radio as $key => $value) 
                    { 
                        $promotionid=$this->student_model->promotion_id($key);
                        $student_data=$this->student_model->id($key);
                        $data=array('student_id' =>$key,
                        'promotion_id'=>$promotionid,
                        'status_id'=> $value,
                           'date'=>date('Y-m-d',strtotime($date)),
                        
                       
                        );
                        //var_dump($student_data);
                       // die();
                        
                        
                        $con= $this->student_model->studentatt_save($data);
                        if($con && $value!=4) {
                            if($value==1){
                            
                            $pres_numbers[]=$student_data['father_contact'];
                     //       $tokens[]=$student_data['token'];
                             $pres_ids[]=$student_data['stid'];}
                            elseif($value==2){
                        
                         $abs_numbers[]=$student_data['father_contact'];
                             $abs_ids[]=$student_data['stid'];
                      }
                             elseif($value==3){
                        $lve_numbers[]=$student_data['father_contact'];
                       //    $tokens[]=$student_data['token'];
                             $lve_ids[]=$student_data['stid'];
                             }
                       }
                    }
                
                   // echo "<pre>";print_r($tokens);exit;
                  $msg= array();
                   $tokens=array();
                   // echo "<pre>";print_r($pres_ids);
                    //echo "<pre>";print_r($abs_ids);exit;
                   if(!empty($pres_ids)){
                    foreach($pres_ids as $ids){
                              
$tokens[]=$this->db->select('token')->from('student')->where('id',$ids)->get()->result_array()[0]['token'];
                    //echo "<pre>";print_r($tokens);exit;
                                    
  $msg = array("message" => "Dear Parents your child is safely reached at School. \nThank You\nPrincipal\n$b_name","id"=>$ids,"topic"=>"attendance" );  
   $this->api_model->send_notification($tokens,$msg);
   $tokens = [];
   }
 }
 
                   if(!empty($abs_ids)){
                    foreach($abs_ids as $ids){
                              
$tokens[]=$this->db->select('token')->from('student')->where('id',$ids)->get()->result_array()[0]['token'];
                                    
  $msg = array("message" => "Dear Parents your child is absent from School. \nThank You\nPrincipal\n$b_name","id"=>$ids,"topic"=>"attendance" );  
   $this->api_model->send_notification($tokens,$msg);
   $tokens = [];
   }
 }
 
                  if(!empty($lve_ids)){
                    foreach($lve_ids as $ids){
                              
$tokens[]=$this->db->select('token')->from('student')->where('id',$ids)->get()->result_array()[0]['token'];
                                    
  $msg = array("message" => "Dear Parents your child is on leave from School. \nThank You\nPrincipal\n$b_name","id"=>$ids,"topic"=>"attendance" );  
   $this->api_model->send_notification($tokens,$msg);
   $tokens = [];
   }
 }
  //var_dump($msg,$abs_ids);
 // die();
                    $check = @$this->db->select('is_permit')->where('id',6)->get('tsms_permission')->row()->is_permit;
                    if($check==1){
                     	$this->hajanasms->sendManyNumber($pres_numbers,$pres_message);
                    }
                    
                $check = @$this->db->select('is_permit')->where('id',7)->get('tsms_permission')->row()->is_permit;
                    if($check==1){
                        $this->hajanasms->sendManyNumber($abs_numbers,$abs_message);
                        }
                   
                    $check = @$this->db->select('is_permit')->where('id',8)->get('tsms_permission')->row()->is_permit;
                    if($check==1){
                        $this->hajanasms->sendManyNumber($lve_numbers,$lve_message);
                    }
                    if($con==true)
                    {
                      redirect("student/studentatt_show/");
                    }else
                    {
                        echo "not saved";
                    }
                }
            }
        }    
        
        
    public function studentatt_show()
    {
        //  $students=$this->db->select('student.student_name,class_name,section_name,student.id')
        //                     ->from('student')
        //                     ->join('promotion','promotion.student_id=student.id')
        //                     ->join('class','class.class_id=promotion.class_id')
        //                     ->join('section','section.section_id=promotion.section_id')
        //                     ->where('student.status',0)
        //                     ->where('student.branch',2)
        //                     ->where('student.is_delete',0)
        //                     ->where('promotion.is_active',1)
        //                     ->where('promotion.is_delete',0)
        //                     ->get()->result_array();
        // foreach($students as $row)
        // {
        //     $validator=$this->db->select('*')
        //                         ->from('studentatt')
        //                         ->where('student_id',$row['id'])
        //                         ->where('studentatt.date',"2019-08-19")
        //                         ->get()->row_array();
        //   if(empty($validator))  
        //   {
        //       echo $row['student_name']."-".$row['class_name']."-".$row['section_name'];
        //       echo "<br>";
        //   }
        // }
        //   die();  
        
        $this->user_model->check_permissions("student/studentatt_show");
        $data['menu'] = $this->load_model->menu();
        $branch=$this->user_model->getBranch();
        $data['base_url'] = base_url();
        $data['userInfo'] = $this->userInfo;
        $week_date = date('Y-m-d',strtotime('-7 days'));
         if(!$this->user_model->is_super()){ 
           $teacher_id =$this->user_model->userInfo('teacher_id')['teacher_id'];
          if($teacher_id>0)
          {
              $cls_inchrg=$this->db->select('*')
                                   ->from('teacher')
                                   ->where('id',$teacher_id)
                                   ->get()->row_array();
                if(!empty($cls_inchrg['class_incharge']))  
                {
                    $cc_ls=$cls_inchrg['class_incharge'];
                     $query = $this->db->query("SELECT student.student_name,student.sid,student.roll_no,class.class_name,section.section_name,studentatt.date,studentatt.id,
         attendancestatus.status FROM `studentatt` inner join `student` on studentatt.student_id = student.id inner join `promotion` on promotion.student_id = student.id
         inner join `class` on promotion.class_id = class.class_id  inner join `section` on promotion.section_id = section.section_id
         inner join `attendancestatus` on attendancestatus.id = studentatt.status_id inner join `teacher` on teacher.class_incharge = class.class_id  WHERE studentatt.date >= '$week_date' AND is_deleted='0' 
         AND is_active='1' AND student.branch='$branch' AND promotion.class_id='$cc_ls' Order by date desc"); 
                }else
                {
                     $query = $this->db->query("SELECT student.student_name,student.sid,student.roll_no,class.class_name,section.section_name,studentatt.date,studentatt.id,
         attendancestatus.status FROM `studentatt` inner join `student` on studentatt.student_id = student.id inner join `promotion` on promotion.student_id = student.id
         inner join `class` on promotion.class_id = class.class_id  inner join `section` on promotion.section_id = section.section_id
         inner join `attendancestatus` on attendancestatus.id = studentatt.status_id  WHERE studentatt.date >= '$week_date' AND is_deleted='0' 
         AND is_active='1' AND student.branch='$branch' Order by date desc"); 
                }
              
          }else
          {
             $query = $this->db->query("SELECT student.student_name,student.sid,student.roll_no,class.class_name,section.section_name,studentatt.date,studentatt.id,
         attendancestatus.status FROM `studentatt` inner join `student` on studentatt.student_id = student.id inner join `promotion` on promotion.student_id = student.id
         inner join `class` on promotion.class_id = class.class_id  inner join `section` on promotion.section_id = section.section_id
         inner join `attendancestatus` on attendancestatus.id = studentatt.status_id  WHERE studentatt.date >= '$week_date' AND is_deleted='0' 
         AND is_active='1' AND student.branch='$branch' Order by date desc");  
          }
        
         }
         if($this->user_model->is_super()){ 
             $query = $this->db->query("SELECT student.student_name,student.sid,student.roll_no,branch.name as b_name,class.class_name,section.section_name,studentatt.date,studentatt.id,
         attendancestatus.status FROM `studentatt` inner join `student` on studentatt.student_id = student.id inner join `promotion` on promotion.student_id = student.id
         inner join `class` on promotion.class_id = class.class_id  inner join `section` on promotion.section_id = section.section_id
         inner join `attendancestatus` on attendancestatus.id = studentatt.status_id
         inner join `branch` on branch.id = student.branch WHERE studentatt.date >= '$week_date' AND is_deleted='0' 
         AND is_active='1' Order by date desc ");
         }
            $data['statusid']=$this->db->select("*")->from('attendancestatus')->get()->result_array();
            $data['studentatt'] = $query->result_array();
            // var_dump($data['studentatt']);die;
            $this->load->view('header',$data);
            $this->load->view('sidebar',$data);
            $this->load->view('student/studentatt_show',$data);
        
        }
        
        
            
    public function my_attendance(){
        
        $data['menu'] = $this->load_model->menu();
        $data['base_url'] = base_url();
        $data['userInfo'] = $this->userInfo;
        $week_date = date('Y-m-d',strtotime('-7 days'));
        $data['studentatt'] = array();
        $student_id =$this->user_model->userInfo('student_id')['student_id'];
        if($student_id>0){
            $query = $this->db->query("SELECT student.student_name,student.sid,student.roll_no,branch.name as b_name,class.class_name,section.section_name,studentatt.date,studentatt.id,
            attendancestatus.status FROM `studentatt` inner join `student` on studentatt.student_id = student.id inner join `promotion` on promotion.student_id = student.id
            inner join `class` on promotion.class_id = class.class_id  inner join `section` on promotion.section_id = section.section_id
            inner join `attendancestatus` on attendancestatus.id = studentatt.status_id 
            inner join `branch` on branch.id = student.branch WHERE studentatt.date >= '$week_date' AND is_deleted='0' 
            AND is_active='1' AND student.id='$student_id' Order by date desc");  
            $data['studentatt'] = $query->result_array();
        }
        $data['statusid']=$this->db->select("*")->from('attendancestatus')->get()->result_array();
        // var_dump($data['studentatt']);die;
        $this->load->view('header',$data);
        $this->load->view('sidebar',$data);
        $this->load->view('student/my_att_show',$data);
    
    }
        
        
        public function studentatt_showw_old2($q="all",$p=1)
        {
               $this->user_model->check_permissions("student/studentatt_show");
            $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 (student.sid like '%".$q."%' OR "; 
            $sq1 .= "student.student_name like '%".$q."%' OR "; 
            $sq1 .= "class.class_name like '%".$q."%' OR ";
            $sq1 .= "section.section_name like '%".$q."%' OR ";  
            $sq1 .= "attendancestatus.status like '%".$q."%' )";
        }
        $total = $this->db->query("SELECT count(*) as total FROM `studentatt` inner join `student` on studentatt.student_id = student.id inner join `promotion` on promotion.student_id = student.id inner join `class` on promotion.class_id = class.class_id  inner join `section` on promotion.section_id = section.section_id inner join `attendancestatus` on attendancestatus.id = studentatt.status_id  WHERE is_deleted='0' AND promotion.is_active='1' AND student.branch='$branch'  $sq1")->result_array()[0]['total'];
         if($total<=$offset)
         {
                    $query = $this->db->query("SELECT student.student_name,student.sid,student.roll_no,class.class_name,section.section_name,studentatt.date,studentatt.id,attendancestatus.status FROM `studentatt` inner join `student` on studentatt.student_id = student.id inner join `promotion` on promotion.student_id = student.id inner join `class` on promotion.class_id = class.class_id  inner join `section` on promotion.section_id = section.section_id inner join `attendancestatus` on attendancestatus.id = studentatt.status_id  WHERE is_deleted='0' AND promotion.is_active='1' AND student.branch='$branch'  $sq1 LIMIT 0, $per_page");
                $p=1;
                }else
        $query = $this->db->query("SELECT student.student_name,student.sid,student.roll_no,class.class_name,section.section_name,studentatt.date,studentatt.id,attendancestatus.status FROM `studentatt` inner join `student` on studentatt.student_id = student.id inner join `promotion` on promotion.student_id = student.id inner join `class` on promotion.class_id = class.class_id  inner join `section` on promotion.section_id = section.section_id inner join `attendancestatus` on attendancestatus.id = studentatt.status_id  WHERE is_deleted='0' AND promotion.is_active='1' AND student.branch='$branch'  $sq1 LIMIT $offset, $per_page");

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


            $data['studentatt'] = $query->result_array();
            $data['end'] = ceil($total / $per_page);
            $this->load->view('header',$data);
            $this->load->view('sidebar',$data);
            $this->load->view('student/studentatt_show',$data);
         
    }
        /*======================== Status =====================================*/
        public function status($q="all",$p=1)
   {
         $this->user_model->check_permissions("student/status");
        $data['is_super'] = $this->user_model->is_super();
        $data['menu'] = $this->load_model->menu();
         $branch=$this->user_model->getbranch();
         //var_dump($branch);die;
            if($this->user_model->is_super())
                $data['branch'] = $this->db->select("name,id")->from("branch")->get()->result();
            else
                $data['branch'] = $this->db->select("name,id")->from("branch")->where("id",$branch)->get()->result();
        if($this->user_model->is_super())
        {
            $query = $this->db->query("SELECT student.*,class.*,section.*,status.*,branch.name as b_name,student.id as stid FROM student JOIN branch on branch.id = student.branch JOIN promotion ON promotion.student_id=student.id JOIN class ON promotion.class_id=class.class_id JOIN section ON promotion.section_id=section.section_id inner join `status` on student.status = status.id  WHERE student.status!='0' AND promotion.is_active='1' ORDER by status.id DESC ");
        }
        else
        $query = $this->db->query("SELECT student.*,class.*,section.*,status.*,branch.name as b_name,student.id as stid FROM student JOIN branch on branch.id = student.branch JOIN promotion ON promotion.student_id=student.id JOIN class ON promotion.class_id=class.class_id JOIN section ON promotion.section_id=section.section_id inner join `status` on student.status = status.id  WHERE student.branch = '$branch' AND student.status!='0' AND promotion.is_active='1' ORDER by status.id DESC ");
        
        
        //$data['q'] = $q;
        //$data['curr'] = $p;
        //$data['searchq'] = $q;
        $data['base_url'] = base_url();
        $data['userInfo'] = $this->userInfo;
        $data['student'] = $query->result_array();
        //$data['end'] = ceil($total / $per_page);
            //calling  pages views
        $this->load->view('header',$data);
        $this->load->view('sidebar',$data);
        $this->load->view('student/status_student',$data);


   }
            // status_update is for  upadte status of teacher
            
     public function student_status_chart()
   {
   
  
  //var_dump($data); die();
   
   
   }       
            
   public function status_update()
   {
        if($this->input->post())
        {
           $data=$this->input->post();
           $this->student_model->status_update($data);
           $this->session->set_flashdata('msg',"<div style='height:30px;color:white;font-size:18px;text-align:center;width:50%;margin-left:230px;background-color:#008241;'>Status Assigned Successfully</div>");
           //$this->session->set_flashdata('feedback_class','alert-success');
           redirect('student/status');
        }
        else
        {
           redirect('student/status');

        }
   }

        //rollback is for back to 0 position
   public function rollback()
   {
            if($this->uri->segment(3))
            {
$data = explode(SALT,json_decode(base64_decode($this->uri->segment(3))))[0];
     //           $data = $this->uri->segment(3);
                $this->student_model->rollback($data);
                redirect('student/status','refresh');
            } 
            else
            {
                redirect('student/status','refresh');

            }
   }


       public function actions($ref="",$value=0)
        {   
           
            if($ref=="edit"){
                $data['menu'] = $this->load_model->menu();
                $data['base_url'] = base_url();
                $data['userInfo'] = $this->userInfo;
                
                $data['studentatt']=$this->student_model->studentatt_edit($value)->result_array();
                 var_dump($data['studentatt']);die;
                $this->load->view('header',$data);
                $this->load->view('sidebar',$data);
                 
                $data['statusid']=$this->db->select("*")->from('attendancestatus')->get()->result_array();
               
                $this->load->view('student/studentatt_edit',$data);
            }else if($ref=="del")
            {
                $data['menu'] =$this->load_model->menu();
                $data['base_url'] = base_url();
                $data['userInfo'] = $this->userInfo;
                $check=$this->student_model->studentatt_del($value);
                if($check==true){
                    redirect("student/studentatt_show/");
                }else
                {
                    echo "could not Delete";
                }
            }
        }
    public function promotion()
    {
        //$this->user_model->check_permissions("student/index");
        $branch = $this->user_model->getBranch();
        $data['is_super'] = $this->user_model->is_super();
        $data['menu'] = $this->load_model->menu();
        $data['base_url'] = base_url();
        $data['userInfo'] = $this->userInfo;
        if($data['is_super'])
            $data['branch'] = $this->db->query("SELECT * FROM `branch` WHERE `is_delete`='0'")->result_array();
        else
            $data['branch'] = $this->db->query("SELECT * FROM `branch` WHERE `is_delete`='0' AND `id`='$branch'")->result_array();
        $data['session'] = $this->db->query("SELECT * FROM `session` WHERE `is_delete`='0'")->result_array();
        $this->load->view('header',$data);
        $this->load->view('sidebar',$data);
        $this->load->view('student/promotion',$data);
    }
    public function promotion_selection($branch=0,$class=0,$section=0,$session=0)
    {
        if($branch==0 OR $class==0 OR $section==0 OR $session==0)
        {
            redirect("student/promotion");
        }
        $data['is_super'] = $this->user_model->is_super();
        $data['menu'] = $this->load_model->menu();
        $data['base_url'] = base_url();
        $data['userInfo'] = $this->userInfo;
        $data['student'] =$this->db->query("SELECT `student`.`sid`,`student`.`id`,`student`.`student_name`, `student`.`father_name`, `promotion`.`id` as p_id FROM `student` INNER JOIN `promotion` ON `promotion`.`student_id`=`student`.`id` WHERE `student`.`status`='0' AND `student`.`is_delete`='0' AND `student`.`branch`='$branch' AND `promotion`.`class_id`='$class' AND `promotion`.`section_id`='$section' AND `promotion`.`session_id`='$session' AND `promotion`.`is_active`='1'")->result_array();
        //$this->db->query("SELECT `student`.`sid`,`student`.`id`,`student`.`student_name`, `student`.`father_name`, `invoice`.`id` as inv_id,invoice.remaining,invoice.status FROM `student` INNER JOIN `promotion` ON `promotion`.`student_id`=`student`.`id` LEFT JOIN `invoice` ON `invoice`.`student_id`=`promotion`.`id`WHERE `student`.`status`='0' AND `student`.`is_delete`='0' AND `student`.`branch`='$branch' AND `promotion`.`class_id`='$class' AND `promotion`.`section_id`='$section' AND `promotion`.`session_id`='$session' AND `promotion`.`is_active`='1' order by `invoice`.`id` DESC")->result_array();
        if($data['is_super'])
            $data['branch'] = $this->db->query("SELECT * FROM `branch` WHERE `is_delete`='0'")->result_array();
        else
            $data['branch'] = $this->db->query("SELECT * FROM `branch` WHERE `is_delete`='0' AND `id`='$branch'")->result_array();
        $data['session'] = $this->db->query("SELECT * FROM `session` WHERE `is_delete`='0'")->result_array();
        $data['branch_old'] = $branch;
        $data['class_old'] = $class;
        $data['section_old'] = $section;
        $data['session_old'] = $session;
        $this->load->view('header',$data);
        $this->load->view('sidebar',$data);
        $this->load->view('student/promotion_selection',$data);
    }
    public function promote_students()
    {
        if($this->input->post())
        {
// echo "<pre>";print_r($this->input->post());exit;
            $is_super = $this->user_model->is_super();
            $students = $this->input->post('student',true);
            $branch_old = $this->input->post('branch_old',true);
            $class_old = $this->input->post('class_old',true);
            $section_old = $this->input->post('section_old',true);
            $session_old = $this->input->post('session_old',true);
            $branch = $this->input->post('branch',true);
            $class = $this->input->post('class',true);
            $section = $this->input->post('section',true);
            $session = $this->input->post('session',true);

            //var_dump($students);die;
            if(empty($students))
            { 
              redirect("student/promotion");
            }
            else{
                
            foreach ($students as $key => $value){
                $data = array(
                    "is_active"=>"0"
                );
                
                $this->db->where("student_id",$value);
                $this->db->where("class_id",$class_old);
                $this->db->where("section_id",$section_old);
                $this->db->where("session_id",$session_old);
                $this->db->update("promotion",$data);
                /**/
                $data1 = array(
                    "student_id"=>$value,
                    "class_id"=>$class,
                    "section_id"=>$section,
                    "session_id"=>$session,
                    "is_active"=>"1",
                    "is_delete"=>"0"
                );
                //var_dump($data1);die;
                $this->db->insert("promotion",$data1);
                // $pro_id = $this->db->insert_id();
                // $student = @$this->db->query("SELECT `invoice`.`id` as inv_id,invoice.remaining,invoice.status From promotion INNER JOIN `invoice` ON `invoice`.`student_id`=`promotion`.`id`WHERE `promotion`.`student_id`='$value' AND `promotion`.`class_id`='$class_old' AND `promotion`.`section_id`='$section_old' AND `promotion`.`session_id`='$session_old' AND `promotion`.`is_active`='0' order by `invoice`.`id` DESC")->row_array();
        
                // if($student['remaining'] == 0 && $student['status'] == 1)
                //     {$remaining = 0;}
                // elseif($student['remaining'] > 0 && $student['status'] !=0)
                //     {$remaining = $student['remaining'];}
                // else{$remaining = ($this->voucher_model->countTotalFee($student['inv_id']));}
                    
                // $array = array(
                // 'promotion_id'=>$pro_id,    
                // 'class_id'=>$class,    
                // 'section_id'=>$section,    
                // 'amount'=>$remaining,    
                // 'add_month'=>date('Y-m-d'),    
                // 'for_month'=>date('Y-m-d'),    
                // 'status'=>($remaining==0) ? '1':'0',
                // );
                // $this->db->insert('arrears',$array);
        
            }
            redirect("student/promotion");
            //redirect("student/show");
    
        }}else{
            redirect("student/promotion");
        }
        
    }  

    public function StudentAdmissionPrint($id=1)
    {
$id = explode(SALT,json_decode(base64_decode($this->uri->segment(3))))[0];
        $this->user_model->check_permissions("student/index");
        $branch = $this->user_model->getBranch();
        $data['menu'] = $this->load_model->menu();
        $data['base_url'] = base_url();
        $data['userInfo'] = $this->userInfo;
        if($this->user_model->is_super())
            $data['b_header'] = $this->db->query("SELECT * FROM `branch` WHERE `is_delete`='0'")->row_array();
        else
            $data['b_header'] = $this->db->query("SELECT * FROM `branch` WHERE `is_delete`='0' AND `id`='$branch'")->row_array();
        $data['student'] = $this->db->query("SELECT `student`.* FROM `student` INNER JOIN `promotion` ON `promotion`.`student_id`=`student`.`id` WHERE `student`.`status`='0' AND `promotion`.`is_delete`='0'  AND `promotion`.`is_active`='1'  AND `promotion`.`student_id`='$id'")->row_array();

        $father_cnic = $data['student']['father_cnic'];

        $this->db->select('student.sid,student.grno,student.student_name, student.father_name , class.class_name,branch.name')->from('student')
                ->join('promotion','promotion.student_id=student.id')
                ->join('class','class.class_id=promotion.class_id')
                ->join('branch', 'branch.id = student.branch')
                ->where('student.is_delete',0)
                ->where('promotion.is_active',1)
                ->where('student.father_cnic',$father_cnic);
               $data['siblings'] = $this->db->get()->result_array();     
            //var_dump("<pre>",$data['siblings']);die();
        $this->load->view('printable/student_admission_print',$data);
    }
    public function StudentAdmissionPrintt()
    {
       // $this->user_model->check_permissions("student/index");
     //  var_dump('hello');
      // die();
        $branch = $this->user_model->getBranch();
        $data['menu'] = $this->load_model->menu();
        $data['base_url'] = base_url();
        $data['userInfo'] = $this->userInfo;
        if($this->user_model->is_super())
            $data['b_header'] = $this->db->query("SELECT * FROM `branch` WHERE `is_delete`='0'")->row_array();
        else
            $data['b_header'] = $this->db->query("SELECT * FROM `branch` WHERE `is_delete`='0' AND `id`='$branch'")->row_array();
       
        $this->load->view('printable/student_admission_printblank.php',$data);
    }

     public function admission_form()
    {
       // $this->user_model->check_permissions("student/index");
     //  var_dump('hello');
      // die();
        $branch = $this->user_model->getBranch();
        $data['menu'] = $this->load_model->menu();
        $data['base_url'] = base_url();
        $data['userInfo'] = $this->userInfo;
        if($this->user_model->is_super())
            $data['b_header'] = $this->db->query("SELECT * FROM `branch` WHERE `is_delete`='0'")->row_array();
        else
            $data['b_header'] = $this->db->query("SELECT * FROM `branch` WHERE `is_delete`='0' AND `id`='$branch'")->row_array();
       
        $this->load->view('printable/admission_form.php',$data);
    }
    
    public function student_report()
    {
        if($this->user_model->is_super())
        {
            $data['branch']=$this->db->query("SELECT * FROM `branch` WHERE `is_delete`='0'")->result_array();
        }else{
            $data['branch']=$this->db->query("SELECT * FROM `branch` WHERE `is_delete`='0' AND `id`='".$this->branch."'")->result_array();
        }
        $b=$this->user_model->getBranch();
        $query = $this->db->query("SELECT student.*,class.*,section.*,student.id as stid FROM student JOIN promotion ON promotion.student_id=student.id JOIN class ON promotion.class_id=class.class_id JOIN section ON promotion.section_id=section.section_id WHERE student.branch = '$b' AND student.status='0' and student.is_delete='0' AND promotion.is_active='1' order by sid ASC");
        $data['student'] = $query->result_array();
        $this->load->view('student/student_report',$data);
    }
 
     
    
    
    
     public function class_cards()
    {
    	
        $data['menu'] = $this->load_model->menu();
        $data['base_url'] = base_url();
        $data['userInfo'] = $this->userInfo;
        $branch=$this->user_model->getbranch();
        $data['sessions'] = $this->db->where('is_delete', 0)->get('session')->result_array();
        if($this->user_model->is_super()){
            $data['types']	= $this->db->select('*')->where('is_delete', 0)->get('class')->result_array();
        }
        else{
        $data['types']	= $this->db->select('*')->where('branch',$branch )->where('is_delete', 0)->get('class')->result_array();
        }
      
      //  $class_ids 	= array_column($classes, 'class_id');
  

        $this->load->view('header',$data);
        $this->load->view('sidebar',$data);
        $this->load->view('student/cards_class',$data);
    } 
    
    public function position_holder()
    {
        $this->user_model->check_permissions("student/position_holder");
        $data['menu'] = $this->load_model->menu();
        $data['base_url'] = base_url();
        $data['userInfo'] = $this->userInfo;
        $data['sessions'] = $this->db->where('is_delete', 0)->get('session')->result_array();
        $classes	= $this->db->select('class_id')->where('branch', 1)->where('is_delete', 0)->get('class')->result_array();
        $data['types']	= $this->db->select('*')->where('is_delete', 0)->get('exam')->result_array();
        $class_ids 	= array_column($classes, 'class_id');
  

        $this->load->view('header',$data);
        $this->load->view('sidebar',$data);
        $this->load->view('student/position_holder',$data);
    }
    
    public function save_position_students()
    {
        $branch=$this->user_model->getbranch();
          $pos= array("1st","2nd","3rd");
         $exam	= $this->input->post('exam',true);
        //  var_dump("<pre>", $exam);die;
         $students 	= $this->db->select("result.promotion_id,result.position, exam.name as exam_name")->from("exam")
         ->join('exam_type', 'exam.etype_id= exam_type.id')
         ->join("result", 'exam.id = result.exam_id')
         ->where("result.exam_id", $exam)
         ->where_in("result.position", $pos)->get()->result_array();
        //  var_dump("<pre>", $students);die;
        
             foreach($students as $student) {
         	$data_array[] = array(
         		'promotion_id' 	=> $student['promotion_id'],
         		'exam_name' 	=> $student["exam_name"],
         		'branch_id'=>$branch
         	);
        //  	var_dump("<pre>", $students);die;
         }
         if(empty($data_array)){
              redirect("student/position_holder", "refresh");
          } 
         else  
          { 
         
        $this->db->where('branch_id',$branch)
                 ->delete("position_holders");
         $this->db->insert_batch('position_holders', $data_array);
	    return redirect("student/position_holder", "refresh");
        }
    }
    
    public function best_students()
    {
        $data['menu'] = $this->load_model->menu();
        $data['base_url'] = base_url();
        $data['userInfo'] = $this->userInfo;
        $data['sessions'] = $this->db->where('is_delete', 0)->get('session')->result_array();
        $classes	= $this->db->select('class_id')->where('branch', 1)->where('is_delete', 0)->get('class')->result_array();
        $data['types']	= $this->db->select('*')->where('is_delete', 0)->get('exam')->result_array();
        $class_ids 	= array_column($classes, 'class_id');
  

        $this->load->view('header',$data);
        $this->load->view('sidebar',$data);
        $this->load->view('student/best_students',$data);
    } 
    
    
    
    
     public function save_best_students()
    {
        $branch=$this->user_model->getbranch();
        $pos= array("1st","2nd","3rd");
        $exam	= $this->input->post('exam',true);
        //  var_dump("<pre>", $exam);die;
         $students 	= $this->db->select("result.promotion_id,result.position, exam.name as exam_name")->from("exam")
         ->join('exam_type', 'exam.etype_id= exam_type.id')
         ->join("result", 'exam.id = result.exam_id')
         ->where("result.exam_id", $exam)
         ->where_in("result.position", $pos)->get()->result_array();
        
        foreach($students as $student) {
         	$data_array[] = array(
         		'promotion_id' 	=> $student['promotion_id'],
         		'exam_name' 	=> $student["exam_name"],
         		'branch_id'=>$branch
         	);

         }
         if(empty($data_array)){
              redirect("student/best_students", "refresh");
          } 
         else  
          { 
         
        $this->db->where('branch_id',$branchid)
	             ->delete('best_students');
         $this->db->insert_batch('best_students', $data_array);
	    return redirect("student/best_students", "refresh");
        }
    }

    public function updatePicForm()
    {
        $this->user_model->check_permissions("student/updatePicForm");
        $data['base_url'] = base_url();
        $data['userInfo'] = $this->userInfo;
        $data['menu'] = $this->load_model->menu();
        $branch=$this->user_model->getbranch();

        //===========================================
        //calling views
        $this->load->view('header',$data);
        $this->load->view('sidebar',$data);
        $this->load->view('student/updatePicForm',$data);
    }

    public function getStudentForPic()
    {
        if($this->input->post('sid')){
            $gr=$this->input->post('sid');
            
            $data['is_super'] = $this->user_model->is_super();
            $data['menu'] = $this->load_model->menu();
            $branch=$this->user_model->getbranch();
            $data['base_url'] = base_url();
            $data['userInfo'] = $this->userInfo;
            $this->db->where('sid',$gr);
            $this->db->select("student.id as std_id, student.*,class.*"); 
            $this->db->from('student');
            $this->db->join('promotion', 'promotion.student_id=student.id');
            $this->db->join('class', 'promotion.class_id=class.class_id');
            //$this->db->where('promotion.is_active',1);
            $this->db->where('student.status',0);
            $query=$this->db->get();
            if($query->num_rows() >= 1)
            {
            $data['student']=$query->row_array();
            $this->load->view('header',$data);
            $this->load->view('sidebar',$data);
            $this->load->view('student/getStudentForPic',$data);
            $this->load->view('footer',$data);
            }
            else{

                echo "No data Found Accourding to this GR #";
                redirect('Student/updatePicForm','refresh');
            } 
        }
        else{
            $this->updatePicForm();
        }
    }

    public function updateStudentPic()
    {
        
        $data=$this->input->post();
        $id = $data['id'];
        $data_img=explode(",",base64_decode($data['image']));
        $image=$data_img[1];
        $image=base64_decode($image);
        $img_name=uniqid();
        $file="./images/".$img_name. '.jpg';
        $res=file_put_contents($file, $image);
        if($res) {
            echo "true";
            $this->db->where('id',$id);
            $this->db->update("student",array(
                "img"=> "./images/".$img_name.".jpg"
            ));
        }
    }


    //Set Country Dropdown
    public function setcountry()
    {
        if(isset($_POST['country']) && !empty($_POST['country']))
       {

            $country_id = $this->input->post('country');
            $provinces = $this->db->order_by('province_name') 
                                ->where('is_delete',0)
                                ->get_where('province', array('country_id'=> $country_id))->result();

            if($provinces)
            {
                $pro_select_box = "";
                $pro_select_box .= '<option value="">Select Province</option>';
                foreach ($provinces as $province) {
                    $pro_select_box .= '<option value="'.$province->province_id.'">'.$province->province_name.'</option>';

                }
            echo $pro_select_box;
            }
        }
    }

    //SET Province Dropdown
    public function setprovince()
    {
        if(isset($_POST['province']) && !empty($_POST['province']))
        {
            $province_id = $this->input->post('province');
            $districts = $this->db->order_by('name','ASC')
                                    ->where('is_delete',0)
                                    ->get_where('district', array('province_id'=> $province_id))->result();

            if($districts)
            {
                $dis_select_box = "";
                $dis_select_box .= '<option value="">Select District</option>';
                foreach ($districts as $district) {
                    $dis_select_box .= '<option value="'.$district->id.'">'.$district->name.'</option>';
                }
            echo $dis_select_box;
            }
        }
    }

    //SET District Dropdown
    public function setdistrict()
    {
        if(isset($_POST['district']) && !empty($_POST['district']))
       {
            $district_id = $this->input->post('district');
            $talukas = $this->db->order_by('name','ASC')
                                ->where('is_delete',0)
                                ->get_where('taluka', array('district_id'=> $district_id))->result();

            if($talukas)
            {
                $tal_select_box = "";
                $tal_select_box .= '<option value="">Select Taluka</option>';
                foreach ($talukas as $taluka) {
                    $tal_select_box .= '<option value="'.$taluka->id.'">'.$taluka->name.'</option>';

            }
            echo $tal_select_box;
            }
        }
    }

    //Set Taluka Dropdown
    public function settaluka()
    {
         if(isset($_POST['taluka']) && !empty($_POST['taluka']))
       {
       
            $taluka_id = $this->input->post('taluka');
            $cities = $this->db->order_by('city_name','ASC')
                                ->where('is_delete',0)
                                ->get_where('city', array('taluka_id'=> $taluka_id))->result();

            if($cities)
            {
                $city_select_box = "";
                $city_select_box .= '<option value="">Select City</option>';
                foreach ($cities as $city) {
                    $city_select_box .= '<option value="'.$city->city_id.'">'.$city->city_name.'</option>';
                }
            echo $city_select_box;
            }
        }
    }
    public function against($br)
    {
         if($br==0)
         {
             $query=$this->db->query("SELECT student.*,class.*,section.*,branch.name as b_name, student.id as stid FROM student JOIN branch on branch.id = student.branch JOIN promotion ON promotion.student_id=student.id JOIN class ON promotion.class_id=class.class_id JOIN section ON promotion.section_id=section.section_id WHERE student.status='0' and student.is_delete='0' AND promotion.is_active='1' and class.is_delete=0 and section.is_delete=0 ORDER BY stid DESC ");//LIMIT $offset,$per_page
         }
         else{
        $query = $this->db->query("SELECT student.*,class.*,section.*,branch.name as b_name,student.id as stid FROM student JOIN branch ON branch.id=student.branch JOIN promotion ON promotion.student_id=student.id JOIN class ON promotion.class_id=class.class_id JOIN section ON promotion.section_id=section.section_id WHERE student.branch = '$br' AND student.status='0' and student.is_delete='0' AND promotion.is_active='1' and class.is_delete=0 and section.is_delete=0 ORDER BY stid DESC ");//LIMIT $offset,$per_page
         }
        $stds = $query->result_array();
        $return = "";
        $i = 1;
        foreach ($stds as $key => $value) {
            $return .= "<tr>";
            $return .= "<td>".$i++."</td>";
            $return .= "<td>".$value['sid']."</td>";
             $return .= "<td>".$value['grno']."</td>";
            $return .= "<td>".$value['student_name']."</td>";
            $return .= "<td>".$value['father_name']."</td>";
            $return .= "<td>".$value['father_contact']."</td>";
            $return .= "<td>".$value['gender']."</td>";
            $return .= "<td>".$value['class_name']."</td>";
            $return .= "<td>".$value['section_name']."</td>";
            $newdate = date('d-m-Y',  strtotime($value['date_of_admission']));
            $return .= "<td>".$newdate."</td>";
            $return .= "<td>".$value['b_name']."</td>";
            
            
            $return .= "<td><a href='".base_url()."student/student_info/".$value['stid']."'><i class='fa fa-eye'></i></a>
            <a href='".base_url()."student/edit/".$value['stid']."'><i class='fa fa-edit'></i></a></td>";
            $return .= "</tr>";
        }
        echo $return;
    }
    
   
    public function against_class($br,$class,$sec)
    {
         if($br==0)
         {
             $query=$this->db->query("SELECT student.*,class.*,section.*,branch.name as b_name, student.id as stid FROM student JOIN branch on branch.id = student.branch JOIN promotion ON promotion.student_id=student.id JOIN class ON promotion.class_id=class.class_id JOIN section ON promotion.section_id=section.section_id WHERE student.status='0' AND student.is_delete='0' AND promotion.is_active='1' and class.is_delete=0 and section.is_delete=0 ORDER BY stid DESC ");//LIMIT $offset,$per_page
         }
         else{
        $query = $this->db->query("SELECT student.*,class.*,section.*,branch.name as b_name,student.id as stid FROM student JOIN branch ON branch.id=student.branch JOIN promotion ON promotion.student_id=student.id JOIN class ON promotion.class_id=class.class_id JOIN section ON promotion.section_id=section.section_id WHERE student.branch = '$br' AND student.status='0' AND student.is_delete='0' AND promotion.is_active='1' and class.is_delete=0 and class.class_id='$class' and section.section_id='$sec' and section.is_delete=0 ORDER BY stid DESC ");//LIMIT $offset,$per_page
         }
        $stds = $query->result_array();
        $return = "";
        $i = 1;
        foreach ($stds as $key => $value) {
            $return .= "<tr>";
            $return .= "<td>".$i++."</td>";
            $return .= "<td>".$value['sid']."</td>";
             $return .= "<td>".$value['roll_no']."</td>";
            $return .= "<td>".$value['student_name']."</td>";
            $return .= "<td>".$value['father_name']."</td>";
            $return .= "<td>".$value['father_contact']."</td>";
            $return .= "<td>".$value['gender']."</td>";
            $return .= "<td>".$value['class_name']."</td>";
            $return .= "<td>".$value['section_name']."</td>";
            $newdate = date('d-m-Y',  strtotime($value['date_of_admission']));
            $return .= "<td>".$newdate."</td>";
            
            
            
            $return .= "<td><a href='".base_url()."student/student_info/".$value['stid']."'><i class='fa fa-eye'></i></a>
            <a href='".base_url()."student/edit/".$value['stid']."'><i class='fa fa-edit'></i></a><a href='".base_url()."student/delete_student/".$value['stid']."'><i class='fa fa-trash'></i></a></td>";
           
            $return .= "</tr>";
        }
        echo $return;
    }
    public function district($v="")
     {          
                
                $result = $this->db->query("SELECT * FROM district WHERE province_id='$v'  AND is_delete='0'")->result_array();
                foreach ($result as $key => $value) {
                    echo "<option value='".$value['id']."'>".$value['name']."</option>";
            
                            }
    }
    public function count_siblings($cnic){
    $this->db->select();
	$this->db->from('student');
	$this->db->where('father_cnic',$cnic);
	$query = $this->db->get();
	$count=$query->num_rows();
    //var_dump($count);die;
	if($query->num_rows() > 0)
			{
				 $data =  $count;
			}
		else{
		        $data =  0;
		    }
		echo json_encode($data);
    }
    public function taluka($v="")
     {          
                
                $result = $this->db->query("SELECT * FROM taluka WHERE district_id='$v'  AND is_delete='0'")->result_array();
                foreach ($result as $key => $value) {
                    echo "<option value='".$value['id']."'>".$value['name']."</option>";
            
                            }
    }
    public function get_record($id, $br){
        $week_date = date('Y-m-d',strtotime('-7 days'));
        $q=$this->db->query("SELECT student.student_name,student.id,class.class_name,section.section_name,studentatt.date,studentatt.id,studentatt.status_id,
         attendancestatus.status FROM `studentatt` join `student` on studentatt.student_id = student.id  join `promotion` on promotion.student_id = student.id
          join `class` on promotion.class_id = class.class_id   join `section` on promotion.section_id = section.section_id
          join `attendancestatus` on attendancestatus.id = studentatt.status_id  WHERE studentatt.id = '$id' AND studentatt.date >= '$week_date' AND is_deleted='0' 
         AND is_active='1' AND student.branch='$br' ");
            // var_dump($q);die;
        $query = $q->row_array();
        
        echo json_encode($query);
     
   }
   public function studentatt_upd($id, $date, $status)
    {
        
  $data=array(
       'date'=>date('Y-m-d',strtotime($date)),
        'status_id' => $status
  );
        $this->db->where('id',$id);
        $this->db->update('studentatt',$data);
 
        $branch=$this->user_model->getbranch();
        if(!$this->user_model->is_super()){ 
        $week_date = date('Y-m-d',strtotime('-7 days'));
         $query = $this->db->query("SELECT student.student_name,student.sid,student.roll_no,class.class_name,section.section_name,studentatt.date,studentatt.id,
         attendancestatus.status FROM `studentatt` inner join `student` on studentatt.student_id = student.id inner join `promotion` on promotion.student_id = student.id
         inner join `class` on promotion.class_id = class.class_id  inner join `section` on promotion.section_id = section.section_id
         inner join `attendancestatus` on attendancestatus.id = studentatt.status_id  WHERE studentatt.date >= '$week_date' AND is_deleted='0' 
         AND is_active='1' AND student.branch='$branch' Order by date desc");
         }
         if($this->user_model->is_super()){ 
            $week_date = date('Y-m-d',strtotime('-7 days'));
        
         $query = $this->db->query("SELECT student.student_name,student.sid,student.roll_no,branch.name as b_name,class.class_name,section.section_name,studentatt.date,studentatt.id,
         attendancestatus.status FROM `studentatt` inner join `student` on studentatt.student_id = student.id inner join `promotion` on promotion.student_id = student.id
         inner join `class` on promotion.class_id = class.class_id  inner join `section` on promotion.section_id = section.section_id
         inner join `attendancestatus` on attendancestatus.id = studentatt.status_id inner join branch on branch.id=student.branch  WHERE studentatt.date >= '$week_date' AND is_deleted='0' 
         AND is_active='1' Order by date desc");
         }
         
         $data['Attendancestatus']=$this->db->select("*")->from('attendancestatus')->get()->result_array();
        $record = $query->result_array();
        // var_dump($record);die;
        if(!empty($record))
         {
            $i=0; 
            foreach ($record as $key => $value)
            { $i++;
                echo "
                 <tr>
                          <td>$i</td>
                          <td>$value[sid]</td>
                          <td>$value[student_name] </td>
                          <td>$value[class_name]</td>
                          <td>$value[section_name] </td>";
                          $newdate = date("d-m-Y",strtotime($value['date']));
                          echo "<td>$newdate</td>
                          <td>$value[status]</td>";
                           if($this->user_model->is_super()){
                               
                               echo "<td>$value[b_name]</td>";
                           }
                           if(!$this->user_model->is_super()){
                             echo "<td>
                            <a href='' onclick='edit($value[id],event)'>
                            <i class='fa fa-edit'></i></a>";
                             echo "</td>";
                           }

                      echo"</tr>";
                        } 
               
            }
            //<a href='' onclick='delete_att($value[id],event)'><i class='fa fa-trash'></a></i>
    }
 
     
    public function delete_record($id, $br){
       $data=array('is_deleted' => 1  );
        $this->db->where('id', $id);   
        $this->db->delete('studentatt');
        
        $branch=$this->user_model->getbranch();
        if(!$this->user_model->is_super()){ 
        $week_date = date('Y-m-d',strtotime('-7 days'));
         $query = $this->db->query("SELECT student.student_name,student.sid,student.roll_no,class.class_name,section.section_name,studentatt.date,studentatt.id,
         attendancestatus.status FROM `studentatt` inner join `student` on studentatt.student_id = student.id inner join `promotion` on promotion.student_id = student.id
         inner join `class` on promotion.class_id = class.class_id  inner join `section` on promotion.section_id = section.section_id
         inner join `attendancestatus` on attendancestatus.id = studentatt.status_id  WHERE studentatt.date >= '$week_date' AND is_deleted='0' 
         AND is_active='1' AND student.branch='$branch' Order by date desc");
         }
         if($this->user_model->is_super()){ 
            $week_date = date('Y-m-d',strtotime('-7 days'));
        
         $query = $this->db->query("SELECT student.student_name,student.sid,student.roll_no,branch.name as b_name,class.class_name,section.section_name,studentatt.date,studentatt.id,
         attendancestatus.status FROM `studentatt` inner join `student` on studentatt.student_id = student.id inner join `promotion` on promotion.student_id = student.id
         inner join `class` on promotion.class_id = class.class_id  inner join `section` on promotion.section_id = section.section_id
         inner join `attendancestatus` on attendancestatus.id = studentatt.status_id inner join branch on branch.id=student.branch  WHERE studentatt.date >= '$week_date' AND is_deleted='0' 
         AND is_active='1' Order by date desc ");
         }
         $data['Attendancestatus']=$this->db->select("*")->from('attendancestatus')->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[sid]</td>
                          <td>$value[student_name] </td>
                          <td>$value[class_name]</td>
                          <td>$value[section_name] </td>";
                          $newdate = date("d-m-Y",strtotime($value['date']));
                          echo "<td>$newdate</td>
                          <td>$value[status]</td>";
                          if($this->user_model->is_super()){
                               
                               echo "<td>$value[b_name]</td>";
                           }
                           if(!$this->user_model->is_super()){
                             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>";
                        } 
               
            }
   }
   function check_date_att($date,$br,$class, $section)
   {
       $newdate = date("Y-m-d",strtotime($date));
       //var_dump($newdate);
    $this->db->select('studentatt.*, student.branch,promotion.class_id,promotion.section_id');
	$this->db->from('studentatt');
	$this->db->join('student', 'studentatt.student_id = student.id');
	$this->db->join('promotion', 'studentatt.promotion_id = promotion.id');
	$this->db->where('branch',$br);
	$this->db->where('class_id',$class);
	$this->db->where('section_id',$section);
	$this->db->where('date',$newdate);
	$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);
   }
   function check_holiday($date,$br,$class, $section)
   {
       $newdate = date("Y-m-d",strtotime($date));
       //var_dump($newdate);
    $this->db->select('holiday.*,class.class_id,section.section_id');
	$this->db->from('holiday');
	$this->db->join('branch', 'branch.id=holiday.branch_id');
	$this->db->join('class', 'class.class_id=holiday.class_id');
	$this->db->join('section', 'section.section_id=holiday.section_id');
	$this->db->where('holiday.branch_id',$br);
	$this->db->where('holiday.class_id',$class);
	$this->db->where('holiday.section_id',$section);
	$this->db->where('froom',$newdate);
	
	$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);
   }
   public function profile($student_id=null){
       if($this->user_model->userInfo('student_id')['student_id'] == '0'){
           redirect('/home');
       }
       $data['is_super'] = $this->user_model->is_super();
        $data['userInfo'] = $this->user_model->userInfo();
        $data['student']=$this->get_student($data['userInfo']['student_id']);
        $data['base_url'] = base_url();
	$data['menu'] = $this->load_model->menu();
     $this->load->view('header',$data);
		$this->load->view('sidebar',$data);
        $this->load->view('profile/student/profile',$data);  
   }
   public function get_student($id){
   return $students=$this->db->select('student.student_name,class_name,section_name,student.id,session.name as session_name,student.gender,student.religion,student.dob,student.date_of_admission,student.img')
                          ->from('student')
                          ->join('promotion','promotion.student_id=student.id')
                        ->join('class','class.class_id=promotion.class_id')
                          ->join('section','section.section_id=promotion.section_id')
                          ->join('session','session.id=promotion.session_id')
                          
                         ->where('student.id',$id)
                          ->get()->row();
   }

}


function check_date_att1($date,$br)
   {
       $newdate = date("Y-m-d",strtotime($date));
       //var_dump($newdate);
    $this->db->select('studentatt.*, student.branch,promotion.class_id');
	$this->db->from('studentatt');
	$this->db->join('student', 'studentatt.student_id = student.id');
	$this->db->join('promotion', 'studentatt.promotion_id = promotion.id');
	$this->db->where('branch',$br);
	$this->db->where('date',$newdate);
	$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);
   }


