<?php

class CommonFunctions {
//CommonFunctions::public_round_number
    protected $info = array();
    private $db;

    public function __construct() {
        $this->db = DBConnectorFactory::loadDriver();
    }        

    public static function public_round_number($number){
        $round_type = smc_session()['default_setting']['round_type'];
        $digits =  smc_session()['default_setting']['round_digits'];
        if ($digits == null)
            $digits = 2;

        if($round_type == 1 || $round_type == 0){
            return round($number,$digits);
        }else{
            $mult = pow(10, $digits);       
            return floor($number * $mult) / $mult;
        }
    }


    public static function formatNumber($number, $prec = null, $remove_trail_zero = null) {
        $number = self::public_round_number($number);
        if (is_null($prec))
            $prec = isset(smc_session()['default_setting']['number_format_precision']) ? smc_session()['default_setting']['number_format_precision'] : 2;
        if (is_null($remove_trail_zero))
            $remove_trail_zero = isset(smc_session()['default_setting']['number_format_remove_zeros']) ? smc_session()['default_setting']['number_format_remove_zeros'] : true;
        $number = number_format((float) $number, $prec);
        if ($remove_trail_zero)    //remove zero from end after decimal if exist
            $number = strpos($number, '.') !== false ? rtrim(rtrim($number, '0'), '.') : $number;
        return $number;
    }

    public static function getPages($Pages, $ID) {
        $section = array();
        $pageInfo = array();
        foreach ($Pages as $page):
            if ($page['Section_ID'] == $ID) {
                $pageInfo = $page;
            }
            if (!in_array($pageInfo, $section)) {
                array_push($section, $pageInfo);
            }
        endforeach;
        return array_filter($section);
    }

    //function that set the number and the width of colomns in the page
    //it have three atributes
    //$colnum a counter for the number of the columns
    //$colwidth for the number of the columns in the row
    //$colsize the size of the colomn (col-md-3 || col-md-4 ..)
    public static function returnColNum($colnum, $colwidth, $colsize) {
        global $colnum;
        global $widthsize;
        $widthsize = $colsize;
        $endcol = '';
        if ($colnum == $colwidth) {
            $colnum = 0;
            $endcol = '</div><div class="row">';
        }
        return $endcol;
    }

