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

class MyHelper
{
    private $CI;
    const REGISTER_PATERN_USERNAME = "/^[a-zA-Z0-9]{6,32}$/";
    const REGISTER_PATERN_PASSWORD = "/^[a-zA-Z0-9_\.\@]{8,32}$/";
    const REGISTER_PATERN_MOBILE = "/^841\d{9}$|^84[2-9]{1}\d{8}$|^01\d{9}$|^0[2-9]{1}\d{8}$/";

    //
    public function __construct()
    {
        $this->CI = &get_instance();
    }

    /**
     * 28/12/2015 by doanpv
     * Hàm định dạng hiển thị lại số điện thoại
     * @param $phone
     * @param string $separate
     * @param int $readType
     * @return string
     */
    public static function format_phone($phone, $separate = '.', $readType = 433)
    {
        $phone = preg_replace("/[^0-9]/", "", $phone);
        if (strlen($phone) == 7) {
            return preg_replace("/([0-9]{3})([0-9]{4})/", "$1-$2", $phone);
        } elseif (strlen($phone) == 9) {
            if ($readType == 334) {
                return '0' . preg_replace("/([0-9]{2})([0-9]{3})([0-9]{4})/", "$1$separate$2$separate$3", $phone);
            } elseif ($readType == 343) {
                return '0' . preg_replace("/([0-9]{2})([0-9]{4})([0-9]{3})/", "$1$separate$2$separate$3", $phone);
            } elseif ($readType == 424) {
                return '0' . preg_replace("/([0-9]{3})([0-9]{2})([0-9]{4})/", "$1$separate$2$separate$3", $phone);
            } elseif ($readType == 433) {
                return '0' . preg_replace("/([0-9]{3})([0-9]{3})([0-9]{3})/", "$1$separate$2$separate$3", $phone);
            }
        } elseif (strlen($phone) == 10) {
            return '0' . preg_replace("/([0-9]{4})([0-9]{3})([0-9]{3})/", "$1$separate$2$separate$3", $phone);
        } else {
            return '0' . $phone;
        }
    }

    public static function format_chargetime($chargetime, $separate = '/')
    {
        $chargetime = preg_replace("/[^0-9]/", "", $chargetime);
        if (strlen($chargetime) == 14) {
            return preg_replace("/([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/", "$3$separate$2$separate$1 $4:$5:$6", $chargetime);
        } else {
            return $chargetime;
        }
    }

    public static function reFormatDate($datetime, $format = 'd/m/Y H:i:s')
    {
        return (isset($datetime) && ($datetime != '0000-00-00 00:00:00')) ? date($format, strtotime($datetime)) : '';
    }

    /**
     * 30/12/2015 by doanpv
     * Hàm xem cấu trúc dữ liệu, ko die
     * @param $data
     */
    public static function echoPre($data)
    {
        echo '<pre>';
        print_r($data);
        echo '</pre>';
    }

    /**
     * 30/12/2015 by doanpv
     * Hàm xem cấu trúc dữ liệu, có die()
     * @param $data
     */
    public static function echoPreDie($data)
    {
        echo '<pre>';
        print_r($data);
        echo '</pre>';
        die();
    }

    public static function truncate($text, $length = 30, $truncateString = '...', $truncateLastspace = false, $escapeHtml = false)
    {
        /**
         * Ham tra cat ky tu tieng viet
         * @param $text
         * @param int $length
         * @param string $truncateString
         * @param bool $truncateLastspace
         * @return string
         * @throws dmException
         */
        /*if (sfConfig::get('sf_escaping_method') == 'ESC_SPECIALCHARS') {
            $text = htmlspecialchars_decode($text, ENT_QUOTES);
        }*/

        if (is_array($text)) {
            throw new dmException('Can not truncate an array: ' . implode(', ', $text));
        }

        $text = (string)$text;

        if (extension_loaded('mbstring')) {
            $strlen = 'mb_strlen';
            $substr = 'mb_substr';
            //hatt12 them dong nay de dem ky tu tieng viet
            $countStr = $strlen($text, 'utf-8');
            if ($countStr > $length) {
                $text = $substr($text, 0, $length, 'utf-8');

                if ($truncateLastspace) {
                    $text = preg_replace('/\s+?(\S+)?$/', '', $text);
                }

                $text = $text . $truncateString;
            }
        } else {
            $strlen = 'strlen';
            $substr = 'substr';
            $countStr = $strlen($text);
            if ($countStr > $length) {
                $text = $substr($text, 0, $length);

                if ($truncateLastspace) {
                    $text = preg_replace('/\s+?(\S+)?$/', '', $text);
                }

                $text = $text . $truncateString;
            }
        }

        if ($escapeHtml) {
            return $text;
        }
        return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
    }

