<?php

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

class App
{

    private $CI;

    public function __construct()
    {
        /* Assign by reference with "&" so we don't create a copy */
        $this->CI = &get_instance();
        $this->CI->load->library('session');
    }

    /* Load Variable System */

    public function get_var_sys()
    {
        $query = $this->CI->db->query('SELECT * FROM sys_variable WHERE is_active = 1 ORDER BY sort ASC');
        if ($query) {
            $nrows = $query->num_rows();
            if ($nrows > 0) {
                $arr = array();
                foreach ($query->result() as $item) {
                    $arr[$item->variable_name] = $item->variable_description;
                }
                return (object) $arr;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /* Get Last updated */

    public function last_updated_table($table = '', $conditon = '')
    {
        $sql = "SELECT IFNULL(updated_at, created_at) AS updated "
            . "FROM " . $table . " "
            . "WHERE 1=1 ";
        $sql .= (!empty($conditon) ? $conditon : '');
        $sql .= " ORDER BY updated DESC";
        $data = $this->CI->db->query($sql)->row();
        return $data->updated;
    }

    /* write_log => $remark is String, $last_query is SQL Syntax */

    public function write_log($remark = '', $last_query = '')
    {
        $device = ($this->CI->agent->is_mobile() ? ($this->CI->agent->is_mobile('iphone') ? 'Iphone' : 'Android') : 'Computer');
        $data = array(
            'company_id' => $this->CI->session->userdata('user_profile')->company_id,
            'datetime' => date('Y-m-d H:i:s'),
            'user_name' => $this->CI->session->userdata('user_profile')->user_name,
            'ip' => $this->CI->input->ip_address(),
            'os' => $this->CI->agent->platform(),
            'device' => $device,
            'browser' => $this->CI->agent->agent_string(),
            'page' => $this->CI->uri->uri_string(),
            'query' => $last_query,
            'remark' => $remark
        );
        $this->CI->db->select('id');
        $this->CI->db->where($data);
        $nrows = $this->CI->db->count_all_results('sys_log');
        if ($nrows == 0) {
            if ($this->CI->db->insert('sys_log', $data)) {
                return TRUE;
            } else {
                return FALSE;
            }
        } else {
            return FALSE;
        }
    }

    /* Generate New Password */

    public function paswd_encrypt($paswd, $hash = PASSWORD_DEFAULT)
    {
        /* $hash Only PASSWORD_DEFAULT, PASSWORD_BCRYPT, PASSWORD_ARGON2I */
        /* ext. $this->app->paswd_encrypt('123') OR $this->app->paswd_encrypt('123',PASSWORD_BCRYPT)  return HASH */
        return password_hash($paswd, $hash);
    }

    /* Verify Password */

    public function paswd_decrypt($paswd, $hash)
    {
        /* ext. $this->app->paswd_decrypt('123', '$2y$10$wF/50jQC9x782KMnljWLb.QEN8lSvGup0XhGEWa2VJNw8ZufqPz.K') RETURN boolean */
        return password_verify($paswd, $hash);
    }

    /* Get Permission User */

    public function get_permission($module = '', $role_id = '', $group_id = '')
    {
        $modules = explode('/', $module);

        $module = $modules[0] . '/' . $modules[1];
        $group_id = (empty($group_id) ? $this->CI->session->userdata('user_profile')->group_id : $group_id);
        $sql = "SELECT * "
            . "FROM sys_permission "
            . "WHERE module = '" . $module . "' AND group_id = '" . $group_id . "'";
        $data = $this->CI->db->query($sql)->row();
        return $data;
    }

    /* Check Permission Can Do This Data */

    public function is_can($permission, $type)
    {
        /* ext. Check Can View Permission $this->app->is_can($permission, "view") */
        /* Defind of Type When Insert Or Update permission in DB sys_permission Must Change $type_id */
        if ($permission->{$type} === '1') {
            return true;
        }
        return false;
    }

    public function increment_date($day = '90')
    {
        $date = strtotime("+" . $day . " day", strtotime(date("Y-m-d H:i:s")));
        return date('Y-m-d H:i:s', $date);
    }

    /* Check Password User Expired */

    public function check_expired_date($datetime)
    {
        $current_datetime = strtotime(date('Y-m-d H:i:s'));
        $check_datetime = strtotime($datetime);
        // Compare the timestamp date
        if ($current_datetime > $check_datetime) {
            return true;
        } else {
            return false;
        }
    }

    /* Datetime to Thai */

    public function datetime_to_th($strDate, $time = true)
    {
        if (!empty($strDate)) {
            $strYear = date("Y", strtotime($strDate)) + 543;
            $strMonth = date("n", strtotime($strDate));
            $strDay = date("j", strtotime($strDate));
            $strHour = date("H", strtotime($strDate));
            $strMinute = date("i", strtotime($strDate));
            $strSeconds = date("s", strtotime($strDate));
            $strMonthCut = array("", "ม.ค.", "ก.พ.", "มี.ค.", "เม.ย.", "พ.ค.", "มิ.ย.", "ก.ค.", "ส.ค.", "ก.ย.", "ต.ค.", "พ.ย.", "ธ.ค.");
            $strMonthThai = $strMonthCut[$strMonth];
            return "$strDay $strMonthThai $strYear " . ($time == true ? ", $strHour:$strMinute" : "");
        } else {
            return "";
        }
    }

    /* Datetime to English */

    public function datetime_to_en($strDate, $time = true)
    {
        if (!empty($strDate)) {
            $strYear = date("Y", strtotime($strDate));
            $strMonth = date("n", strtotime($strDate));
            $strDay = date("j", strtotime($strDate));
            $strHour = date("H", strtotime($strDate));
            $strMinute = date("i", strtotime($strDate));
            $strSeconds = date("s", strtotime($strDate));
            $strMonthCut = array("", "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC");
            $strMonthThai = $strMonthCut[$strMonth];
            return "$strDay $strMonthThai $strYear " . ($time == true ? ", $strHour:$strMinute" : "");
        } else {
            return "";
        }
    }

    /* Date in national format */

    public function date_format($strDate)
    {
        if (!empty($strDate)) {
            $strYear = date("Y", strtotime($strDate));
            $strMonth = date("n", strtotime($strDate));
            $strDay = date("j", strtotime($strDate));
            $strMonthCut = array("", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12");
            $strMonth = $strMonthCut[$strMonth];
            return str_pad($strDay, 2, '0', STR_PAD_LEFT) . "/$strMonth/$strYear ";
        } else {
            return "";
        }
    }

    /* Encrypt & Decrypt URI Segment ID */

    public function encrypt_segment($string, $token = NULL)
    {
        /* you may change these values to your own */
        $secret_key = $this->CI->session->userdata("user_profile")->id;
        $secret_iv = (!empty($token) ? $token : $this->CI->session->userdata("token"));

        $output = false;
        $encrypt_method = "AES-256-CBC";
        $key = hash('sha256', $secret_key);
        $iv = substr(hash('sha256', $secret_iv), 0, 16);
        $output = base64_encode(openssl_encrypt($string, $encrypt_method, $key, 0, $iv));
        return $output;
    }

    public function decrypt_segment($string, $token = NULL)
    {
        /* you may change these values to your own */
        $secret_key = $this->CI->session->userdata("user_profile")->id;
        $secret_iv = (!empty($token) ? $token : $this->CI->session->userdata("token"));

        $output = false;
        $encrypt_method = "AES-256-CBC";
        $key = hash('sha256', $secret_key);
        $iv = substr(hash('sha256', $secret_iv), 0, 16);
        $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
        return $output;
    }

    /* Remove all In Directory */

    public function rmdir_recursive($dir)
    {
        if (is_dir($dir)) {
            $files = scandir($dir);
            foreach ($files as $file) {
                if ($file == '.' or $file == '..') {
                    continue;
                }
                $file = "$dir/$file";
                if (is_dir($file)) {
                    $this->rmdir_recursive($file);
                    rmdir($file);
                } else {
                    unlink($file);
                }
            }
            return rmdir($dir);
        } else {
            return false;
        }
    }

    /* Check Limit time */
    public function check_limit_time($datetime, $hours = 0)
    {
        $current_datetime = strtotime(date('Y-m-d H:i:s'));
        $check_datetime = strtotime(strftime($datetime, time() + $hours * 60 * 60));
        //echo $current_datetime .'>'.$check_datetime.'<br>';
        // Compare the timestamp date
        if ($current_datetime > $check_datetime) {
            return 1;
        } else {
            return 0;
        }
    }

    /* การจับคู่ใบ invoice ที่สแกนจากเครื่อง เข้าระบบ */
    /*
    public function mapped_invoice_scanner()
    {
        // ต้องตั้งชื่อไฟล์ตามเลขที่ใบ invoice ไว้ที่ S:\System-Master\store\scan\
        // ใส่ section name
        $section = strtolower($this->CI->session->userdata('user_profile')->section_name);
        // var_dump($this->CI->session->userdata());
        if ($section === 'store' || $this->CI->session->userdata('user_profile')->id === 1) {

            $dir = '\\\\eft-fl1-server\Share\System-Master\store\scan\\'; // PATH TO SERVER DRIVE
            if (is_dir($dir)) {
                if ($dh = opendir($dir)) {
                    while (($file = readdir($dh)) !== false) {
                        if ($file != "." && $file != "..") {
                            $doc = $dir . $file;
                            echo file_exists($doc) ? '' : 'File: was not found.';
                            $ext = pathinfo($doc, PATHINFO_EXTENSION);
                            $inv_no = pathinfo($doc, PATHINFO_FILENAME);
                            $sql = "SELECT sto_receipt_note.id, LOWER({ fn CONCAT(sto_receipt_note.receipt_type, CONVERT(VARCHAR, sto_receipt_note.receipt_no)) }) AS receipt_no,
                            LOWER(pur_po.no) AS po_no, sto_receipt_note.inv_no
                            FROM sto_receipt_note INNER JOIN pur_po ON sto_receipt_note.po_id = pur_po.id
                                    WHERE LOWER(sto_receipt_note.inv_no) = '" . strtolower($inv_no) . "' AND sto_receipt_note.record_status ='N' ";
                            $nrow = $this->CI->db->query($sql)->num_rows();
                            if ($nrow > 0) {
                                $row = $this->CI->db->query($sql)->row();
                                $file_name = strtolower($row->receipt_no . "." . $ext);
                                rename($doc, $dir . "/" . $file_name);
                                if (copy($dir . "/" . $file_name, "uploads/receipt/" . $row->po_no . "/" . $file_name)) {
                                    unlink($dir . "/" . $file_name);
                                    // อัพเดทชื่อไฟล์
                                    $this->CI->db->query("UPDATE sto_receipt_note SET inv_filename ='" . $file_name . "' WHERE id = '" . $row->id . "'");
                                }
                            }
                        }
                    }
                    closedir($dh);
                }
            } else {
                echo 'Directory not found.';
            }
        } else {
            // echo 'Access denied';
        }
    }
    */

    /* ดึงไฟล์รูป */
    public function user_pic($id)
    {
        $sql = "SELECT user_pic FROM sys_user WHERE record_status='N' AND id = '" . $id . "'";
        $data = $this->CI->db->query($sql)->row();
        return (!empty($data->user_pic) ? $data->user_pic : 'https://pbs.twimg.com/profile_images/1202831035219660800/kpgTtyk9.png');
    }



    /************************************/
    //Form Element DB
    /************************************/

    /* ฟังก์ชัน แปลงตัวเลขอาราบิก เป็น ตัวเลขไทย อย่างง่าย */
    public function thaiNumDigit($num)
    {
        return str_replace(
            array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'),
            array("o", "๑", "๒", "๓", "๔", "๕", "๖", "๗", "๘", "๙"),
            $num
        );
    }
    /* GET ค่าที่อยู่ระหว่างคำ */
    public function find_between(string $string, string $start, string $end, bool $greedy = false)
    {
        $start = preg_quote($start, '/');
        $end   = preg_quote($end, '/');

        $format = '/(%s)(.*';
        if (!$greedy) $format .= '?';
        $format .= ')(%s)/';

        $pattern = sprintf($format, $start, $end);
        preg_match($pattern, $string, $matches);

        return $matches[2];
    }

    // ตัวเลขทศนิยม แบบปัดเศษทิ้งเลย
    public function strDigit($str, $digit = 2)
    // $digit จำนวน ทศนิยม ค่าพื่้นฐาน 2 หลัก (ถ้าไม่มีใส่ เป็น 0)
    {
        if (strpos($str, ".") === true) {
            $ex = explode('.', $str);
            $s = substr($ex[1], 0, $digit);
            if ($s == '') {
                $s = str_pad('0', $digit, '0', STR_PAD_RIGHT);
            }
            if ($ex[0] == '') {
                $ex[0] = '0';
            }
            $dec = number_format($ex[0]) . "." . str_pad($s, $digit, '0', STR_PAD_RIGHT);
        } else {
            $dec = number_format($str, $digit);
        }
        return $dec;
    }

    /* SelectOption */
    /*
    public function selectOption($table = '', $element = array(), $class = '', $id = '', $isArray = false)
    {
        $sql = "SELECT " . implode(",", $element)
            . " FROM " . $table
            . " WHERE Active ='True' "
            . " ORDER BY SeqNO ASC ";
        $results = $this->CI->db->query($sql)->result();
        $ret = '<select class="form-control form-control-line ' . $class . '" id ="' . $id . '" name ="' . $element[0] . ($isArray === true ? '[]' : '') . '" style="width:100%">';
        $ret .= '<option value="">Please select</option>';
        foreach ($results as $item) {
            $ret .= '<option value="' . $item->{$element[0]} . '">' .  $item->{$element[0]} . '=> ' . $item->{$element[1]} . '</option>';
        }
        $ret .= '</select>';
        return $ret;
    }
    */
}
