<?php

class attendance_model extends CI_Model {

    function __construct() {
        // Call the Model constructor
        parent::__construct();
         
    }

    
    function get_active_staff(){
        
        
        $where = "(staff.business_id=". $this->session->userdata('businessid') ." OR staff.staff_shared = 'Yes') ";
        
        $this->db->select('*');
        $this->db->join('business','id_business=staff.business_id');
        $this->db->where('staff_active','Y');  
        if($this->session->userdata("ho")=='No'){
            $this->db->where($where);
        }
        $this->db->order_by('business_id, id_staff');
        $query = $this->db->get('staff');
        
        return $query->result_array();
    }

    function get_staff_attendance($date,$opening='10:00:00'){
        //echo $opening;exit();
        $time_margin = 0;
        $sql = "select timein_margin from business where id_business = ".$this->session->userdata('businessid') ;
        $query = $this->db->query($sql);
        $d= $query->row();
        if(isset($d->timein_margin)){
            $time_margin = $d->timein_margin;        
        }
       
        $sql="select business_name, id_business, id_staff, staff_fullname, day(time_in) day, month(time_in) month, year(time_in) year, date_format(time_in,'%H:%i:%s') TimeIn,
        date(time_in) as mDate, time_in,
        TIMESTAMPDIFF(MINUTE,CONCAT(date(time_in), ' ', day_start_time), time_in) as timeDiff,
        case When TIMESTAMPDIFF(MINUTE,CONCAT(date_format(time_in,'%Y-%m-%d'), ' ', day_start_time), time_in) > ".$time_margin." then 'late' else 'ontime' End as onTime, 
        left(staff_attendance.address,4) as address

        from staff_attendance
        join staff on id_staff = staff_id
        join business on business.id_business = staff.business_id 
        where month(time_in)=".date("m",strtotime($date))."
        and year(time_in)='".date("Y",strtotime($date))."' ";
        if($this->session->userdata("ho")=='No'){
            $sql .= " and staff_attendance.business_id = ".$this->session->userdata('businessid')."";
        }

        $sql .=" and staff_active='Y'   
        group by id_staff, day, month,year
        order by id_staff
        ";
      //  echo $sql;exit();
         $query = $this->db->query($sql);
        return $query->result_array();
        
    }
    
    function get_qr(){
        
        $this->db->select('*');
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $query = $this->db->get('key_code');
        
        return $query->row();
    }
    
    function update_qr($qr){
        
        $this->db->set('current_key', $qr);
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->update('key_code');
        
    }

    function get_holidays($month=null, $year=null, $type='array'){

        $this->db->select('date(holiday_date) holiday_date, holiday_day, holiday_reason');
        if(null!= $month){
            $this->db->where('month(holiday_date)', $month);
        }
        if(null!=$year){
            $this->db->where('year(holiday_date)', $year);
        }
        
        if($this->session->userdata('common_products')=='No'){
            $this->db->where('business_id', $this->session->userdata('businessid'));
        }
        
        $query = $this->db->get('holidays');
        
        //echo $query;
        if(null==$type || $type != 'array'){
            return $query->result();
        }else {
            return $query->result_array();
        }
    }    
    
    function get_calendar_holidays($month=null, $year=null, $type='array'){

        $this->db->select('id_holidays as id, date(holiday_date) start,  DATE_ADD(holiday_date, INTERVAL 1 DAY) end, holiday_reason as title, "bg-warning" as className, "font-size:10px; color:#000;" as style, "holiday" as event_type' );
        if(null!= $month){
            $this->db->where('month(holiday_date)', $month);
        }
        if(null!=$year){
            $this->db->where('year(holiday_date)', $year);
        }
        if($this->session->userdata('common_products')=='No'){
            $this->db->where('business_id', $this->session->userdata('businessid'));
        }
        
        $query = $this->db->get('holidays');
        
        //echo $query;
        if(null==$type || $type != 'array'){
            return $query->result();
        }else {
            return $query->result_array();
        }
    }    
    
    function check_holiday($date){
        $this->db->select('holiday_date');
        $this->db->where('holiday_date', $date);
        if($this->session->userdata('common_products')=='No'){
            $this->db->where('business_id', $this->session->userdata('businessid')); 
        }
        
        $q = $this->db->get('holidays');
        return $q->row();
    }
    
