<?php

    class Commons {

        const BR_DATE      = 'd/m/Y';
        const BR_TIMEDATE  = 'H:i d/m/Y';
        const BR_DATETIME  = 'd/m/Y H:i';
        const US_DATE      = 'Y-m-d';
        const US_DATETIME  = 'Y-m-d H:i:s';
        const TIME         = 'H:i';
        const FULL_TIME    = 'H:i:s';
        const TIME_HOURS   = 'H';
        const TIME_MINUTES = 'i';
        const TIME_SECONDS = 's';
        const DELAY        = 0;

        public static function slug($str, $replace = array(), $delimiter = '-') {
            setlocale(LC_ALL, 'en_US.UTF8');
            if( !empty($replace) ) {
                $str = str_replace((array)$replace, ' ', $str);
            }

            $clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
            $clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
            $clean = strtolower(trim($clean, '-'));
            $clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);

            return $clean;
        }

        public static function slugFile( $file, $replace = array(), $delimiter = '-' ){

            if(!is_string($file)){
                $file = $file['name'];
            }

            $extension = explode('.', $file);
            $extension = $extension[count($extension) - 1];
            $file = str_replace($extension, '', $file);
            $name = self::slug(rand(1, 9999) . '-' . $file, $replace, $delimiter);
            $name = implode('.', array($name, $extension));

            return $name;

        }

        public static function slugExists($conn, $slug, $table, $colName = 'slug', $id = null){

            if($id != null){
                $check = $conn->prepare("SELECT COUNT( :colName ) FROM {$table} WHERE {$colName} = :slug AND id <> :id");
                $check->bindParam(':id', $id);
            }else{
                $check = $conn->prepare("SELECT COUNT( :colName ) FROM {$table} WHERE {$colName} = :slug");
            }

            $check->bindParam(':colName', $colName);
            $check->bindParam(':slug', $slug);

            if( $check->execute() ){

                $total = $check->fetchColumn(0);

                if($total > 0){
                    return $total;
                }else{
                    return false;
                }

            }else{
                return false;
            }
        }

        public static function uniqueSlug($text, $conn, $table, $colName = 'slug', $id = null){

            $slug = self::slug($text);

            $cont = 0;
            $exist = self::slugExists($conn, $slug, $table, $colName, $id);

            while($exist){
                $cont += ($cont == 0) ? ($exist + 1) : $exist;
                $exist = self::slugExists($conn, ($slug . '-' . $cont), $table, $colName, $id);
            }

            return ($cont > 0) ? $slug . '-' . $cont : $slug;

        }

        public static function dateFormat($date, $type = self::BR_DATETIME){

            $date = new DateTime($date);

            return $date->format($type);
        
        }

        public static function reverseDate($date, $separator = '-'){
            return implode($separator, array_reverse(explode("/", $date)));
        }

        public static function prepareDir($dir, $permission = 0755){
            if( !file_exists( $dir ) ){
                $create = mkdir($dir, $permission);

                if(substr($dir, -1) != '/'){
                    $dir .= '/';
                }

                file_put_contents($dir . 'index.html', null);

            }else{
                return true;
            }
        }

        public static function convertFileToArray($file){
             $format = array();

            if( is_array($file['size']) ) {
                
                for($i = 0; $i < count($file['size']); $i++){
                    if($file['size'] > 0){
                        $format[] = array(
                            'size' => $file['size'][$i],
                            'tmp_name' => $file['tmp_name'][$i],
                            'name' => $file['name'][$i],
                            'type' => $file['type'][$i]
                        );
                    }
                }

            }else{

                $format[] = $file;

            }

            return $format;
        }

        public static function uploadImage( $file, $staticDir ){

            self::prepareDir(ROOT_PATH . '/statics/' . $staticDir);
            self::prepareDir(ROOT_PATH . '/statics/' . $staticDir . '/thumbs');

            $format = self::convertFileToArray($file);

            $fileNames = array();
            
            foreach ($format as $img){

                if($img['size'] > 0){

                    $image = WideImage::load($img['tmp_name']);
                    $name = self::slugFile($img['name']);

                    if($image->getWidth() > $image->getHeight())
                        $image = $image->resize(800, null);
                    else
                        $image = $image->resize(null, 800);

                    $image->saveToFile(ROOT_PATH . '/statics/' . $staticDir . '/' . $name);

                    if($image->getWidth() > $image->getHeight())
                        $image = $image->resize(300, null);
                    else
                        $image = $image->resize(null, 300);

                    // Save Thumb
                    $image->saveToFile(ROOT_PATH . '/statics/' . $staticDir . '/thumbs/' . $name);

                    $fileNames[] = $name;
                }
            }

            return (!empty($fileNames)) ? implode(', ', $fileNames) : null;

        }

        public static function redirectTo($url, $delay = self::DELAY) {
            echo "<meta http-equiv='refresh' content='{$delay}, url={$url}'>";
        }

        public static function drawPagination($current, $total, $gets = array(), $position = 'left', $return = false){

            $struct = '';

            if($total > 1){

                $extraGets = null;
                if(!empty($gets)){
                    $extraGets = '?' . http_build_query($gets);
                }

                $struct .= '<div class="pagination ' . $position . '">';

                if($current > 1)
                    $struct .= '<a href="' . (($extraGets != null) ? $extraGets . '&page=1' : '?page=1') . '">Primeira</a>';

                for($i = 1; $i <= $total; $i++){
                    if($current == $i){
                        $struct .= '<a href="javascript:void;" class="active">' . $i . '</a>';
                    }else{
                        $struct .= '<a href="' . (($extraGets != null) ? $extraGets . "&page=$i" : "?page=$i") . '" >' . $i . '</a>';
                    }
                }

                if($current < $total)
                    $struct .= '<a href="' . (($extraGets != null) ? $extraGets . '&page=' . $total : '?page=' . $total) . '">Ultima</a>';

                $struct .= '</div>';
            }

            if($return)
                return $struct;
            else
                print $struct;

        }

        public static function limitarTexto($texto, $limite){
            $contador = strlen($texto);
            if ($contador > $limite){
                $texto = substr($texto, 0, strrpos(substr($texto, 0, $limite), ' '));
            }
            return $texto;
        }

    }