    //function that return module colors
    public function returnModuleColors() {
        $data = array();
        $query = $this->db->query('
                                        SELECT *
                                        FROM
                                            tbl_common_module_pages_color                                            
                                    ');
        while ($row = $this->db->assoc($query)) {
            $data[] = $row;
        }
        return $data;
    }

    public static function iteration($args) {
        for ($i = 0; $i < count($args); $i++) {
            foreach ($args as $key)
                return $key;
        }
        //        endfor;
    }

    //return module name from url
    public static function GetController($Url) {
        $arr = explode('/', $Url);
        return $arr[4];
    }

    public function moduleColor() {
        $ModuleName = '';
        $ModuleName = self::GetController($_SERVER['HTTP_REFERER']);
        $modulename = $this->db->query('
                                        SELECT 
                                            b.Color_Class,
                                            b.Color_Value
                                        FROM   
                                            tbl_common_modules a
                                        JOIN
                                            tbl_common_module_pages_color b
                                        ON
                                            a.Color_ID = b.Color_ID
                                        WHERE 
                                            Module_Title = "' . $ModuleName . '" 
                                    ');
        $row = $this->db->assoc($modulename);
        return $row;
    }

    public static function thisColor() {
        $color = new CommonFunctions();
        $thisColor = $color->moduleColor();
        return $thisColor;
    }

    public static function getLastID($table, $col) {
        $db = DBConnectorFactory::loadDriver();
        $query = $db->query("SELECT MAX(" . $col . ") AS ID FROM $table ");
        $row = $db->assoc($query);
        return intval($row['ID']);
    }

    public static function CommonView($tbl, $fieldID = null, $targetID = null, $condition = null, $condition2 = null) {
        $db = DBConnectorFactory::loadDriver();
        $condition1 = ' ';
        if (!empty($fieldID)) {
            $condition1 .= ' WHERE 1=1';
            for ($i = 0; $i < count($fieldID); $i++) {
                $condition1 .= ' AND ' . $fieldID[$i] . (!is_null($condition) ? $condition : ' = ') . '"' . $targetID[$i] . '"';
            }
        }
        $data = array();
        $query = $db->query('SELECT * FROM ' . $tbl . $condition1 . (!is_null($condition2) ? $condition2 : ''));
        while ($row = $db->assoc($query)) {
            $data[] = $row;
        }
        return $data;
    }

    public static function ViewByTableEntry($table, $entry_id, $entry_name, $ids) {
        $data = array();
        $db = DBConnectorFactory::loadDriver();
        $query = $db->query("select
                                        {$entry_id}  as id,
                                        {$entry_name} as text
                                   from
                                        {$table}
                                   where 
                                        {$entry_id} IN (" . $ids . ")
        ");
        while ($row = $db->assoc($query)) {
            $data[] = $row;
        }
        return $data;
    }

    public static function CommonDelete($tbl, $fieldID = null, $targetID = null, $condition = null, $condition2 = null) {
        $db = DBConnectorFactory::loadDriver();
        $condition1 = ' ';
        if (!empty($fieldID)) {
            $condition1 .= ' WHERE 1=1';
            for ($i = 0; $i < count($fieldID); $i++) {
                $condition1 .= ' AND ' . $fieldID[$i] . (!is_null($condition) ? $condition : ' = ') . '"' . $targetID[$i] . '"';
            }
        }
        $query = $db->query('Delete FROM ' . $tbl . $condition1 . (!is_null($condition2) ? $condition2 : ''));
        if ($query)
            return true;
        return false;
    }

    public static function UpdateRecordStatus($tbl, $idCol, $idValue, $statusCol, $statusValue) {
        $db = DBConnectorFactory::loadDriver();
        $db->prepare_Stmt('UPDATE ' . $tbl . ' SET ' . $statusCol . ' = ? WHERE ' . $idCol . ' = ?', [&$statusValue, &$idValue]);
        $error = $db->error();
        return $error;
    }

    public static function SpecificAttribute($tbl, $field, $fieldID, $attribute) {
        $db = DBConnectorFactory::loadDriver();
        $condition = ' WHERE 1=1 ';
        if (!is_array($field)) {
            $condition .= ' AND ' . $field . ' = "' . $fieldID . '"';
        } else {
            for ($i = 0; $i < count($field); $i++) {
                $condition .= ' AND ' . $field[$i] . ' = "' . $fieldID[$i] . '"';
            }
        }
        $query = $db->query('SELECT ' . $attribute . ' FROM ' . $tbl . $condition);
        $row = $db->assoc($query);
        return $row[$attribute] ? $row[$attribute] : 0;
    }

    //    public static function moveZipFiles($zip_file_name,$current_url){
    //        $remote_file = 'uploads/tmp/'.$zip_file_name;
    //        /* FTP Account */
    //        $ftp_host = 'trusto.info'; /* host */
    //        $ftp_user_name = 'smart_diner_sharing@trusto.info'; /* username */
    //        $ftp_user_pass = 'DeliveryAppSharingFiles'; /* password */
    //
    //
    //        /* New file name and path for this file */
    //        $local_file = $zip_file_name;
    //
    //        /* Connect using basic FTP */
    //        $connect_it = ftp_connect( $ftp_host );
    //
    //        /* Login to FTP */
    //        $login_result = ftp_login( $connect_it, $ftp_user_name, $ftp_user_pass );
    //        ftp_pasv($connect_it, true) or die("Cannot switch to passive mode");
    //
    //        /* Download $remote_file and save to $local_file */
    //        if ( !ftp_put( $connect_it, $remote_file, $local_file, FTP_BINARY ) ) {
    //            return false;
    //        }
    //
    //        /* Close the connection */
    //        ftp_close( $connect_it );
    //        return true;
    //    }

    public static function generateRandomStringNumber($len = 10, $abc = "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789") {
        $letters = str_split($abc);
        $str = "";
        for ($i = 0; $i <= $len; $i++)
            $str .= $letters[rand(0, count($letters) - 1)];
        return $str;
    }

    public static function set_trusted_computer_cookie($cookie_data) {
        $cookie_name = DB_NAME . '_computer';
        setcookie($cookie_name, json_encode($cookie_data), time() + (3600 * 24 * 365 * 10), '/');
        $_COOKIE[$cookie_name] = json_encode($cookie_data);
    }

    public static function encryptAutoLogin($user, $pass) {
        return self::encrypt2(str_rot13($pass) . "|||" . strrev($user) . "|||" . strtotime("now"));
    }

    public static function decryptAutoLogin($enc) {
        $user = $pass = "";
        $enc = self::decrypt2($enc);
        $enc_var = explode("|||", $enc);
        //link is valid for only one day
        if (strtotime("-1 day") < $enc_var[2]) {
            $user = strrev($enc_var[1]);
            $pass = str_rot13($enc_var[0]);
        }
        return array($user, $pass);
    }

    public static function encrypt($string) {
        $encrypt_method = 'AES-256-CBC';
        $encrypt_password = 'Clic9R0Un%T6chn0lo9y9810'; //must be the same in encrypt/decrypt
        //here $iv must be generated using [openssl_random_pseudo_bytes(openssl_cipher_iv_length($encrypt_method));]
        //and send it then decrypt using it.. and since it return binary we bsae64 encode it and fix it here
        $iv = base64_decode("bKK4yt/ETzedN+gmvLJ5hg==");    //openssl_random_pseudo_bytes(openssl_cipher_iv_length($encrypt_method));
        $encrypted_string = openssl_encrypt($string, $encrypt_method, $encrypt_password, 0, $iv);
        //we can't use it directly as it is binary we use base64_encode() or bin2hex() to make it textual representation
        $encrypted_string = base64_encode($encrypted_string);
        return $encrypted_string;
    }

//
    public static function decrypt($string) {
        $encrypt_method = 'AES-256-CBC';
        $encrypt_password = 'Clic9R0Un%T6chn0lo9y9810'; //must be the same in encrypt/decrypt
        $iv = base64_decode("bKK4yt/ETzedN+gmvLJ5hg==");
        $string = base64_decode($string);
        $decrypted_string = openssl_decrypt($string, $encrypt_method, $encrypt_password, 0, $iv);
        return $decrypted_string;
    }

    public static function encrypt2($string) {
        return str_rot13(strrev(base64_encode(str_rot13(strrev($string)))));
    }

    public static function decrypt2($enc) {
        return str_rot13(strrev(base64_decode(strrev(str_rot13($enc)))));
    }

    public static function generate_track_code($id, $type = '') {
        return $type . '4' . str_rot13(strrev((($id * 73) - 17)));
    }

    public static function restore_track_code($string) {
        $arr = null;
        $sep = strpos($string, '4');
        if ($sep !== false) {
            $id = substr($string, $sep + 1);
            $id = strrev(str_rot13($id));
            echo '=' . $id . '=';
            if (is_numeric($id) && !empty($id)) {
                $id = intval($id) + 17;
                $id = $id / 73;
                if (!is_float($id))
                    $arr = array($id, substr($string, 0, $sep));
            }
        }
        return $arr;
    }

    public static function get_role_tree($parent_ids, &$parents_arr, &$role_arr) {
        if (empty($parent_ids))
            return;
        $db = DBConnectorFactory::loadDriver();
        $new_parent_ids = array();
        $query = $db->query("select Parent_ID,Role_ID from tbl_common_roles where Parent_ID in ({$parent_ids}) ");
        while ($row = $db->assoc($query)) {
            $role_arr[$row['Role_ID']] = $row;
            if (!isset($parents_arr[$row['Parent_ID']]))
                $parents_arr[$row['Parent_ID']] = array();
            $new_parent_ids[$row['Role_ID']] = $row['Role_ID'];
            $parents_arr[$row['Parent_ID']][] = $row['Role_ID'];
        }
        if (!empty($new_parent_ids))
            self::get_role_tree(implode(',', $new_parent_ids), $parents_arr, $role_arr);
    }

    public static function get_user_roles($exclude_current_role = false, $current_role_id = null) {
        $parents_arr = array();
        $role_arr = array();
        $current_user_role = '';
        $role_id = !empty($current_role_id) ? $current_role_id : smc_session()['control_role_id'];
        CommonFunctions::get_role_tree($role_id, $parents_arr, $role_arr);
        foreach ($role_arr as $role) {
            $current_user_role .= $role['Role_ID'] . ',';
        }
        if (!$exclude_current_role)
            $current_user_role .= $role_id;
        else
            $current_user_role = substr($current_user_role, 0, -1);
        return $current_user_role;
    }

    public static function get_blocks($block_id, $is_excluded = false) {
        $parents_arr = array();
        $block_arr = array();
        $current_blocks = $block_id;
        $current_blocks = !$is_excluded ? $block_id : '';
        CommonFunctions::get_block_tree($block_id, $parents_arr, $block_arr);
        foreach ($block_arr as $block) {
            $current_blocks .= ($current_blocks == '' ? '' : ',') . $block['block_id'];
        }
        return $current_blocks;
    }

    public static function get_block_tree($parent_ids, &$parents_arr, &$block_arr) {
        $db = DBConnectorFactory::loadDriver();
        $new_parent_ids = array();
        $query = $db->query("select parent_id,block_id,block_name from tbl_subscription_block where parent_id in ({$parent_ids}) ");
        while ($row = $db->assoc($query)) {
            $block_arr[$row['block_id']] = $row;
            if (!isset($parents_arr[$row['parent_id']]))
                $parents_arr[$row['parent_id']] = array();
            $new_parent_ids[$row['block_id']] = $row['block_id'];
            $parents_arr[$row['parent_id']][] = $row['block_id'];
        }
        if (!empty($new_parent_ids))
            self::get_block_tree(implode(',', $new_parent_ids), $parents_arr, $block_arr);
    }

    public static function get_activity($activity_id, $is_excluded = false) {
        $parents_arr = array();
        $activity_arr = array();
        $current_activities = $activity_id;
        $current_activities = !$is_excluded ? $activity_id : '';
        CommonFunctions::get_activity_tree($activity_id, $parents_arr, $activity_arr);
        foreach ($activity_arr as $activity) {
            $current_activities .= ($current_activities == '' ? '' : ',') . $activity['activity_id'];
        }
        return $current_activities;
    }

    public static function get_activity_tree($parent_ids, &$parents_arr, &$activity_arr, $only_final = 0) {
        if (empty($parent_ids))
            return;
        $db = DBConnectorFactory::loadDriver();
        $new_parent_ids = array();
        $query = $db->query("select parent_id,activity_id,activity_code,activity_title,
            if(activity_title_alias='',activity_title,activity_title_alias) as activity_alias,
            is_final from tbl_activity_tree where parent_id in ({$parent_ids}) ");
        while ($row = $db->assoc($query)) {
            if ((!empty($only_final) && $row['is_final'] == 1) || empty($only_final))
                $activity_arr[$row['activity_id']] = $row;
            if (!isset($parents_arr[$row['parent_id']]))
                $parents_arr[$row['parent_id']] = array();
            $new_parent_ids[$row['activity_id']] = $row['activity_id'];
            $parents_arr[$row['parent_id']][] = $row['activity_id'];
        }
        if (!empty($new_parent_ids))
            self::get_activity_tree(implode(',', $new_parent_ids), $parents_arr, $activity_arr);
    }

    public static function get_emp_absence_leave_per($perm_name) {
        $db = DBConnectorFactory::loadDriver();
        $role_arr = array();
        $data = array();
        $query = $db->query('SELECT `Role_ID` FROM `tbl_common_role_permission` rp join tbl_common_permission p 
            on p.Permission_ID = rp.`Permission_ID` WHERE p.Permission_Name = "' . $perm_name . '" ');
        while ($row = $db->assoc($query)) {
            $role_arr[] = $row['Role_ID'];
        }
        $query_users = $db->query('select * from tbl_common_users 
            where Role_ID in (' . implode(',', $role_arr) . ')');
        while ($row_user = $db->assoc($query_users)) {
            $data[] = $row_user;
        }
        return $data;
    }

    public static function insertEmpTask($arr) {
        $db = DBConnectorFactory::loadDriver();
        if (empty($arr['emp_id']))
            $arr['emp_id'] = smc_session()['user_details']['Employee_ID'];
        if (empty($arr['task_type']))
            $arr['task_type'] = 'task';
        if (empty($arr['date_time']))
            $arr['date_time'] = date('Y-m-d h:i:s');
        if (empty($arr['logged_id']))
            $arr['logged_id'] = smc_session()['user_logged_id'];
        //
        $db->prepare_Stmt('INSERT INTO `tbl_emp_tasks`(`employee_id`,`task_desc`,`due_date`,`main_type`,`main_id`,`date_time`,`logged_id`,`task_type`) VALUES (?,?,?,?,?,?,?,?) '
                , array($arr['emp_id'], $arr['task_desc'], $arr['due_date'], $arr['main_type'], $arr['main_id'], $arr['date_time'], $arr['logged_id'], $arr['task_type']));
    }

    public static function update_task_status($main_id, $main_type) {
        $db = DBConnectorFactory::loadDriver();
        $db->prepare_Stmt('update tbl_emp_tasks set task_status = 1 where main_id = ? and main_type = ? ', [&$main_id, &$main_type]);
    }

    public static function getUserPrivacyTypes($selected_value = '', $return_arr = false) {
        $privacy_types = array(
            'public' => CommonLanguage::getMessage('privacy_public')
            , 'dep' => CommonLanguage::getMessage('privacy_dep')
            , 'grp' => CommonLanguage::getMessage('privacy_grp')
            , 'admin_dep' => CommonLanguage::getMessage('privacy_admin_dep')
            , 'usr' => CommonLanguage::getMessage('privacy_usr')
        );
        if ($return_arr)
            return $privacy_types;
        $options = '<option> --- </option>';
        foreach ($privacy_types as $value => $view)
            $options .= "<option value='{$value}' " . ($selected_value == $value ? " selected='selected' " : "") . ">{$view}</option>";
        return $options;
    }

    //build thumb & return it's patth. if created before just return it
    public static function image_thumb($image_path, $width = null, $height = null, $options = array()) {
        //can check options: https://www.abeautifulsite.net/the-simple-image-class-for-php
        $tmp_image_path = filter_var($image_path, FILTER_VALIDATE_URL) !== false ? $image_path : realpath($image_path);
        $output_image = "thumb--{$width}-{$height}--" . sha1($tmp_image_path) . '.' . pathinfo($image_path, PATHINFO_EXTENSION);  //we make sha1 to don't show real full path 
        $is_return_obj = isset($options['return_obj']) && $options['return_obj'] === true;
        $upload_path = dirBase . "uploads/";
        $upload_link = SITE_LINK . "uploads/";
        if (!$is_return_obj && file_exists($upload_path . "cache/{$output_image}")) {
            //but make check if it is modified after the thumb creation date then we must create new thumb image
            //also we check that file size not zero, since some times may create zero size in case of error
            if (@filesize($upload_path . "cache/{$output_image}") > 0 && (@filemtime($image_path) === false /* just in case if path is url */ || filemtime($upload_path . "cache/{$output_image}") >= filemtime($image_path)))
                return $upload_link . "cache/{$output_image}";
        }
        if (!file_exists($upload_path . "cache"))    //if cache folder not exist create it
            mkdir($upload_path . "cache");
        //to don't clean on each request since later in large data i think it will take time to build scandir & we do it from back end only
        $cookie_index = DB_NAME . '__cookie_cache_dir_clean';
        if (empty($_COOKIE[$cookie_index]) || $_COOKIE[$cookie_index] !== true) {
            $files = glob($upload_path . "cache/*"); // get all file names
            foreach ($files as $full_file) {
                if (is_file($full_file) && is_writable($full_file)) {
                    $stat_data = stat($full_file);
                    //since maybe new files like from seconds or minutes created & used for now,..
                    //we need it to at least keep today file ex: 86400 means delete all filed before 24 hour
                    $old_time = time() - 864000;    //clear old date files 864000 = 10days
                    if (($stat_data['mtime'] < $old_time))
                        unlink($full_file);
                }
            }
            if (!headers_sent())    //to don't give error header already send
                setcookie($cookie_index, true, time() + 86400/* expire in one day */, '/');
            $_COOKIE[$cookie_index] = true;
        }
        try {
            include_once __DIR__ . '/simple_image.php';
            $image_obj = new SimpleImage($image_path);
            $image_obj->resize($width, $height);
            if (!empty($options['watermark']))
                $image_obj->overlay($options['watermark'], (empty($options['watermark_position']) ? "" : $options['watermark_position']), (empty($options['watermark_opacity']) ? 1 : $options['watermark_opacity']));
            //below we can put quality to 85% but if image already with loq quality like 50% then it will make quality 85% for that already 50% bad quality
            $image_obj->toFile($upload_path . "cache/{$output_image}");
        } catch (Exception $e) {
            //if make error like we make thumb of url where image not found or .. 
            return null;
        }
        if ($is_return_obj)
            return $image_obj;
        return $upload_link . "cache/{$output_image}";
    }

    public static function calc_date_diff($date_from, $date_to, $return_obj = false) {
        //we make substr to get date only without time or we must check $since_start->h
        //depend on hours also to add day or not and if invert subtract day
        $start_date = new DateTime(substr($date_from, 0, 10));
        $since_start = $start_date->diff(new DateTime(substr($date_to, 0, 10)));
        if ($return_obj)
            return $since_start;
        return ($since_start->days * ($since_start->invert == 1 ? -1 : 1));
    }

    public static function add_user_log($data) {
        //type,main_id,action('delete','add','edit') are required
        $db = DBConnectorFactory::loadDriver();
        $date_time = empty($data['date_time']) ? date('Y-m-d H:i:s') : $data['date_time'];
        $logged_id = empty($data['user_id']) ? smc_session()['user_logged_id'] : $data['user_id'];
        $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']);
        //
        $db->prepare_Stmt('insert into `tbl_main_log`(`type`, `main_id`, `action`, `date_time`, `user_id`, `ip`)
            values(?,?,?,?,?,?) ', [&$data['type'], &$data['main_id'], &$data['action'], &$date_time, &$logged_id, &$ip]);
    }

    public static function add_version($data) {
        //main_type,main_id,version_arr,version_nb are required
        $db = DBConnectorFactory::loadDriver();
        $date_time = empty($data['date_time']) ? date('Y-m-d H:i:s') : $data['date_time'];
        $logged_id = empty($data['user_id']) ? smc_session()['user_logged_id'] : $data['user_id'];
        $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']);
        //
        $db->prepare_Stmt('insert into `tbl_versions`
            ( `version_nb`, `main_type`, `main_id`, `date_time`, `user_id`, `version_array`, `ip`)
            values(?,?,?,?,?,?,?) ', [&$data['version_nb'], &$data['main_type'],
            &$data['main_id'], &$date_time, &$logged_id, &$data['version_array'], &$ip]);
    }

    function delete_dir($dir) {
        $dir = realpath($dir);
        if (is_dir($dir)) {
            $dir_elements = scandir($dir);
            foreach ($dir_elements as $element) {
                if ($element != '.' && $element != '..') {
                    $full_element = $dir . DIRECTORY_SEPARATOR . $element;
                    if (is_dir($full_element))
                        delete_dir($full_element);
                    else
                        unlink($full_element);
                }
            }
            rmdir($dir);
        }
    }

    public static function get_scale_types($scale_library = false, $key = null) {
        if ($scale_library)
            $arr = ['1' => 'scale_kertz', '2' => 'scale_motex','3'=>'scale_jhma'];
        else
            $arr = ['1' => 'Kertz', '2' => 'Motex','3'=>'Jhma'];
        if (!empty($key))
            return $arr[$key];
        return $arr;
    }

    //
    public static function check_ping_ip($ip, $sec_timeout = 2) {
        $output = array();
        $return_var = null;
        exec('ping -n 1 -i 255 -w ' . ($sec_timeout * 1000) . ' ' . escapeshellarg($ip), $output, $return_var);
        $output = array_values(array_filter($output)); //remove empty output lines and re-index array
        if (!empty($output[1]) && preg_match("/time(?:=|<)(?<time>[\.0-9]+)(?:|\s)ms/", $output[1], $matches))
            return true;
        //if failed ping try another method
        $ch = curl_init($ip);
        curl_setopt($ch, CURLOPT_TIMEOUT, $sec_timeout);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $sec_timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_exec($ch);
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($httpcode >= 200 && $httpcode < 300)
            return true;
        //
        return false;
    }

    public static function get_hotel_connection() {
        require_once dirname(__DIR__) . '/Common/db_standalone_class.php';
        static $con_db = null;
        if (!empty(smc_session()['default_setting']['hotel_database']) && is_null($con_db)) {
            $hotel_db = smc_session()['default_setting']['hotel_database'];
            $hotel_data = json_decode(smc_session()['default_setting']['hotel_database'], true);
            if (!empty($hotel_data['db']))
                $con_db = new db_standalone(null, (isset($hotel_data['host']) ? $hotel_data['host'] : DB_HOST), (isset($hotel_data['user']) ? $hotel_data['user'] : DB_USER), (isset($hotel_data['pass']) ? $hotel_data['pass'] : DB_PASS), $hotel_data['db']);
        }
        return $con_db;
    }

    public static function convertxlsxtoCSV($infile, $outfile) {
        $fileType = PHPExcel_IOFactory::identify($infile);
        $objReader = PHPExcel_IOFactory::createReader($fileType);

        $objReader->setReadDataOnly(true);
        $objPHPExcel = $objReader->load($infile);

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
        $objWriter->save($outfile);
    }

    public static function check_lock_data($options) {
        $official = Session::getCurrentYearRange();
        $actual = Session::getActCurrentYearRange();
        $start_year = $options['is_actual'] ? $actual['start_date_act'] : $official['start_date'];
        $end_year = $options['is_actual'] ? $actual['end_date_act'] : $official['end_date'];
        $is_closed = $options['is_actual'] ? $actual['year_closed_act'] : $official['year_closed'];
        $last_lock_date = smc_session()['last_lock_date'];
        $last_close_vat = smc_session()['last_close_vat'];
        $stop_type = '';

        if ($is_closed)
            $stop_type = 'close_year';
        elseif (!empty($options['start_date']) && ($options['start_date'] < $start_year || $options['start_date'] > $end_year))
            $stop_type = 'out_year';
        elseif (!empty($options['end_date']) && ($options['end_date'] < $start_year || $options['end_date'] > $end_year))
            $stop_type = 'out_year';
        if (empty($stop_type) && !empty($last_lock_date)) {
            if (!empty($options['start_date']) && $options['start_date'] <= $last_lock_date){
                $stop_type = 'lock';
            }
            elseif (!empty($options['end_date']) && $options['end_date'] <= $last_lock_date)
                $stop_type = 'lock';
        }
        if (empty($stop_type) && $options['type'] != 'assign' && !empty($last_close_vat)) {
            if (!empty($options['start_date']) && $options['start_date'] <= $last_close_vat)
                $stop_type = 'close_vat';
            elseif (!empty($options['end_date']) && $options['end_date'] <= $last_close_vat)
                $stop_type = 'close_vat';
        }
   
        //
        if (empty($stop_type))
            return '';
        switch ($stop_type) {
            case 'close_year':
                return CommonLanguage::getMessage('edit_year_alert');
            case 'out_year':
                return CommonLanguage::getMessage('current_year_modify');
            case 'lock':
                return CommonLanguage::getMessage('edit_locked_data_alert');
            case 'close_vat':
                return CommonLanguage::getMessage('edit_close_vat_alert');
        }
        return CommonLanguage::getMessage('unknown_lock_data_alert');
    }

}
