<?php

class Staffapp_model extends CI_Model {

    function __construct() {
        // Call the Model constructor
        parent::__construct();
    }
    
    
    public function updateFCMToken($row){
        $res = $this->db->query("UPDATE staff SET fcm_id='".$row['fcmid']."' WHERE id_staff=".$row['idStaff']);
        return $this->printResponse("true","Registration Successfull");
    }
    
    public function checkMobileNumber($cell){
        $resp = $this->db->query("SELECT * FROM staff WHERE staff_cell=".$cell);
        if($resp->num_rows()>0){
            $row = $resp->result_array();
            return $this->printResponse("true","Number Registerd","staff",$row);
        }else{
            return $this->printResponse("false","No User Found with this Cell Number");
        }
    }
    
    public function login($r){
       
        $fcm_id= $r['fcm_id'];
        $sql = "SELECT id_staff, staff_fullname, staff_firstname, staff_lastname, staff_cell, staff_email, 
                staff_eid, CONCAT('". base_url() ."assets/images/staff/', staff_image)  as staff_image, staff_comment, staff_shared, id_business, business_name, 
                left(business_opening_time,2) as business_opening_time, left(business_closing_time,2) as business_closing_time, CONCAT('". base_url() ."assets/images/business/', business_logo)  as logo, 
                    fcm_id, 'correct' as status, staff_annual_leaves
                FROM staff
                join business on business.id_business = staff.business_id
                where staff_active='Y'
                and fcm_id='".$r['fcm_id']."' 
                and staff_cell='".$r['cellNumber']."' ; ";
                
//and staff_firstname='".$r['username']."' 

        $resp = $this->db->query($sql);
        $staff = $resp->row();
        
        if($resp->num_rows()>0){
           $row = $resp->result_array();
            return $this->printResponse("true","Login Succesfull","staff",$row);
        } else {

            $sql = "SELECT id_staff,  ifnull(fcm_id,'') as fcm_id
                FROM staff                
                where staff_active='Y'
                and staff_firstname='".$r['username']."' 
                and staff_cell='".$r['cellNumber']."'; ";

            $resp1 = $this->db->query($sql);
            $staff = $resp1->row();
            if($resp1->num_rows()>0){
                if($staff->fcm_id == null || $staff->fcm_id==''){
                    
                    $sql1="select fcm_id from staff  where fcm_id = '".$r['fcm_id']."' and staff_active = 'Y' ;";
                    $fcmusedquery =  $this->db->query($sql1);
                    $fcmused = $fcmusedquery->row();
                    
                    if($fcmusedquery->num_rows()==0){
                    
                        $this->db->set('fcm_id', $fcm_id);
                        $this->db->where('id_staff', $staff->id_staff);
                        $this->db->update('staff');

                        $sql = "SELECT id_staff, staff_fullname, staff_firstname, staff_lastname, staff_cell, staff_email, 
                            staff_eid, CONCAT('". base_url() ."assets/images/staff/', staff_image)  as staff_image, staff_comment, staff_shared, id_business, business_name, 
                            ifnull(fcm_id,'') as fcm_id, left(business_opening_time,2) as business_opening_time, left(business_closing_time,2) as business_closing_time, 
                            CONCAT('". base_url() ."assets/images/business/', business_logo)  as logo
                            FROM staff
                            join business on business.id_business = staff.business_id
                            where staff_active='Y'
                            and staff_firstname='".$r['username']."' 
                            and staff_cell='".$r['cellNumber']."'; ";
                        $resp2 = $this->db->query($sql);
                        $row = $resp2->result_array();
                        return $this->printResponse("true","Login Succesfull","staff",$row);
                    }else{
                        return $this->printResponse("false","fcm ID already in Use");
                    }
                }else{
                    return $this->printResponse("false","Please Use Registered Cell Number");
                }
            }else {
                return $this->printResponse("false","Invalid User Password");
            }
        }
    }