    function get_leave_types(){
        
        $this->db->select('*');
        $query = $this->db->get('leave_type');
        
         return $query->result_array();
    }
    
    
    function get_staff_leaves($month, $year, $staffid){
        
        $this->db->select('date(staff_leave_date) leave_date, leave_reason');
        $this->db->where('month(staff_leave_date)', $month);
        $this->db->where('year(staff_leave_date)', $year);
        $this->db->where('staff_id', $staffid);
        $this->db->where('staff_leave_status', 'Active');
        $query = $this->db->get('staff_leaves');
        
        //echo $query;
        
        return $query->result_array();
        
    }
    
    
    function get_calendar_leaves($month=null, $year=null, $businessid=null, $type='array'){
        
        $this->db->select('id_staff_leaves as id, date(staff_leave_date) start,  DATE_ADD(staff_leave_date, INTERVAL 1 DAY) end, concat(upper(staff.staff_fullname), "\n " , upper(ifnull(leave_type,""))," - ", leave_reason) as title, "bg-pink text-white" as className, "font-size:10px; color:#fff;" as styleName, "leave" as event_type' );
        $this->db->join('staff','staff.id_staff = staff_leaves.staff_id');
        if(null!= $month){
            $this->db->where('month(staff_leave_date)', $month);
        }
        if(null!=$year){
            $this->db->where('year(staff_leave_date)', $year);
        }
        
        $this->db->where('staff.business_id', $this->session->userdata('businessid'));
        $this->db->where('staff_leave_status', 'Active');
        $query = $this->db->get('staff_leaves');
        
        //echo $query;
        if(null==$type || $type != 'array'){
            return $query->result();
        }else {
            return $query->result_array();
        }
    }
    
    function check_leaves($staffid, $date){
        
        $this->db->select('staff_id', 'staff_leave_date');
        $this->db->where('staff_id', $staffid);
        $this->db->where('staff_leave_date', $date);
        $this->db->where('staff_leave_status', 'Active');
        $query = $this->db->get('staff_leaves');
        
        return $query->row();
    }
    
    function getleaveapplications($status="Pending", $staffid=0){
        
        $this->db->select('*');
        $this->db->where('application_status', $status);
        if($staffid>0){
            $this->db->where('staff_id', $staffid);
        }
        $query = $this->db->get('leave_applications');
        
       // echo $query; exit();    
        
        return $query->result_array();
        
    }
    
    function get_remaining_leaves($staffid){
         $sql="select id_staff, staff_fullname, staff_annual_leaves, count(id_staff_leaves) as leaves_taken,
            staff_annual_leaves - count(id_staff_leaves) as remaining_leaves 
            from staff
            left join staff_leaves on staff.id_staff=staff_leaves.staff_id  and year(staff_leave_date)=year(now()) and staff_leaves.staff_leave_status = 'Active'
            Where staff_leaves.staff_id=".$staffid.";";
        $query=$this->db->query($sql);
         return $query->row();
    }
    
    function get_countofapplications(){
        $this->db->select("count(*) as count");
        if($this->input->post('id_loan_application') != null && $this->input->post('id_loan_application') != ''){
            $this->db->where('id_loan_applications', $this->input->post('id_loan_application'));
        }
        if($this->input->post('staff_id') != null && $this->input->post('staff_id') != ''){
            $this->db->where('staff_id', $this->input->post('staff_id'));
        }
        if($this->input->post('staff_name') != null && $this->input->post('staff_name') != ''){
            $this->db->like('staff_name', $this->input->post('staff_name'));
        }
        if($this->input->post('created_on') != null && $this->input->post('created_on') != ''){
            $this->db->like('created_on', $this->input->post('created_on'));
        }
        if($this->input->post('required_loan_amount') != null && $this->input->post('required_loan_amount') != ''){
            $this->db->where('required_loan_amount', $this->input->post('required_loan_amount'));
        }
        if($this->input->post('approved_amount') != null && $this->input->post('approved_amount') != ''){
            $this->db->where('approved_amount', $this->input->post('approved_amount'));
        }
        if($this->input->post('approved_by') != null && $this->input->post('approved_by') != ''){
            $this->db->like('approved_by', $this->input->post('approved_by'));
        }
        if($this->input->post('approved_on') != null && $this->input->post('approved_on') != ''){
            $this->db->like('approved_on', $this->input->post('approved_on'));
        }
        if($this->input->post('installment') != null && $this->input->post('installment') != ''){
            $this->db->where('installment', $this->input->post('installment'));
        }
        if($this->input->post('num_of_months') != null && $this->input->post('num_of_months') != ''){
            $this->db->where('num_of_months', $this->input->post('num_of_months'));
        }
        if($this->input->post('application_status') != null && $this->input->post('application_status') != ''){
            $this->db->where('application_status', $this->input->post('application_status'));
        }
        
       
        $query = $this->db->get('loan_applications');
        
      
        foreach ($query->result() as $row){
            $result=$row->count;
        }
        return $result;
    }
    
