<?php

define('CMS__APP_VERSION', 1.0);
header('Content-Type: application/json');

class app extends app_base_class {

    /**
     * ..
     * ====================================================================>
     */
    public function get_location() {
        $locations_arr = $this->select_query("SELECT `Location_ID` as id, `location_code` as code, `Location_Name` as name
            FROM `tbl_employee_location`  ");
        die(json_encode(array('data' => $locations_arr)));
    }

    public function get_employee() {
        $emp_arr = $this->select_query("SELECT `Employee_ID` as employee_id,
            concat(`Employee_FirstName`,' ',`Employee_MiddleName`,' ',`Employee_LastName`) as employee_name,second_lang_name,
                `Employee_MobilePhone` as employee_phone,`fingerprint_code` 
                FROM `tbl_hrm_employee` where leave_date is null and Status_ID = 1");
        die(json_encode(array('data' => $emp_arr)));
    }

    public function get_attendance() {
        $arr = array();
        $query = "SELECT `app_att_id` as attend_id,if(`check_type`=0,'in','out') as check_type,
            DATE(`date_time`) as date,`employee_id`,location_id,time(`date_time`) as time FROM `tbl_checkinout`
            where app_user_id = ? ";
        $stmt = $this->db->query_execute($query, array($this->get_login_user_id()));
        while ($row = $this->db->query_fetch($stmt)) {
            $row['is_new'] = false;
            $arr[$row['attend_id']] = $row;
        }
        die(json_encode(array('data' => array_values($arr))));
    }

    public function add_attendance() {
//        die(print_r($this->_body));
        $body_result = json_decode($this->_body, true);
//        file_put_contents(__DIR__ . '/att.txt', print_r($body_result, true));
        $succ_att_ids = array();
        $err_att_ids = array();
        $err_msgs = null;
        //fill in session since some methods depend on it like for logged id, current year,.. also we need it to 
        //fill permission or it will make logout when call new StockAjax() class or other classes
//        $this->fill_trusto_session();
        //
        if (empty($body_result) || empty($body_result['attendance']) || !is_array($body_result['attendance']))
            $this->die_error('no attendance send to insert them!');
        $att_data = array();
        $logged_id = $this->get_login_user_id();
        $prefix = $this->get_login_data('serial_prefix');
        foreach ($body_result['attendance'] as $row) {
//            echo 'heree';
            $check_request = $this->db->query_execute('select entry_id from tbl_checkinout where app_att_id = ? and app_user_id = ?', array($row['attend_id'], $logged_id));
            if ($this->db->query_result_count($check_request) == 0) {
                if (!empty($row["employee_id"]) && !empty($row["date"]) && !empty($row["time"]) && !empty($row["check_type"])) {
                    $check_type = $row['check_type'] == 'out' ? 1 : 0;
                    $date_time = $row['date'] . ' ' . $row['time'];
                    $att_data = array(
                        $row['employee_id'],
                        $date_time,
                        $check_type,
                        $row['location_id'],
                        $logged_id,
                        $row['attend_id'],
                        $prefix
                    );
                    $att_query = $this->db->query_execute('INSERT INTO `tbl_checkinout`(
                        `employee_id`, `date_time`, `check_type`, `location_id`, `app_user_id`,
                        `app_att_id`, `prefix`) values (?,?,?,?,?,?,?) ', $att_data);
                    if ($att_query) {
                        $succ_att_ids['succ_ids'][] = $row['attend_id'];
                    } else {
                        $err_att_ids['err_att_ids'][] = $row['attend_id'];
                        $err_msgs .= $att_query ? '' : $row['attend_id'] . "<br/>";
                    }
                }
            } else {
                $succ_att_ids['succ_ids'][] = $row['attend_id'];
            }
        }
        $result_arr = array();
        if (count($err_att_ids)) {
            $result_arr['error_info'] = "Error Occured while inserting attendance: " . $err_msgs;
            $result_arr['err_att_ids'] = $err_att_ids;
        }
        if (count($succ_att_ids))
            $result_arr = $succ_att_ids;
        if (!count($result_arr))
            $this->die_error('no attendance inserted!');
        die(json_encode($result_arr));
    }

//    public function update_employee() {
//        $body_result = json_decode($this->_body, true);
////        file_put_contents(__DIR__ . '/updt_emp.txt', print_r($body_result, true));
//        $succ_emp_ids = array();
//        $err_emp_ids = array();
//        $err_msgs = null;
//        //fill in session since some methods depend on it like for logged id, current year,.. also we need it to 
//        //fill permission or it will make logout when call new StockAjax() class or other classes
////        $this->fill_trusto_session();
//        //
//        if (empty($body_result) || empty($body_result['employee']) || !is_array($body_result['employee']))
//            $this->die_error('no employee send to update them!');
//        $emp_data = array();
//        foreach ($body_result['employee'] as $row) {
//
//            if (!empty($row["employee_id"]) && !empty($row["employee_work_id"])) {
//                $emp_data = array(
//                    $row['employee_work_id'],
//                    $row['employee_id']
//                );
//                $att_query = $this->db->query_execute('update tbl_hrm_employee 
//                        set finger_print_nb = ? where Employee_ID = ?
//                        ', $emp_data);
//                if ($att_query) {
//                    $succ_emp_ids['succ_ids'][] = $row['employee_id'];
//                } else {
//                    $err_emp_ids['err_emp_ids'][] = $row['employee_id'];
//                    $err_msgs .= $att_query ? '' : $row['employee_id'] . "<br/>";
//                }
//            }
//        }
//        $result_arr = array();
//        if (count($err_emp_ids)) {
//            $result_arr['error_info'] = "Error Occured while updating employee: " . $err_msgs;
//            $result_arr['err_emp_ids'] = $err_emp_ids;
//        }
//        if (count($succ_emp_ids))
//            $result_arr = $succ_emp_ids;
//        if (!count($result_arr))
//            $this->die_error('no employee updated!');
//        die(json_encode($result_arr));
//    }


    public function add_fingerprint() {
        $body_result = json_decode($this->_body, true);
        //file_put_contents(__DIR__ . '/fingerprint.txt', print_r($body_result, true));
        $succ_ids = array();
        $err_ids = array();
        $err_msgs = null;
        $fingerprint_types_arr = array('hf7000', 'telpo');
        $is_fingerprint_data = false;
        foreach ($fingerprint_types_arr as $fingerprint_type) {
            if (!empty($body_result) && !empty($body_result[$fingerprint_type]) && is_array($body_result[$fingerprint_type])) {
                $is_fingerprint_data = true;
                break;
            }
        }
        if (!$is_fingerprint_data)
            $this->die_error('no fingerprint send to insert them!');
        $data = array();
        $logged_id = $this->get_login_user_id();
        foreach ($body_result[$fingerprint_type] as $row) {
            $check_request = $this->db->query_execute('select entry_id from tbl_hrm_fingerprint where app_id = ? 
                and app_user_id = ? and fingerprint_type = ?', array($row['record_id'], $logged_id, $fingerprint_type));
            if ($this->db->query_result_count($check_request) == 0) {
                if (!empty($row["employee_id"]) && !empty($row["fingerprint_data"])) {
                    $data = array(
                        $row['employee_id'],
                        json_encode($row["fingerprint_data"]),
                        $fingerprint_type,
                        $row['record_id'],
                        $logged_id
                    );
                    $query = $this->db->query_execute('INSERT INTO `tbl_hrm_fingerprint`(
                        `employee_id`, `fingerprint`, fingerprint_type, `app_id`,  `app_user_id`) values (?,?,?,?,?) ', $data);
                    if ($query)
                        $succ_ids['succ_ids'][] = $row['record_id'];
                    else {
                        $err_ids['err_ids'][] = $row['record_id'];
                        $err_msgs .= $query ? '' : $row['record_id'] . "<br/>";
                    }
                }
            } else
                $succ_ids['succ_ids'][] = $row['record_id'];
        }
        $result_arr = array();
        if (count($err_ids)) {
            $result_arr['error_info'] = "Error Occured while inserting fingerprint: " . $err_msgs;
            $result_arr['err_ids'] = $err_ids;
        }
        if (count($succ_ids))
            $result_arr = $succ_ids;
        if (!count($result_arr))
            $this->die_error('no fingerprint inserted!');
        die(json_encode($result_arr));
    }

    //
    public function get_fingerprint() {
        $arr = array();
        //here don't check for specific user, to get all already exist fingerprint from all users
        $query = "SELECT  `employee_id`, `fingerprint` as fingerprint_data, `app_id` as record_id, `app_user_id` 
                    FROM `tbl_hrm_fingerprint` where fingerprint_type = ? ";
        $stmt = $this->db->query_execute($query, array($_GET['device_type']));
        while ($row = $this->db->query_fetch($stmt)) {
            $row['fingerprint_data'] = json_decode($row['fingerprint_data']);
            $row['isNew'] = false;
            $arr[$row['record_id']] = $row;
        }
        die(json_encode(array('data' => array_values($arr))));
    }

    //
    public function backup_fingerprint() {
//        $body_result = json_decode($this->_body, true);
//        $fingerprint_types_arr = array('hf7000', 'telpo');
//        $is_fingerprint_data = false;
//        foreach ($fingerprint_types_arr as $fingerprint_type) {
//            if (!empty($body_result) && !empty($body_result[$fingerprint_type]) && is_array($body_result[$fingerprint_type])) {
//                $is_fingerprint_data = true;
//                break;
//            }
//        }
//        if (!$is_fingerprint_data)
//            $this->die_error('no fingerprint send to backup them!');
        $app_backup_dir = upload_path . 'app_backup/';
        if (!file_exists($app_backup_dir))
            mkdir($app_backup_dir, 0777);
        file_put_contents($app_backup_dir . '/fingerprint_attnd_data__' . $_GET['device_type'] . '__' . date('Y_m_d__H_i_s') . '.txt', $this->_body);
        die(json_encode(array('msg' => 'data backup success')));
    }

}