    public function getVisits($staffId, $startDate, $endDate, $businessId){
        $resp = $this->db->query("SELECT id_customer_visits, customer_name, customer_cell, service_name, staff_id, staff_name, 
            date_format(visit_services.visit_service_start,'%Y-%m-%d %H:%i:%s') as service_start,
            date_format(visit_services.visit_service_end,'%Y-%m-%d %H:%i:%s') as service_end,
            YEAR(visit_services.visit_service_start) as year, 
           MONTH(visit_services.visit_service_start) as month, 
           DAY(visit_services.visit_service_start) as day, 
           Hour(date_format(visit_services.visit_service_start,'%Y-%m-%d %H:%i:%s')) as start_hour,
           Minute(date_format(visit_services.visit_service_start,'%Y-%m-%d %H:%i:%s')) as start_minute,
           TIMESTAMPDIFF(MINUTE, visit_services.visit_service_start, visit_services.visit_service_end)  as Duration, 
            customer_visits.business_id, business.business_name, customer_visits.visit_status,
            Case when customer_visits.business_id = '".$businessId."' then
                'same branch'
            Else
                'other branch'
            End as branch,
            visit_color, visit_color_type
            FROM customer_visits
            join customers on customers.id_customers = customer_visits.customer_id
            join visit_services on visit_services.customer_visit_id = customer_visits.id_customer_visits
            and visit_service_status='Active' 
            join visit_service_staffs on visit_service_staffs.visit_service_id = visit_services.id_visit_services 
            and visit_service_staff_status='Active'             
            join business on customer_visits.business_id = business.id_business
            where visit_status in ('open', 'invoiced')  
            and date(visit_services.visit_service_start) >= '".$startDate." 00:00:00'        
            and date(visit_services.visit_service_start) <= '".$endDate." 23:59:00'    
            and visit_service_staffs.staff_id= '".$staffId."';");
        
        if($resp->num_rows()>0){
            $row = $resp->result_array();
            return $this->printResponse("true",$resp->num_rows(),"staff",$row);
        }else{
            return $this->printResponse("false","0", "No records found");
        }
    }

    public function commission_details($staff_id, $startdate, $enddate,$business_id=0, $typeid, $categoryid){
        
         //  $date = strtotime("+ 1 days", strtotime($enddate));
      //  $enddate = date("Y-m-d", $date);

        $this->db->select("reference_invoice_number, staff_fullname, invoice.customer_name, invoice_staff.staff_id, invoice_staff.service_type, invoice_staff.service_category, invoice_staff.service_name, invoice_staff.additional_staff, bs.commission_perc staff_commission, bs.helper_perc helper_commission, invoice_staff.paid as final_price, reference_invoice_number, "
                . "date_format(invoice_date,'%Y-%m-%d %H:%i') as staff_service_date, invoice_staff.invoice_id, invoice_details.invoice_discount, invoice_details.discounted_price,  invoice_details.final_price as final_price1, date_format(invoice.invoice_date, '%Y-%m-%d %H:%i') as customer_visit_date");
        
        $this->db->join("invoice", " invoice.id_invoice = invoice_staff.invoice_id");
        $this->db->join("staff", "staff.id_staff = invoice_staff.staff_id");
        $this->db->join("invoice_details", "invoice_staff.invoice_detail_id= invoice_details.id_invoice_details");
        $this->db->join("business_services bs", " invoice_details.service_id = bs.id_business_services");
        $this->db->where("invoice_status='valid'");
        $this->db->where("invoice_type='service'");
        if($business_id==0){
            $this->db->where('invoice.business_id', $this->session->userdata('businessid'));
        }else{
            $this->db->where('invoice.business_id', $business_id);
        }
       // $this->db->where('reference_invoice_number <>', 'bad debts');
       // $this->db->where('ifnull(invoice.reference_invoice_number,"")=""');
        $this->db->where('date(invoice_date) >=', $startdate);
        $this->db->where('date(invoice_date) <=', $enddate);
        $this->db->where('invoice_staff.staff_id', $staff_id);
        
        if($typeid !== 'all'){
            $this->db->where('invoice_details.service_type =', $typeid);
        }
        if($categoryid !== 'all'){
            $this->db->where('invoice_details.service_category =', $categoryid);
        }
        //$this->db->group_by("staff_id");
        $resp = $this->db->get('invoice_staff');
      
        if($resp->num_rows()>0){
            $row = $resp->result_array();
            return $this->printResponse("true",$resp->num_rows(),"performance",$row);
        }else{
            return $this->printResponse("false","0", "No records found");
        }
        
        
    }
    
    function retail_commission_details($staff_id, $startdate, $enddate, $business_id=0) {

      //  $date = strtotime("+ 1 days", strtotime($enddate));
      //  $enddate = date("Y-m-d", $date);

        $this->db->select("reference_invoice_number, invoice.customer_name,  staff_fullname, staff_id, business_brand_name, 
                bp.product, bp.qty_per_unit, bp.measure_unit, invoice_products.invoice_qty,
                bp.commission commission, 
               invoice_products.paid, 
               date_format(invoice_date, '%Y-%m-%d %H:%i') as invoice_date, 
               invoice_id, invoice_products.discounted_price as discounted_price, round((invoice_products.discounted_price*bp.commission)/100,2) as staff_commission", false);
        $this->db->join("business_products bp", "invoice_products.product_id = bp.id_business_products ");
        $this->db->join("business_brands bb", "bb.id_business_brands = bp.brand_id");
        $this->db->join("invoice", "invoice.id_invoice = invoice_products.invoice_id");
        $this->db->join("staff", "staff.id_staff = invoice_products.staff_id");
        
        $this->db->where("invoice_status='valid'");
        if($business_id==0){
            $this->db->where('invoice.business_id', $this->session->userdata('businessid'));
        }else{
            $this->db->where('invoice.business_id', $business_id);
        }
       // $this->db->where('reference_invoice_number <>', 'bad debts');
       // $this->db->where('ifnull(invoice.reference_invoice_number,"")=""');
        $this->db->where('date(invoice_date) >=', $startdate);
        $this->db->where('date(invoice_date) <=', $enddate);
        $this->db->where('staff_id', $staff_id);
        //$this->db->group_by("staff_id");
        $resp = $this->db->get('invoice_products');
       // echo $query; exit();
        
       if($resp->num_rows()>0){
            $row = $resp->result_array();
            return $this->printResponse("true",$resp->num_rows(),"performance",$row);
        }else{
            return $this->printResponse("false","0", "No records found");
        }
        
    }
    
    
     function get_services_types($business_id) {
        $data=[];
        
        $this->db->select('id_service_types, business_id, service_type, concat("'. 'assets/images/servicetype/' .'", ifnull(service_type_image, "nu.jpg")) as service_type_image, service_type_active, order_id, "servicetype" as "flag"');
        $this->db->where('business_id', $business_id);
        $this->db->where('service_type_active', 'Yes');
        
        $subQuery1 = $this->db->get('service_type');
        $services=$subQuery1->result_array();
        
        $this->db->select('id_package_type as "id_service_types", business_id, service_type, concat("'. 'assets/images/servicetype/' .'", ifnull(service_type_image, "nu.jpg")) as service_type_image, service_type_active, order_id, "packagetype" as "flag"');
        $this->db->where('business_id', $business_id);
        $this->db->where('service_type_active', 'Yes');
        
        $subQuery2 = $this->db->get('package_type');
        $packages=$subQuery2->result_array();
        //$query = $this->db->query("select * from (".$subQuery1." UNION ".$subQuery2.") as unionTable order by flag desc, order_id asc");
        
        $data = array_merge($services, $packages);
        //var_dump($data); exit();
        //return $data;
        if(sizeof($data)>0){
            return $this->printResponse("true", sizeof($data), "servicetypes", $data);
        } else {
            return $this->printResponse("false", sizeof($data), "servicetypes", "No Record Found");
        }
    }
    
    function get_services_categories($service_type_id, $service_type_flag, $business_id=0) {
        
        
        if($service_type_flag==="packagetype"){
            $this->db->select('*, concat("assets/images/category/", ifnull(service_category_image, "nu.png")) as service_category_image, id_package_category as id_service_category, "packagetype" as "flag"');
           // $this->db->where('business_id', $this->session->userdata('businessid'));
            $this->db->where('service_category_active', 'Yes');
            $this->db->where('package_type_id', $service_type_id);
            $this->db->order_by('order_id', 'ASC');
            $query = $this->db->get('package_category');            
        } else {
            $this->db->select('*, concat("assets/images/category/", ifnull(service_category_image, "nu.png")) as service_category_image, "servicetype" as "flag"');
           // $this->db->where('business_id', $this->session->userdata('businessid'));
            $this->db->where('service_category_active', 'Yes');
            $this->db->where('service_type_id', $service_type_id);
            //$this->db->order_by('id_service_category', 'ASC');
            $this->db->order_by('order_id', 'ASC');
            $query = $this->db->get('service_category');
        }
        
        $count=$query->num_rows();
        
        if($count > 0){
            $row = $query->result_array();
            return $this->printResponse("true", $count, "servicecategories", $row);
        }else {
            return $this->printResponse("false","0", "servicecategories", "No Record Found");
        }
    }
    
    
    public function printResponse($status,$msg,$key=null,$data=null){
        if($key && $data){
            if(is_array($data)){
                $arr = array();
                foreach($data as $k=>$r){
                    $arr[] = $this->getFormat($r);
                }
                $r = array(array(
                "status"=>array($status,"string"),
                "message"=>array($msg,"string"),
                "$key"=>array($arr,'array')),
                'struct');
            }else{
                $r = array(array(
                "status"=>array($status,"string"),
                "message"=>array($msg,"string"),
                "$key"=>$this->getFormat($data)),
                'struct');
            }
        }else{
            $r = array(array(
            "status"=>array($status,"string"),
            "message"=>array($msg,"string")),'struct');
        }
        return $r;
    }
    
    public function getFormat($r){
        $arr = array();
        foreach($r as $key => $val){
            if(!is_array($val)){
                if(strcmp(gettype($val), "NULL")!=0)
                $arr[$key] = array($val,"string");
            }
        }
        return array($arr,'struct');
    }
    
    public function getFormat2($r){
        $arr = array();
        foreach($r as $key => $val){
            
            if(!is_array($val)){
                if(strcmp(gettype($val), "NULL")!=0)
                $arr[$key] = array($val,"string");
            }
        }
        //print_r($arr);
        return array($arr,'struct');
    }
    
    
    
    function sentNotif($title, $staffid){
        
        $this->db->select('count(*) as appointments, fcm_id');
        $this->db->where('staff.id_staff',$staffid);
        $query = $this->db->get('staff');
        $row = $query->row();
       
        if(null!==$row->fcm_id){
        
            $fcmId = $row->fcm_id;
            $appointments = $row->appointments;        
            $url='https://fcm.googleapis.com/fcm/send';
        
            
            $data = array(
                "to" => $fcmId,
                "notification" => array(
                    'body' => 'You have '.$appointments.' appointments today!',
                    "title" => $title
                )                
            );
            
            $opts = array(
               'http' => array(
                'method'  => 'POST',
                'content' => json_encode( $data ),
                'header'=>  "Content-Type: application/json\r\n" .
                            "Accept: application/json\r\n" . 
                            "Authorization: key=AAAARZOnnvk:APA91bFS43lli-5xA-RBgNYxYaJmsn8wU5Z02QKzQgsjh71KGcwnsf7YOrdGKsNPA5mJWvCllP5sF6u1jQcAwc9K6UGM009XBv-JvyN4DHnMyl9owsk2BP-p3PcCzKyalbCc-t26JZ_v"
                )            
            );
            
            $context = stream_context_create($opts);
            
            $file = file_get_contents('https://fcm.googleapis.com/fcm/send', false, $context);
//            $ch = curl_init();
//            curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
//            curl_setopt( $ch,CURLOPT_POST, true );
//            curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
//            curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
//            curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
//            curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $msg ) );
//            $result = curl_exec($ch );
//            curl_close( $ch );
            $resp = json_decode($file);
           // print_r($resp);
       
            if($resp->success == 1){
                return true;
            }else{
                return false;
            }
        }else {
            return false;
        }
    }
    
    public function get_staff_for_notifications(){
        $today = date('Y-m-d');
        $tomorrow = date('Y-m-d H:i:s', strtotime('tomorrow'));
        
        $resp = $this->db->query("SELECT id_customer_visits, staff_id, staff_name, 
           date_format(visit_services.visit_service_start,'%Y-%m-%d %H:%i:%s') as service_start,
           date_format(visit_services.visit_service_end,'%Y-%m-%d %H:%i:%s') as service_end,
           YEAR(visit_services.visit_service_start) as year, 
           MONTH(visit_services.visit_service_start) as month, 
           DAY(visit_services.visit_service_start) as day, 
           TIMESTAMPDIFF(MINUTE, visit_services.visit_service_start, visit_services.visit_service_end)  as Duration, 
           customer_visits.business_id, business.business_name
           FROM customer_visits
           join customers on customers.id_customers = customer_visits.customer_id
           join visit_services on visit_services.customer_visit_id = customer_visits.id_customer_visits
           and visit_service_status='Active'
           join visit_service_staffs on visit_service_staffs.customer_visit_id = customer_visits.id_customer_visits
           and visit_service_staff_status='Active' 
           and visit_service_staffs.visit_service_id = visit_services.id_visit_services
           join staff on visit_service_staffs.staff_id=staff.id_staff
           join business on customer_visits.business_id = business.id_business
           where visit_status='open' 
           and ifnull(staff.fcm_id,'')!=''
           and date(visit_services.visit_service_start) = '".$today."';");

        return $resp->result_array();
    }
    
    public function mark_staff_attendance($cellNumber, $fcm_id, $key, $date, $time, $businessId, $address, $longitude, $latitude){
        
        $this->db->select("id_staff");
        $this->db->where("staff_cell", $cellNumber);
        $this->db->where("ifnull(fcm_id,'')", $fcm_id);
        $this->db->where("business_id", $businessId);
        $query = $this->db->get("staff");
        
        //$sql="select id_staff from staff where business_id = '".$businessId."' and staff_cell = '".$cellNumber."' and fcm_id = '".$fcm_id."';";
        //$query = $this->db->query($sql);
        
        
        $staff=$query->row();
        
        if($query->num_rows() > 0){
            $location='';
            $staff_id=$staff->id_staff;
            
            $this->db->select("*, ifnull(time_out,'') as t_out", true);
            $this->db->where('staff_id',$staff_id);
            $this->db->where('date(time_in) =', $date);
            $exists = $this->db->get("staff_attendance");
            
            $row = $exists->row();
            
            $t=explode(":", $time);
            
            if($exists->num_rows() > 0 && $t[0] < 14){
                return $this->printResponse("false","Attendance already marked for today");
            } else if($exists->num_rows() > 0 && $t[0] > 14 && $row->t_out == ''){
                $data = array('time_out' => $date.' '.$time);
                
                $this->db->where('id_staff_attendance', $row->id_staff_attendance);
                $this->db->update('staff_attendance', $data);
                        
                $qr= $this->getRandomString(8);

                $this->db->set('current_key', $qr);
                $this->db->where('business_id', $this->session->userdata('businessid'));
                $this->db->update('key_code');


                return $this->printResponse("true","Time Out Marked Succesfully","staff",$staff);
            } else {
                
                ///verify the current key here
                $sql1="select current_key, serverurl from key_code where business_id = '".$businessId."';";
        
                $query1 = $this->db->query($sql1);
                $row1 = $query1->row();
                if($query1->num_rows() > 0){
                    
                    $key_code = $row1->current_key;
                    if($key_code == $key){
                        $data = array(
                                'business_id' => $businessId,
                                'staff_id' => $staff_id,
                                'time_in' => $date.' '.$time,
                                'address'=>$address,
                                'longitude'=>$longitude,
                                'latitude'=>$latitude
                            );
                        
                        $this->db->insert('staff_attendance', $data);
                        
                        $qr= $this->getRandomString(8);
            
                        $this->db->set('current_key', $qr);
                        $this->db->where('business_id', $this->session->userdata('businessid'));
                        $this->db->update('key_code');
            
                       
                        return $this->printResponse("true","Time In Marked Succesfully","staff",$staff);
                    } else {
                        return $this->printResponse("true","Expired or Invalid Key Code. Wait for new code before retrying.","staff",$staff);
                    }
                } else {
                    return $this->printResponse("true","Key Code not available at the server","staff",$staff);
                }
            }
        }else {
            return $this->printResponse("false","Please Use Registered Cell Number");
            //return $this->printResponse("false", $businessId);
        }
        
        
        
    }

    function getRandomString($length = 8) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $string = '';

        for ($i = 0; $i < $length; $i++) {
            $string .= $characters[mt_rand(0, strlen($characters) - 1)];
        }

        return $string;
    }    

//**********HRM WORK***********//
    
    
    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 remainin_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.";";
        
        $resp = $this->db->query($sql);
        
        if($resp->num_rows()>0){
           $row = $resp->result_array();
           return $this->printResponse("true",$resp->num_rows(),"staff",$row);
        }else{
            return $this->printResponse("false","0", "No records found");
        }   
        
        
    }
    
    function get_leave_types($businessid){
        
                
        $this->db->select("id_leave_type, leave_type");        
        $resp = $this->db->get("leave_type");
        
        if($resp->num_rows()>0){
            $row = $resp->result_array();
            return $this->printResponse("true",$resp->num_rows(),"staff",$row);
        }else{
            return $this->printResponse("false","0", "No records found");
        }   
    }
    
    function leave_application($staff_id, $fcm_id, $required_from, $required_to, $business_id, $leave_type, $comment){
    
        $this->db->select("id_staff, staff_fullname");
        $this->db->where("id_staff", $staff_id);
        $this->db->where("ifnull(fcm_id,'')", $fcm_id);        
        $this->db->where("business_id", $business_id);
        $query = $this->db->get("staff");
        
        
        $staff = $query->row();
        
        //return $this->printResponse("false", print_r($query->num_rows()),"0");
        
        if($query->num_rows() == 1){
            
           // return $this->printResponse("false", $staff->staff_fullname,"0");
            
            //insert into leave application
            $data = array(
                'staff_id' => $staff->id_staff,
                'staff_name' => $staff->staff_fullname,
                'required_from' => $required_from,
                'required_to' => $required_to,
                'leave_type' => $leave_type,
                'comments' => $leave_type." - ".$comment,
                'created_by' => $staff->staff_fullname
                
            );
            
            $this->db->insert('leave_applications', $data);
            
            return $this->printResponse("true","Leave Application Forwarded Succesfully","staff");
            
        } else {
            return $this->printResponse("false","This Staff ID is not allowed to use this cellphone","0");
        }
        
    }
    
    
    function adv_salary_application($staff_id, $fcm_id, $amount, $comment){
    
        $this->db->select("id_staff, staff_fullname");
        $this->db->where("id_staff", $staff_id);
        $this->db->where("ifnull(fcm_id,'')", $fcm_id);        
        $query = $this->db->get("staff");
        
        $staff = $query->row();
        
        //return $this->printResponse("false", print_r($query->num_rows()),"0");
        
        if($query->num_rows() == 1){
            
           // return $this->printResponse("false", $staff->staff_fullname,"0");
            
            //insert into leave application
            $data = array(
                'staff_id' => $staff->id_staff,
                'staff_name' => $staff->staff_fullname,
                'amount' => $amount,
                
                'comments' => $comment,
                'created_by' => $staff->staff_fullname
                
            );
            
            $this->db->insert('adv_salary_applications', $data);
            
            return $this->printResponse("true","Application For Advance Salary of ".$amount." Forwarded Succesfully","staff");
            
        } else {
            return $this->printResponse("false","This Staff ID is not allowed to use this cellphone","0");
        }
        
    }
    
    function loan_application($staff_id, $fcm_id, $amount, $num_of_months, $comment){
    
        $this->db->select("id_staff, staff_fullname");
        $this->db->where("id_staff", $staff_id);
        $this->db->where("ifnull(fcm_id,'')", $fcm_id);          
        $query = $this->db->get("staff");
        
        $staff = $query->row();
        
        //return $this->printResponse("false", print_r($query->num_rows()),"0");
        
        
        $installment = $amount/$num_of_months;
        
        if($query->num_rows() == 1){
            
           // return $this->printResponse("false", $staff->staff_fullname,"0");
            
            //insert into leave application
            $data = array(
                'staff_id' => $staff->id_staff,
                'staff_name' => $staff->staff_fullname,
                'required_loan_amount' => $amount,
                'num_of_months' => $num_of_months,
                'installment' => round($installment,2),
                'comments' => $comment,
                'created_by' => $staff->staff_fullname
                
            );
            
            $this->db->insert('loan_applications', $data);
            
            return $this->printResponse("true","Application For Loan of ".$amount." Forwarded Succesfully","staff");
            
        } else {
            return $this->printResponse("false","This Staff ID is not allowed to use this cellphone","0");
        }
        
    }

    function staff_month_attendance_detail($staffid, $year, $month){
        $margin = 0;
       
       $this->db->select('timein_margin');
       $this->db->where('id_staff', $staffid);
       $this->db->join('staff','staff.business_id = business.id_business');
       $m = $this->db->get('business');
       $businss_margin = $m->row(); 
      // if($m->num_rows() > 0){
           $margin = $businss_margin->timein_margin;
      // }
        
        
        $this->db->select('id_staff, staff_fullname, staff_image, staff_salary, provident_fund_rate, 
                week_day_off, deduction_days_absent, deduction_days_late, total_late_allowed, 
                total_absents_allowed, salary_monthly_tax, salary_type, day_start_time');
        $this->db->join('deduction_policy', 'id_deduction_policy = staff.deduction_policy');
        $this->db->where('id_staff', $staffid);
        $qresult = $this->db->get('staff');
        $q = $qresult->row();
        
        
        //print_r($q);exit();
        $week_day_off = $q->week_day_off;
        $day_start_time = $q->day_start_time;
        
        
        $sql = "SELECT 
                mDays.Date,
                mDays.Day,
                '".$week_day_off."' as week_day_off,
                ".$q->id_staff." as id_staff, 
                '".$q->staff_fullname."' AS staff_fullname,
                attendance.time_in,
                attendance.time_out,
                staff_leaves.staff_leave_date,
                staff_leaves.leave_reason,
                holidays.holiday_date,
                holidays.holiday_reason,
                CONCAT(ROUND(TIMESTAMPDIFF(MINUTE, attendance.time_in, attendance.time_out) / 60,2),' Hours') AS 'Work_Hours',
                CASE WHEN
                        IFNULL(attendance.time_in, '') != '' AND attendance.time_in != CONCAT(DATE(attendance.time_in), ' 00:00:00')
                    THEN 1
                    ELSE 0
                END AS 'Present',
                CASE
                    WHEN INSTR('".$week_day_off."',  mDays.Day) > 0 AND IFNULL(attendance.time_in, '') = '' THEN 0
                    WHEN '".$week_day_off."' Not Like concat('%',mDays.Day,'%') AND IFNULL(attendance.time_in, '') = '' 
                        AND IFNULL(staff_leave_date, '') = '' 
                        AND IFNULL(holidays.holiday_date,'') = ''  THEN 1 
                    WHEN IFNULL(holidays.holiday_date,'') != '' THEN 0    
                    WHEN IFNULL(staff_leave_date, '') != '' THEN 0
                    ELSE 0
                END AS 'Absent',
                CASE
                    WHEN
                        TIMESTAMPDIFF(MINUTE,
                            CONCAT(mDays.Date, ' ', '".$day_start_time."'),
                            attendance.time_in) > ".$margin."
                    THEN
                        1
                    WHEN attendance.time_in = CONCAT(DATE(attendance.time_in), ' 00:00:00') THEN 0
                    ELSE 0
                END AS 'Late',
                CASE
                    WHEN IFNULL(staff_leave_date, '') = '' THEN 0
                    WHEN '".$week_day_off."' NOT LIKE concat('%',mDays.Day,'%') AND IFNULL(holidays.holiday_date,'') = '' AND IFNULL(staff_leave_date, '') != '' AND IFNULL(attendance.time_in, '') = '' THEN 1        
                    ELSE 0
                END AS 'Leaves',
                CASE 
                    WHEN IFNULL(holidays.holiday_date,'') != '' THEN 1
                    WHEN INSTR('".$week_day_off."', mDays.Day) > 0 THEN 1
                    ELSE 0 
                END AS 'Holiday',
                attendance.address,   
                business.business_opening_time,
                business.business_closing_time
            FROM (SELECT 
                    FROM_UNIXTIME(UNIX_TIMESTAMP(CONCAT('".$year."-".$month."-', n)), '%Y-%m-%d') AS Date,
                    FROM_UNIXTIME(UNIX_TIMESTAMP(CONCAT('".$year."-".$month."-', n)), '%a') AS Day
                            FROM
                    (SELECT 
                                    (((b4.0 << 1 | b3.0) << 1 | b2.0) << 1 | b1.0) << 1 | b0.0 AS n
                            FROM
                                    (SELECT 0 UNION ALL SELECT 1) AS b0, (SELECT 0 UNION ALL SELECT 1) AS b1, (SELECT 0 UNION ALL SELECT 1) AS b2, (SELECT 0 UNION ALL SELECT 1) AS b3, (SELECT 0 UNION ALL SELECT 1) AS b4) t
                            WHERE
                                    n > 0 AND n <= DAY(LAST_DAY('".$year."-".$month."-01'))) AS mDays
            LEFT JOIN
                (SELECT staff_id, time_in, time_out, address
                FROM staff_attendance
                WHERE
                    MONTH(time_in) = ".$month."
                    AND YEAR(time_in) = '".$year."'
                    AND staff_id = ".$q->id_staff.") AS attendance ON DATE(time_in) = mDays.Date
            LEFT JOIN
                (SELECT id_staff,
                        staff_fullname,
                        staff_image,
                        week_day_off,
                        business_id
                FROM staff WHERE id_staff = ".$q->id_staff.") AS staff ON staff.id_staff = attendance.staff_id
            LEFT JOIN 
                (SELECT staff_id,
                        staff_leave_date,
                        leave_reason
                 FROM staff_leaves 
                 WHERE staff_id = ".$q->id_staff."
                 AND staff_leave_status = 'Active' 
                 AND MONTH(staff_leave_date) =  ".$month."
                 AND YEAR(staff_leave_date) =  '".$year."') As staff_leaves 
                 ON date(staff_leaves.staff_leave_date) = mDays.Date
            LEFT JOIN (
		SELECT holiday_date,
                holiday_day,
                holiday_reason
                FROM holidays WHERE";
        
        if($this->session->userdata('common_products')=='No'){
            $sql .= " business_id= ".$this->session->userdata('businessid')." AND ";
        }
        
        $sql .= " MONTH(holiday_date) = ".$month."
                AND YEAR(holiday_date)='".$year."'       
                ) As holidays ON holiday_date = mDays.Date
            LEFT JOIN
                (SELECT id_business, business_opening_time, business_closing_time
                FROM business) AS business ON staff.business_id = business.id_business
            ORDER BY mDays.Date;";
        
       // echo $sql; exit();
        
        $query = $this->db->query($sql);
        
        if($query->num_rows() > 0){
            $row = $query->result_array();
            return $this->printResponse("true","Attendance","staff",$row);
        }else{
            return $this->printResponse("false","No Records Found for this Staff");
        }   
    }
    
    function leave_application_report($staffid){
        
        $this->db->select('id_leave_applications as id, leave_type, required_from as from, required_to as to, application_status, approved_on');
        $this->db->where('staff_id', $staffid);
        $this->db->order_by('created_on', 'desc');
        $query = $this->db->get('leave_applications'); 
        
        
        if($query->num_rows() > 0){
            $row = $query->result_array();
            return $this->printResponse("true","Leave Applications","staff",$row);
        }else{
            return $this->printResponse("false","No Records Found for this Staff");
        }   
    }
    
    function adv_salary_application_report($staffid){
        
        $this->db->select('id_adv_salary_applications as id, amount, number_of_months, application_status, approved_on');
        $this->db->where('staff_id', $staffid);
        $this->db->order_by('created_on', 'desc');
        $query = $this->db->get('adv_salary_applications'); 
         
                
        if($query->num_rows() > 0){
            $row = $query->result_array();
            return $this->printResponse("true","Adv. Salary Applications","staff",$row);
        }else{
            return $this->printResponse("false","No Records Found for this Staff");
        }   
    }
    
    function loan_application_report($staffid){
        
        $this->db->select('id_loan_applications as id, required_loan_amount as amount, num_of_months, installment, application_status, approved_on');
        $this->db->where('staff_id', $staffid);
        $this->db->order_by('created_on', 'desc');
        $query = $this->db->get('loan_applications'); 
         
        
        if($query->num_rows() > 0){
            $row = $query->result_array();
            return $this->printResponse("true","Loan Applications","staff",$row);
        }else{
            return $this->printResponse("false","No Records Found for this Staff");
        }   
    }
    
}