    function getloanapplications($status="Pending", $staffid=0){
        
        $this->db->select("id_loan_applications, staff_id, staff_name, date_format(created_on, '%d-%m-%Y') created_on, required_loan_amount, application_status, ifnull(approved_by,'') approved_by, ifnull(approved_on,'') approved_on, num_of_months, installment, approved_amount");
        $this->db->select('CASE WHEN application_status=\'Pending\' THEN concat("<span style=\'cursor:pointer;\' class=\'text-primary\' onclick=\"open_loan_app(\'", loan_applications.id_loan_applications ,"\');\">","<button class=\'btn btn-sm btn-warning\'>Update</button>","</span>") ELSE \'\' END action');        
        if($this->input->post('id_loan_application') != null && $this->input->post('id_loan_application') != ''){
            $this->db->where('id_loan_applications', $this->input->post('id_loan_application'));
        }
        if($this->input->post('staff_id') != null && $this->input->post('staff_id') != ''){
            $this->db->where('staff_id', $this->input->post('staff_id'));
        }
        if($this->input->post('staff_name') != null && $this->input->post('staff_name') != ''){
            $this->db->like('staff_name', $this->input->post('staff_name'));
        }
        if($this->input->post('created_on') != null && $this->input->post('created_on') != ''){
            $this->db->like('created_on', $this->input->post('created_on'));
        }
        if($this->input->post('required_loan_amount') != null && $this->input->post('required_loan_amount') != ''){
            $this->db->where('required_loan_amount', $this->input->post('required_loan_amount'));
        }
        if($this->input->post('approved_amount') != null && $this->input->post('approved_amount') != ''){
            $this->db->where('approved_amount', $this->input->post('approved_amount'));
        }
        if($this->input->post('approved_by') != null && $this->input->post('approved_by') != ''){
            $this->db->like('approved_by', $this->input->post('approved_by'));
        }
        if($this->input->post('approved_on') != null && $this->input->post('approved_on') != ''){
            $this->db->like('approved_on', $this->input->post('approved_on'));
        }
        if($this->input->post('installment') != null && $this->input->post('installment') != ''){
            $this->db->where('installment', $this->input->post('installment'));
        }
        if($this->input->post('num_of_months') != null && $this->input->post('num_of_months') != ''){
            $this->db->where('num_of_months', $this->input->post('num_of_months'));
        }
        if($this->input->post('application_status') != null && $this->input->post('application_status') != ''){
            $this->db->where('application_status', $this->input->post('application_status'));
        }
        $query = $this->db->get('loan_applications');
        
       // echo $query; exit();    
        
        return $query->result_array();
        
    }
    
    function get_countofattendancereq(){

        $this->db->select("count(*) as count");      
        $this->db->join('staff', 'staff.id_staff = attendance_request.staff_id');

        if($this->session->userdata('common_products') == 'No'){
            $this->db->where('attendance_request.business_id', $this->session->userdata('businessid'));
        }elseif($this->session->userdata('ho')=='Yes'){
            $this->db->join('business', 'business.id_business = attendance_request.business_id');
            $this->db->where('business.common_products', 'Yes');
        }else{
            $this->db->where('attendance_request.business_id', $this->session->userdata('businessid'));
        }

        if($this->input->post('id_attendance_request') != null && $this->input->post('id_attendance_request') != ''){
            $this->db->where('id_attendance_request', $this->input->post('id_attendance_request'));
        }
        if($this->input->post('staff_id') != null && $this->input->post('staff_id') != ''){
            $this->db->where('staff_id', $this->input->post('staff_id'));
        }
        if($this->input->post('staff_name') != null && $this->input->post('staff_name') != ''){
            $this->db->like('staff_fullname', $this->input->post('staff_name'));
        }
        if($this->input->post('request_date') != null && $this->input->post('request_date') != ''){
            $this->db->like('request_date', $this->input->post('request_date'));
        }
        if($this->input->post('request_time_in') != null && $this->input->post('request_time_in') != ''){
            $this->db->where('request_time_in', $this->input->post('request_time_in'));
        }
        if($this->input->post('request_time_out') != null && $this->input->post('request_time_out') != ''){
            $this->db->where('request_time_out', $this->input->post('request_time_out'));
        }
        if($this->input->post('approved_by') != null && $this->input->post('approved_by') != ''){
            $this->db->like('approved_by', $this->input->post('approved_by'));
        }
        if($this->input->post('address') != null && $this->input->post('address') != ''){
            $this->db->like('address', $this->input->post('address'));
        }       
        if($this->input->post('request_status') != null && $this->input->post('request_status') != ''){
            $this->db->where('request_status', $this->input->post('request_status'));
        }else {
            $this->db->where('request_status', 'pending');
        }
        
        $query = $this->db->get('attendance_request');
        
       
        foreach ($query->result() as $row){
            $result=$row->count;
        }
        return $result;

    }