    public static function genSlug($str, $strtolower = 0)
    {
        //$marTViet= array('À','Á','Â','Ã','Ä','Å','Æ','Ç','È','É','Ê','Ë','Ì','Í','Î','Ï','Ð','Ñ','Ò','Ó','Ô','Õ','Ö','Ø','Ù','Ú','Û','Ü','Ý','ß','à','á','â','ã','ä','å','æ','ç','è','é','ê','ë','ì','í','î','ï','ñ','ò','ó','ô','õ','ö','ø','ù','ú','û','ü','ý','ÿ','A','a','A','a','A','a','C','c','C','c','C','c','C','c','D','d','Ð','d','E','e','E','e','E','e','E','e','E','e','G','g','G','g','G','g','G','g','H','h','H','h','I','i','I','i','I','i','I','i','I','i','?','?','J','j','K','k','L','l','L','l','L','l','?','?','L','l','N','n','N','n','N','n','?','O','o','O','o','O','o','Œ','œ','R','r','R','r','R','r','S','s','S','s','S','s','Š','š','T','t','T','t','T','t','U','u','U','u','U','u','U','u','U','u','U','u','W','w','Y','y','Ÿ','Z','z','Z','z','Ž','ž','?','ƒ','O','o','U','u','A','a','I','i','O','o','U','u','U','u','U','u','U','u','U','u','?','?','?','?','?','?');
        //$marKoDau = array('A','A','A','A','A','A','AE','C','E','E','E','E','I','I','I','I','D','N','O','O','O','O','O','O','U','U','U','U','Y','s','a','a','a','a','a','a','ae','c','e','e','e','e','i','i','i','i','n','o','o','o','o','o','o','u','u','u','u','y','y','A','a','A','a','A','a','C','c','C','c','C','c','C','c','D','d','D','d','E','e','E','e','E','e','E','e','E','e','G','g','G','g','G','g','G','g','H','h','H','h','I','i','I','i','I','i','I','i','I','i','IJ','ij','J','j','K','k','L','l','L','l','L','l','L','l','l','l','N','n','N','n','N','n','n','O','o','O','o','O','o','OE','oe','R','r','R','r','R','r','S','s','S','s','S','s','S','s','T','t','T','t','T','t','U','u','U','u','U','u','U','u','U','u','U','u','W','w','Y','y','Y','Z','z','Z','z','Z','z','s','f','O','o','U','u','A','a','I','i','O','o','U','u','U','u','U','u','U','u','U','u','A','a','AE','ae','O','o');
        $marTViet = array(
            "à", "á", "ạ", "ả", "ã", "â", "ầ", "ấ", "ậ", "ẩ", "ẫ", "ă", "ằ", "ắ", "ặ", "ẳ", "ẵ",
            "è", "é", "ẹ", "ẻ", "ẽ", "ê", "ề", "ế", "ệ", "ể", "ễ",
            "ì", "í", "ị", "ỉ", "ĩ",
            "ò", "ó", "ọ", "ỏ", "õ", "ô", "ồ", "ố", "ộ", "ổ", "ỗ", "ơ", "ờ", "ớ", "ợ", "ở", "ỡ",
            "ù", "ú", "ụ", "ủ", "ũ", "ư", "ừ", "ứ", "ự", "ử", "ữ",
            "ỳ", "ý", "ỵ", "ỷ", "ỹ",
            "đ",
            "À", "Á", "Ạ", "Ả", "Ã", "Â", "Ầ", "Ấ", "Ậ", "Ẩ", "Ẫ", "Ă", "Ằ", "Ắ", "Ặ", "Ẳ", "Ẵ",
            "È", "É", "Ẹ", "Ẻ", "Ẽ", "Ê", "Ề", "Ế", "Ệ", "Ể", "Ễ",
            "Ì", "Í", "Ị", "Ỉ", "Ĩ",
            "Ò", "Ó", "Ọ", "Ỏ", "Õ", "Ô", "Ồ", "Ố", "Ộ", "Ổ", "Ỗ", "Ơ", "Ờ", "Ớ", "Ợ", "Ở", "Ỡ",
            "Ù", "Ú", "Ụ", "Ủ", "Ũ", "Ư", "Ừ", "Ứ", "Ự", "Ử", "Ữ",
            "Ỳ", "Ý", "Ỵ", "Ỷ", "Ỹ",
            "Đ");
        $marKoDau = array(
            "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a",
            "e", "e", "e", "e", "e", "e", "e", "e", "e", "e", "e",
            "i", "i", "i", "i", "i",
            "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o",
            "u", "u", "u", "u", "u", "u", "u", "u", "u", "u", "u",
            "y", "y", "y", "y", "y",
            "d",
            "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A",
            "E", "E", "E", "E", "E", "E", "E", "E", "E", "E", "E",
            "I", "I", "I", "I", "I",
            "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O",
            "U", "U", "U", "U", "U", "U", "U", "U", "U", "U", "U",
            "Y", "Y", "Y", "Y", "Y",
            "D");
        if ($strtolower != 0) {
            $str = strtolower(preg_replace(array('/[^a-zA-Z0-9 -]/', '/[ -]+/', '/^-|-$/'), array('', '-', ''), str_replace($marTViet, $marKoDau, $str)));
        } else {
            $str = preg_replace(array('/[^a-zA-Z0-9 -]/', '/[ -]+/', '/^-|-$/'), array('', '-', ''), str_replace($marTViet, $marKoDau, $str));
        }
        return $str;
    }

