<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Logger{

    function create_log($module, $action, $query = '', $username_try = '') {
        $this->ci = &get_instance();
        $this->ci->load->model('db_model');

        if($username_try != '') {
            $username = $username_try;
        } else {
            $username = $this->ci->session->userdata('username');
        }
        date_default_timezone_set('Asia/Jakarta');
        $id_log = $this->getNextId('log_aktivitas','id',$this->ci->session->userdata('id_company'),3);
        $data = array(
            'id' => $id_log
            ,'username' => $username
            , 'waktu' => date('Y-m-d h:i:s')
            , 'modul' => $module
            , 'action' => $action
            , 'query' => $query
            , 'id_company' => $this->ci->session->userdata('id_company')
        );

        if ($this->ci->db_model->add('log_aktivitas', $data)) {
            return true;
        }else{
            return false;
        }
    }

    function getNextId($tableName = null, $fieldName = null, $id_company = null, $lengthNumber=null){
        $this->ci = &get_instance();
        $current_month = date('Ym');
        $len_substring = -6-$lengthNumber;
        $gedId = $this->ci->db->query("SELECT MAX($fieldName) as id
                                        FROM $tableName
                                        WHERE id_company = '$id_company'
                                        AND SUBSTRING($fieldName,$len_substring,6) = '$current_month'");

        if($gedId->num_rows() > 0){
            $current_id = substr($gedId->row()->id,"-".$lengthNumber);
            $nextId =  $id_company.$current_month.sprintf("%0".$lengthNumber."d", ($current_id+1));
        }else{
            $nextId = $id_company.$current_month.sprintf("%0".$lengthNumber."d", 1);
        }

        return $nextId;
    }

    function log_notifikasi($module, $query = '', $id, $status) {
        $CI = & get_instance();
        $CI->load->model('db_model');

        $data = array(
            'waktu' => date('Y-m-d h:i:s')
            , 'modul' => $module
            , 'query' => $query
            , 'id_karyawan' => $id
            , 'status' => $status
        );

        if ($CI->db_model->add('log_notifikasi', $data)) {
            return true;
        }else{
            return false;
        }
    }

}