    function getattendancerequests(){

        $this->db->select("id_attendance_request, staff_id, staff_fullname staff_name, business.business_name as business, date_format(request_date, '%d-%m-%Y') request_date, request_time_in, request_time_out, ifnull(approved_by,'') approved_by, attendance_request.address, request_status");
        $this->db->select('CASE WHEN request_status = \'pending\' THEN concat("<span style=\'cursor:pointer;\' class=\'text-primary\' onclick=\"approve(\'", id_attendance_request ,"\');\">","<button class=\'btn btn-sm btn-warning\'>Approve</button>","</span>") ELSE \'\' END as approve');        
        $this->db->select('CASE WHEN request_status = \'pending\' THEN concat("<span style=\'cursor:pointer;\' class=\'text-primary\' onclick=\"reject(\'", id_attendance_request ,"\');\">","<button class=\'btn btn-sm btn-danger\'>Reject</button>","</span>") ELSE \'\' END as reject');        
        
        $this->db->join('staff', 'staff.id_staff = attendance_request.staff_id');
        $this->db->join('business', 'business.id_business = attendance_request.business_id');

        if($this->session->userdata('common_products') == 'No'){
            $this->db->where('attendance_request.business_id', $this->session->userdata('businessid'));
        }elseif($this->session->userdata('ho')=='Yes'){
            
            $this->db->where('business.common_products', 'Yes');
        }else{
            $this->db->where('attendance_request.business_id', $this->session->userdata('businessid'));
        }

        if($this->input->post('id_attendance_request') != null && $this->input->post('id_attendance_request') != ''){
            $this->db->where('id_attendance_request', $this->input->post('id_attendance_request'));
        }
        if($this->input->post('staff_id') != null && $this->input->post('staff_id') != ''){
            $this->db->where('staff_id', $this->input->post('staff_id'));
        }
        if($this->input->post('staff_name') != null && $this->input->post('staff_name') != ''){
            $this->db->like('staff_fullname', $this->input->post('staff_name'));
        }
        if($this->input->post('request_date') != null && $this->input->post('request_date') != ''){
            $this->db->like('request_date', $this->input->post('request_date'));
        }
        if($this->input->post('request_time_in') != null && $this->input->post('request_time_in') != ''){
            $this->db->where('request_time_in', $this->input->post('request_time_in'));
        }
        if($this->input->post('request_time_out') != null && $this->input->post('request_time_out') != ''){
            $this->db->where('request_time_out', $this->input->post('request_time_out'));
        }
        if($this->input->post('approved_by') != null && $this->input->post('approved_by') != ''){
            $this->db->like('approved_by', $this->input->post('approved_by'));
        }
        if($this->input->post('address') != null && $this->input->post('address') != ''){
            $this->db->like('address', $this->input->post('address'));
        }       
        if($this->input->post('request_status') != null && $this->input->post('request_status') != ''){
            $this->db->where('request_status', $this->input->post('request_status'));
        }else {
            $this->db->where('request_status', 'pending');
        }
        
        $query = $this->db->get('attendance_request');
        
        //echo $query; exit();    
        
        return $query->result_array();

    }