    public static function unsigned($str, $strtolower = 0)
    {
        $marTViet = array(
            "à", "á", "ạ", "ả", "ã", "â", "ầ", "ấ", "ậ", "ẩ", "ẫ", "ă", "ằ", "ắ", "ặ", "ẳ", "ẵ",
            "è", "é", "ẹ", "ẻ", "ẽ", "ê", "ề", "ế", "ệ", "ể", "ễ",
            "ì", "í", "ị", "ỉ", "ĩ",
            "ò", "ó", "ọ", "ỏ", "õ", "ô", "ồ", "ố", "ộ", "ổ", "ỗ", "ơ", "ờ", "ớ", "ợ", "ở", "ỡ",
            "ù", "ú", "ụ", "ủ", "ũ", "ư", "ừ", "ứ", "ự", "ử", "ữ",
            "ỳ", "ý", "ỵ", "ỷ", "ỹ",
            "đ",
            "À", "Á", "Ạ", "Ả", "Ã", "Â", "Ầ", "Ấ", "Ậ", "Ẩ", "Ẫ", "Ă", "Ằ", "Ắ", "Ặ", "Ẳ", "Ẵ",
            "È", "É", "Ẹ", "Ẻ", "Ẽ", "Ê", "Ề", "Ế", "Ệ", "Ể", "Ễ",
            "Ì", "Í", "Ị", "Ỉ", "Ĩ",
            "Ò", "Ó", "Ọ", "Ỏ", "Õ", "Ô", "Ồ", "Ố", "Ộ", "Ổ", "Ỗ", "Ơ", "Ờ", "Ớ", "Ợ", "Ở", "Ỡ",
            "Ù", "Ú", "Ụ", "Ủ", "Ũ", "Ư", "Ừ", "Ứ", "Ự", "Ử", "Ữ",
            "Ỳ", "Ý", "Ỵ", "Ỷ", "Ỹ",
            "Đ");
        $marKoDau = array(
            "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a",
            "e", "e", "e", "e", "e", "e", "e", "e", "e", "e", "e",
            "i", "i", "i", "i", "i",
            "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o",
            "u", "u", "u", "u", "u", "u", "u", "u", "u", "u", "u",
            "y", "y", "y", "y", "y",
            "d",
            "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A",
            "E", "E", "E", "E", "E", "E", "E", "E", "E", "E", "E",
            "I", "I", "I", "I", "I",
            "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O",
            "U", "U", "U", "U", "U", "U", "U", "U", "U", "U", "U",
            "Y", "Y", "Y", "Y", "Y",
            "D");
        if ($strtolower != 0) {
            $str = strtolower(str_replace($marTViet, $marKoDau, $str));
        } else {
            $str = str_replace($marTViet, $marKoDau, $str);
        }
        return $str;
    }