    function staff_year_attendance($year){
        
      
        
        $sql = "SELECT
                attendance.id_staff,
                attendance.staff_fullname,
                a.month,
                a.year,
                attendance.daysinmonth AS daysinmonth,
                time_in AS present,
            attendance.daysinmonth - time_in AS absent,
            CASE WHEN staff_leaves.leaves IS NULL THEN 0 ELSE staff_leaves.leaves
            END AS leaves,
            holidays.holidays AS holidays
               from (
                   SELECT 'Jan' month, '".$year."' year, 1 monthOrder UNION 
                   SELECT 'Feb' month, '".$year."' year, 2 monthOrder UNION 
                   SELECT 'Mar' month, '".$year."' year, 3 monthOrder UNION 
                   SELECT 'Apr' month, '".$year."' year, 4 monthOrder UNION 
                   SELECT 'May' month, '".$year."' year, 5 monthOrder UNION 
                   SELECT 'Jun' month, '".$year."' year, 6 monthOrder UNION 
                   SELECT 'Jul' month, '".$year."' year, 7 monthOrder UNION 
                   SELECT 'Aug' month, '".$year."' year, 8 monthOrder UNION 
                   SELECT 'Sep' month, '".$year."' year, 9 monthOrder UNION 
                   SELECT 'Oct' month, '".$year."' year, 10 monthOrder UNION 
                   SELECT 'Nov' month, '".$year."' year, 11 monthOrder UNION 
                   SELECT 'Dec' month, '".$year."' year, 12 monthOrder 
                ) AS a JOIN
                (SELECT
                        id_staff,
                         staff_fullname,
                         month(time_in) as monthtimein,
                         case when count(time_in)>0 THEN count(time_in) else 0 END AS time_in,
                         DAYOFMONTH(
                             LAST_DAY(staff_attendance.time_in)
                         ) AS daysinmonth
                     FROM
                         staff_attendance
                     JOIN staff ON staff.id_staff = staff_attendance.staff_id
                     WHERE
                         staff.business_id = 1 AND staff.staff_active = 'Y' AND YEAR(staff_attendance.time_in) = '".$year."'
                     GROUP BY
                         month(time_in),
                         id_staff
                 ) AS attendance ON monthtimein = a.monthOrder
                LEFT JOIN 
                       (SELECT staff_id,
                           month(staff_leave_date) as leavemonth,
                           year(staff_leave_date) as leaveyear,
                           count(*) as leaves
                        FROM staff_leaves 
                        JOIN staff on staff.id_staff=staff_leaves.staff_id
                        WHERE 
                        staff.business_id= ". $this->session->userdata('businessid') ." 
                        AND staff_leave_status = 'Active'                  
                        AND YEAR(staff_leave_date) =  '".$year."'
                        GROUP BY staff_id, month(staff_leave_date)
                        ) As staff_leaves 
                        ON staff_leaves.leavemonth = a.monthOrder and leaveyear = a.year

               LEFT JOIN (
                       SELECT month(holidays.holiday_date) as monthholiday, 
                       year(holidays.holiday_date) as yearholiday, 
                       count(*) as holidays
                       FROM holidays 
                       WHERE 
                       holidays.business_id= ". $this->session->userdata('businessid') ." 		
                       AND YEAR(holiday_date)= '".$year."'  
                       GROUP BY month(holiday_date), year(holiday_date)
                       ) As holidays ON holidays.monthholiday  =a.monthOrder and yearholiday = a.year

               group by id_staff, monthOrder
               order by id_staff, monthOrder";
       // echo $sql; exit();
        $query = $this->db->query($sql);
        
        return $query->result_array();
        
    }

    // FingerPrint
    function get_staff_fingerprint(){
        $this->db->select('id_staff,fcm_id, business_id, staff_fullname,staff_fingerprint,staff_fingerprint_template_base64');
        $this->db->where('s.business_id', $this->session->userdata('businessid'));
        $this->db->where('s.id_staff', $this->input->post('id_staff'));
        $query = $this->db->get('staff s');
        return $query->row();
    }
    function update_staff_fingerprint() {
        $data = array(
            'staff_fingerprint' => $this->input->post('staff_fingerprint', TRUE),
            'staff_fingerprint_template_base64' => $this->input->post('staff_fingerprint_template_base64', TRUE)
        );
        $this->db->set($data);
        $this->db->where('id_staff', $this->input->post('id_staff', TRUE));
        $this->db->update('staff');
        return $this->input->post('id_staff', TRUE);
    }
    function get_all_staff_fingerprints(){
        $this->db->select('id_staff,fcm_id, business_id, staff_firstname,staff_cell,staff_fullname,staff_fingerprint_template_base64');
        //$this->db->where('s.business_id', $this->session->userdata('businessid'));
        $this->db->where('s.staff_fingerprint_template_base64 IS NOT NULL');
        $query = $this->db->get('staff s');
        return $query->result();
    }
    // FingerPrint End
}