    public static function genKeyCode($str, $alog = 'sha256')
    {
        if ($str != '') {
            return hash($alog, $str);
        } else {
            return hash($alog, date('dmY'));
        }
    }

    public static function genExportPassword($length = 10)
    {
        if ($length > 0 && $length <= 32) {
            return substr(md5(rand(1, 9999)), 0, $length);
        } else {
            return substr(md5(rand(1, 9999)), 0, 10);
        }
    }

    /**
     * doanpv - 28/01/2016
     * Hàm đọc số thành chữ, dùng để đọc hóa đơn cước
     * @param $number
     * @return bool|null|string
     */
    public static function number2words($number)
    {
        $hyphen = ' ';
        $conjunction = '  ';
        $separator = ' ';
        $negative = 'âm ';
        $decimal = ' phẩy ';
        $dictionary = array(
            0 => 'Không',
            1 => 'Một',
            2 => 'Hai',
            3 => 'Ba',
            4 => 'Bốn',
            5 => 'Năm',
            6 => 'Sáu',
            7 => 'Bảy',
            8 => 'Tám',
            9 => 'Chín',
            10 => 'Mười',
            11 => 'Mười một',
            12 => 'Mười hai',
            13 => 'Mười ba',
            14 => 'Mười bốn',
            15 => 'Mười năm',
            16 => 'Mười sáu',
            17 => 'Mười bảy',
            18 => 'Mười tám',
            19 => 'Mười chín',
            20 => 'Hai mươi',
            30 => 'Ba mươi',
            40 => 'Bốn mươi',
            50 => 'Năm mươi',
            60 => 'Sáu mươi',
            70 => 'Bảy mươi',
            80 => 'Tám mươi',
            90 => 'Chín mươi',
            100 => 'trăm',
            1000 => 'ngàn',
            1000000 => 'triệu',
            1000000000 => 'tỷ',
            1000000000000 => 'nghìn tỷ',
            1000000000000000 => 'ngàn triệu triệu',
            1000000000000000000 => 'tỷ tỷ'
        );

        if (!is_numeric($number)) {
            return false;
        }

        if (($number >= 0 && (int)$number < 0) || (int)$number < 0 - PHP_INT_MAX) {
            // overflow
            trigger_error(
                'self::number2words only accepts numbers between -' . PHP_INT_MAX . ' and ' . PHP_INT_MAX,
                E_USER_WARNING
            );
            return false;
        }

        if ($number < 0) {
            return $negative . self::number2words(abs($number));
        }

        $string = $fraction = null;

        if (strpos($number, '.') !== false) {
            list($number, $fraction) = explode('.', $number);
        }

        switch (true) {
            case $number < 21:
                $string = $dictionary[$number];
                break;
            case $number < 100:
                $tens = ((int)($number / 10)) * 10;
                $units = $number % 10;
                $string = $dictionary[$tens];
                if ($units) {
                    $string .= $hyphen . $dictionary[$units];
                }
                break;
            case $number < 1000:
                $hundreds = $number / 100;
                $remainder = $number % 100;
                $string = $dictionary[$hundreds] . ' ' . $dictionary[100];
                if ($remainder) {
                    $string .= $conjunction . self::number2words($remainder);
                }
                break;
            default:
                $baseUnit = pow(1000, floor(log($number, 1000)));
                $numBaseUnits = (int)($number / $baseUnit);
                $remainder = $number % $baseUnit;
                $string = self::number2words($numBaseUnits) . ' ' . $dictionary[$baseUnit];
                if ($remainder) {
                    $string .= $remainder < 100 ? $conjunction : $separator;
                    $string .= self::number2words($remainder);
                }
                break;
        }

        if (null !== $fraction && is_numeric($fraction)) {
            $string .= $decimal;
            $words = array();
            foreach (str_split((string)$fraction) as $number) {
                $words[] = $dictionary[$number];
            }
            $string .= implode(' ', $words);
        }

        return $string;
    }

    public static function genSrcImageByBase64($path)
    {
        if ($path == '') {
            $path = '/uploads/grid.png';
        }
        $type = pathinfo($path, PATHINFO_EXTENSION);
        $data = file_get_contents($path);
        $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);

        return $base64;
    }

    public static function genPaginationLink($totalRecord, $pageSize = 10, $pageIndex = 1, $paginationName = 'changePagination')
    {
        $pagination = "";
        if ($pageSize >= 1 && $pageIndex >= 1) {
            $adjacents = "2";
            $prev = $pageIndex - 1;
            $next = $pageIndex + 1;
            $lastpage = ceil($totalRecord / $pageSize);
            $lpm1 = $lastpage - 1;
        } else {
            return $pagination;
        }

        if ($lastpage > 1) {
            $pagination .= "<div class='pagination'>";
            if ($pageIndex > 1) {
                $pagination .= "<a href=\"#page=" . ($prev) . "\" onClick='" . $paginationName . "(" . ($prev) . ");'>&laquo;&nbsp;</a>";
            } else {
                $pagination .= "<span class='disabled'>&laquo;&nbsp;</span>";
            }
            if ($lastpage < 7 + ($adjacents * 2)) {
                for ($counter = 1; $counter <= $lastpage; $counter++) {
                    if ($counter == $pageIndex) {
                        $pagination .= "<span class='current'>$counter</span>";
                    } else {
                        $pagination .= "<a href=\"#page=" . ($counter) . "\" onClick='" . $paginationName . "(" . ($counter) . ");'>$counter</a>";
                    }
                }
            } elseif ($lastpage > 5 + ($adjacents * 2)) {
                if ($pageIndex < 1 + ($adjacents * 2)) {
                    for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++) {
                        if ($counter == $pageIndex) {
                            $pagination .= "<span class='current'>$counter</span>";
                        } else {
                            $pagination .= "<a href=\"#page=" . ($counter) . "\" onClick='" . $paginationName . "(" . ($counter) . ");'>$counter</a>";
                        }
                    }
                    $pagination .= "...";
                    $pagination .= "<a href=\"#page=" . ($lpm1) . "\" onClick='" . $paginationName . "(" . ($lpm1) . ");'>$lpm1</a>";
                    $pagination .= "<a href=\"#page=" . ($lastpage) . "\" onClick='" . $paginationName . "(" . ($lastpage) . ");'>$lastpage</a>";

                } elseif ($lastpage - ($adjacents * 2) > $pageIndex && $pageIndex > ($adjacents * 2)) {
                    $pagination .= "<a href=\"#page=\"1\"\" onClick='" . $paginationName . "(1);'>1</a>";
                    $pagination .= "<a href=\"#page=\"2\"\" onClick='" . $paginationName . "(2);'>2</a>";
                    $pagination .= "...";
                    for ($counter = $pageIndex - $adjacents; $counter <= $pageIndex + $adjacents; $counter++) {
                        if ($counter == $pageIndex) {
                            $pagination .= "<span class='current'>$counter</span>";
                        } else {
                            $pagination .= "<a href=\"#page=" . ($counter) . "\" onClick='" . $paginationName . "(" . ($counter) . ");'>$counter</a>";
                        }
                    }
                    $pagination .= "..";
                    $pagination .= "<a href=\"#page=" . ($lpm1) . "\" onClick='" . $paginationName . "(" . ($lpm1) . ");'>$lpm1</a>";
                    $pagination .= "<a href=\"#page=" . ($lastpage) . "\" onClick='" . $paginationName . "(" . ($lastpage) . ");'>$lastpage</a>";
                } else {
                    $pagination .= "<a href=\"#page=\"1\"\" onClick='" . $paginationName . "(1);'>1</a>";
                    $pagination .= "<a href=\"#page=\"2\"\" onClick='" . $paginationName . "(2);'>2</a>";
                    $pagination .= "..";
                    for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++) {
                        if ($counter == $pageIndex) {
                            $pagination .= "<span class='current'>$counter</span>";
                        } else {
                            $pagination .= "<a href=\"#page=" . ($counter) . "\" onClick='" . $paginationName . "(" . ($counter) . ");'>$counter</a>";
                        }
                    }
                }
            }
            if ($pageIndex < $counter - 1) {
                $pagination .= "<a href=\"#page=" . ($next) . "\" onClick='" . $paginationName . "(" . ($next) . ");'> &raquo;</a>";
            } else {
                $pagination .= "<span class='disabled'> &raquo;</span>";
            }
            $pagination .= "</div> (Tổng số kết quả: " . number_format($totalRecord) . ")";
        }
        return $pagination;
    }

    /**
     * 28/07/2016 @ hieudd
     * Hàm crop ảnh
     * @param $source
     * @return bool
     */
    public static function cropImg($source, $w, $h)
    {
        $config['image_library'] = 'gd2';
        $config['source_image'] = $source;
        $config['create_thumb'] = TRUE;
        $config['maintain_ratio'] = FALSE;
        $imageSize = getimagesize($config['source_image']);
        $width = $imageSize[0];
        $height = $imageSize[1];
        if ($width * $h > $height * $w) {
            $config['width'] = ($height * $w) / $h;
            $config['height'] = $height;
            $config['x_axis'] = (($width / 2) - ($config['width'] / 2));
        } else {
            $config['height'] = ($width * $h) / $w;
            $config['width'] = $width;
            $config['y_axis'] = (($height / 2) - ($config['height'] / 2));
        }
        $CI = &get_instance();
        $CI->load->library('image_lib', $config);
        $CI->image_lib->initialize($config);
        if ($CI->image_lib->crop()) {
            $return = true;
        } else {
            $return = false;
        }
        $CI->image_lib->clear();
        unset($config);
        return $return;
    }

    /**
     * 8/09/2016 @ hieudd
     * Hàm resize ảnh
     * @param $source
     * @return bool
     */
    public static function resizeImg($source)
    {
        $config['image_library'] = 'gd2';
        $config['source_image'] = $source;
        $config['create_thumb'] = TRUE;
        $config['thumb_marker'] = '_thumb';
        $config['maintain_ratio'] = FALSE;
        $imageSize = getimagesize($config['source_image']);
        $width = $imageSize[0];
        $height = $imageSize[1];
        if ($width > $height) {
            $config['width'] = 100;
            $config['height'] = (100 * $height) / $width;
        } else {
            $config['height'] = 100;
            $config['width'] = (100 * $width) / $height;
        }
        $CI = &get_instance();
        $CI->load->library('image_lib', $config);
        $CI->image_lib->initialize($config);
        if ($CI->image_lib->resize()) {
            $return = true;
        } else {
            $return = false;
        }
        $CI->image_lib->clear();
        unset($config);
        return $return;
    }

    /**
     * 01/08/2016 by doanpv
     * @param null $id
     * @return array|string
     */
    public static function getErrorCode($id = null)
    {
        $arr = array(
            '0' => '0 - Thành công',
            '1' => '1 - Sai phương thức',
            '2' => '2 - Lỗi DB',
            '3' => '3 - Thiếu tham số'
        );
        if ($id != null) {
            if (array_key_exists($id, $arr)) {
                return $arr[$id];
            } else {
                return '';
            }
        } else {
            return $arr;
        }
    }

    /**
     * Ham kiem tra duong dan anh trong DB
     * Neu co http:// hoac https:// thi lay nguyen duong dan
     * Neu ko co thi ghep them base_url vao
     * 08/08/2016 - doanpv
     * @param $base_url
     * @param $image_path
     * @return string
     */
    public static function getImageSrcFromDB($base_url, $image_path)
    {
        if ($base_url != '' && $image_path != '') {
            if (preg_match("/^(.*)(http:\/\/|https:\/\/)(.*)$/", $image_path)) {
                return $image_path;
            } else {
                return $base_url . $image_path;
            }
        } else {
            return '';
        }
    }

    public static function getThumbImageSrcFromDB($base_url, $image_path)
    {
        if ($base_url != '' && $image_path != '') {
            if (preg_match("/^(.*)(http:\/\/|https:\/\/)(.*)$/", $image_path)) {
                return str_replace('/images/', '/_thumbs/Images/', $image_path);
            } else {
                return $base_url . str_replace('/images/', '/_thumbs/Images/', $image_path);
            }
        } else {
            return '';
        }
    }

    /**
     * Ham lay ds ten module
     * 10/08/2016 - doanpv
     * @param null $id
     * @return array|string
     */
    public static function getModuleName($id = null)
    {
        $arr = array(
            'account' => 'Tài khoản',
            'chatSocketIO' => 'Chat',
            'gift' => 'Vật phẩm',
            'home' => 'Trang chủ',
            'resource' => 'Tài nguyên',
            'setting' => 'Hệ thống',
            'slideAds' => 'Slide-Ads',
            'streaming' => 'Streaming',
            'user' => 'Thành viên',
            'news' => 'Tin tức',
            'statistic' => 'Thống kê',
        );
        if ($id != null) {
            if (array_key_exists($id, $arr)) {
                return $arr[$id];
            } else {
                return '';
            }
        } else {
            return $arr;
        }
    }

    /**
     * Ham kiem tra duong dan anh trong DB
     * Neu co http:// hoac https:// thi lay nguyen duong dan
     * Neu ko co thi ghep them base_url vao
     * 08/08/2016 - doanpv
     * @param $base_url
     * @param $image_path
     * @return string
     */
    public static function getUserAvatarPath($base_url, $image_path)
    {
        if ($base_url != '' && $image_path != '') {
            $image_path = str_replace('/upload', 'upload', $image_path);
            $image_path = str_replace('/public', 'public', $image_path);
            if (preg_match("/^(.*)(http:\/\/|https:\/\/)(.*)$/", $image_path)) {
                return $image_path;
            } else {
                return $base_url . $image_path;
            }
        } else {
            return '';
        }
    }

    /**
     * simple dectect mobile device
     * 14/10/2016 by hieudd
     */
    public static function detectMobileDevice()
    {
        $useragent = $_SERVER['HTTP_USER_AGENT'];

        if (preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i', $useragent) || preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i', substr($useragent, 0, 4))) {
            return true;
        } else {
            return false;
        }

    }

    //Kiem tra truyen thieu tham so
    public static function validateNullParams($arrayParams)
    {
        foreach ($arrayParams as $key => $values) {
            $values = trim($values);
            if (!$values || $values == '' || $values == null || empty($values)) {
                return $key;
            }
        }
        return false;
    }

    /**
     * Ham lay ds key va security dang nhap bang facebook gogle
     */
    public static function getKeySecurity($id = null)
    {
        $arr = array(
            'key_facebook' => '386922185012961',
            'security_facebook' => '448b7b1160e0f7a5d16d55aa1a84d456',
            'key_google' => '640127056152-rcq545s5vr2q0q6j4r87dpb7h3p4rpqm.apps.googleusercontent.com',
            'security_google' => 'R9s2L_D9nF6_U_nUfJblnbHc',
        );
        if ($id != null) {
            if (array_key_exists($id, $arr)) {
                return $arr[$id];
            } else {
                return '';
            }
        } else {
            return $arr;
        }
    }

    //Tra ve gia tri khi muon tra ve api
    public static function responseApi($arrResult)
    {
        if (is_array($arrResult) && count($arrResult) >= 4) {
            echo json_encode($arrResult);
        } else {
            $data['urlApi'] = isset($arrResult['urlApi']) ? $arrResult['urlApi'] : base_url('api/apiGame/?');
            $data['errorCode'] = 4;
            $data['message'] = 'Có lỗi từ dữ liệu trả về. Bạn vui lòng, kiểm tra lại!';
            $data['data'] = null;
            echo json_encode($data);
        }
        die();
    }

    /**
     * @param $date_order
     * @return null
     */
    public static function getDatePlayByDateOrder($date_order)
    {
        $CI = &get_instance();
        $CI->load->model('mcontest_details');
        $data = $CI->mcontest_details->getByDateOrder($date_order);
        if ($data) {
            return $data[0]['date_play'];
        } else {
            return null;
        }
    }

    /**
     * Lấy top trong ngày
     * @param $date
     * @return array
     */
    public static function getTopByDate($date)
    {
        $CI = &get_instance();
        $CI->load->model('mgame_details');
        $data = $CI->mgame_details->getTopByDateInOneGame(10, 0, $date, null);
        if ($data) {
            return $data;
        } else {
            return array();
        }
    }

    /**
     * Lấy top trong tuần
     * @param $date
     * @return array
     */
    public static function getTopByWeek($date1, $date7)
    {
        $CI = &get_instance();
        $CI->load->model('mgame_details');
        $data = $CI->mgame_details->getTopWeek($date1, $date7);
        if ($data) {
            return $data[0];
        } else {
            return array();
        }
    }

    /**
     * Tao token ngay sau khi login thanh cong
     * Token = hash256(time()*user_agent)
     */
    public static function getToken()
    {
        $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : md5(time());
        return self::genKeyCode(time().$user_agent);
    }

    /**
     * Tính toán đường dẫn ảnh của bài hát tương ứng với ca sĩ thể hiện bài hát đó
     * Nếu không tìm thấy ảnh thì lấy giá trị mặc định
     *
     * @param $art
     *
     * @return string
     */
    public static function getArtByTrack($art, $is_same_src=false)
    {
        $CI = &get_instance();
        $default_image = base_url('images/track.png');
        if ($art) {
            if ($is_same_src) {
                $default_image = base_url(str_replace('%w', 200, $art));
            } else {
                $default_image = $CI->config->item('vmusicchart_url') . str_replace('%w', 200, $art);
            }
        }
        return $default_image;
    }

    /**
     * Hàm trả về ảnh icon của nguồn nhạc
     *
     * @param $id_zing
     * @param $id_nct
     * @param $id_keeng
     *
     * @return string
     */
    public static function getSourceIcon($id_zing, $id_nct, $id_keeng)
    {
        $html = '';
        if (!empty($id_zing)) {
            $html .= "<span title='Nguồn Zing MP3'><img src='" . base_url('images/favicon/zing_favicon_20x.png') . "'></span>&nbsp;&nbsp;";
        }
        if (!empty($id_nct)) {
            $html .= "<span title='Nguồn NCT'><img src='" . base_url('images/favicon/nct_favicon_16x.png') . "'></span>&nbsp;&nbsp;";
        }
        if (!empty($id_keeng)) {
            $html .= "<span title='Nguồn Keeng'><img src='" . base_url('images/favicon/keeng_favicon_16x.png') . "'></span>";
        }
        return $html;
    }

    /**
     * Hàm lấy thông tin so sánh tuần trước, tháng trước, ngày trước
     *
     * @param $track_id
     * @param $order
     * @param $previousRanking
     *
     * @return string
     */
    public static function getRankingCompare($track_id, $order, $previousRanking)
    {
        $compare = 1000;
        if (is_array($previousRanking) && count($previousRanking) > 0) {
            if (array_key_exists($track_id, $previousRanking)) {
                $old_ranking = $previousRanking[$track_id];
                $compare = $old_ranking - $order;
            }
        }

        $resutl = '';
        if ($compare == 1000) {
            $resutl = '<span>Mới</span>';
        } else {
            if ($compare < 0) {
                $resutl = '<i class="fa fa-caret-down" aria-hidden="true" style="font-size: 20px; color: #f50202"></i>&nbsp;&nbsp;' . abs($compare);
            } else if ($compare == 0) {
                $resutl = '<i class="fa fa-minus" aria-hidden="true" style="font-size: 20px; color: #999999"></i>';
            } else {
                $resutl = '<i class="fa fa-caret-up" aria-hidden="true" style="font-size: 20px; color: #22ba4e"></i>&nbsp;&nbsp;' . $compare;
            }
        }
        return $resutl;
    }

    /**
     * Hàm lấy ngày đầu tiên và cuối cùng của 1 tuần trong năm
     * 0- Nếu tuần bắt đầu là chủ nhật
     * 1- Nếu tuần bắt đầu là thứ 2
     *
     * @param $week
     * @param $year
     * @param string $format
     *
     * @return mixed
     */
    public static function getWeekDateRange($week, $year, $format='d/m/Y')
    {
        $dto = new DateTime();
        $dto->setISODate($year, $week, 0); // 0: CN

        $ret['start_week'] = $dto->format($format);
        $dto->modify('+6 days');
        $ret['end_week'] = $dto->format($format);

        return $ret;
    }


}
/* End */