<?php

class ResizeImg extends Model
{

    private $dirpath;
    private $folder;

    public function getFolder()
    {
        return $this->folder;
    }

    public function setFolder($folder)
    {
        $this->folder = $folder;
    }

    public function getDirpath()
    {
        return $this->dirpath;
    }

    public function setDirpath($dirpath)
    {
        $this->dirpath = $dirpath;
    }

    public function resize($filename, $width, $height, $type = "", $return = true)
    {
        if (!file_exists($this->getDirpath() . $filename) || !is_file($this->getDirpath() . $filename)) {
            return;
        }

        $info = pathinfo($filename);

        $extension = $info['extension'];

        $old_image = $filename;
        $new_image = 'cache/' . utf8_substr($filename, 0, utf8_strrpos($filename, '.')) . '-' . $width . 'x' . $height . $type . '.' . $extension;

        if (!file_exists($this->getDirpath() . $new_image) || (filemtime($this->getDirpath() . $old_image) > filemtime($this->getDirpath() . $new_image))) {
            $path = '';

            $directories = explode('/', dirname(str_replace('../', '', $new_image)));

            foreach ($directories as $directory) {
                $path = $path . '/' . $directory;

                if (!file_exists($this->getDirpath() . $path)) {
                    @mkdir($this->getDirpath() . $path, 0777);
                }
            }

            list($width_orig, $height_orig) = getimagesize($this->getDirpath() . $old_image);

            if ($width_orig != $width || $height_orig != $height) {
                $image = new Image($this->getDirpath() . $old_image);
                if(!$image->getImage()){
                    $this->log->write('Erro na Imagem: '. $old_image);
                }

                $image->resize($width, $height, $type);
                $image->save($this->getDirpath() . $new_image);
            } else {
                copy($this->getDirpath() . $old_image, $this->getDirpath() . $new_image);
            }


        }

        if ($return) {
            return $this->urlloja->link('', '', 'SSL', false) . $this->getFolder() . '/' . $new_image;
        } else {
            return $new_image;
        }

    }

    public function resizeWithWatermark($filename, $width, $height, $type = "", $return = true)
    {
        if (!file_exists($this->getDirpath() . $filename) || !is_file($this->getDirpath() . $filename)) {
            return;
        }

        $config_watermark = $this->config->get('config_watermark');
        if ($config_watermark) {
            $cache_dir = 'cache/watermark/';
        } else {
            $cache_dir = 'cache/';
        }

        $info = pathinfo($filename);
        $extension = $info['extension'];
        $old_image = $filename;
        $new_image = $cache_dir . utf8_substr($filename, 0, utf8_strrpos($filename, '.')) . '-' . $width . 'x' . $height . $type . '.' . $extension;

        //se a imagem nao existir ele atribui zero pra data do cache ser menor que a data da watermark e gerar com watermark - by Marcos Duca
        $img_cache_date = file_exists($this->getDirpath() . $new_image) ? filemtime($this->getDirpath() . $new_image) : 0;
        $config_watermark_date = $this->config->get('config_watermark_date');
        $config_watermark_date = $config_watermark_date ? DateTime::createFromFormat('d/m/Y H:i:s', $config_watermark_date) : false;
        $config_watermark_date = $config_watermark_date ? $config_watermark_date->getTimestamp() : false;
        $update_watermark = ($config_watermark_date) && ($img_cache_date < $config_watermark_date);

        if (!file_exists($this->getDirpath() . $new_image) ||
           (filemtime($this->getDirpath() . $old_image) > filemtime($this->getDirpath() . $new_image)) || $update_watermark) {
            $path = '';

            $directories = explode('/', dirname(str_replace('../', '', $new_image)));

            foreach ($directories as $directory) {
                $path = $path . '/' . $directory;

                if (!file_exists($this->getDirpath() . $path)) {
                    @mkdir($this->getDirpath() . $path, 0777);
                }
            }

            list($width_orig, $height_orig) = getimagesize($this->getDirpath() . $old_image);


            if ($width_orig != $width || $height_orig != $height) {
                $image = new Image($this->getDirpath() . $old_image);
                $image->resize($width, $height, $type);
                $image->save($this->getDirpath() . $new_image);
            } else {
                copy($this->getDirpath() . $old_image, $this->getDirpath() . $new_image);
            }

            if($config_watermark){
                $position = $this->getWatermarkPosDescription($this->config->get('config_watermark_position'));

                $size = array();
                $size = $this->getProportionalWatermarkSize($this->getDirpath() . $config_watermark, $width, $height); //recebe o tamanho da imagem original que ira receber a watermark

                $caminho_cache_wt = $this->resize($config_watermark,  $size['width'], $size['height'], $type, false);

                $config_watermark_opacity = $this->config->get('config_watermark_opacity');
                if($caminho_cache_wt && $config_watermark_opacity){
                    $image = new Image($this->getDirpath() . $new_image);
                    $image->watermark($this->getDirpath() . $caminho_cache_wt, $position, $config_watermark_opacity);
                }
            }
        }


        if ($return) {
            return $this->urlloja->link('', '', 'SSL', false) . $this->getFolder() . '/' . $new_image;
        } else {
            return $new_image;
        }

    }

    public function getProportionalWatermarkSize($watermark_filename, $original_image_width, $original_image_height){
        $width_wtm = $original_image_width * 0.50;
        $height_wtm = $original_image_height * 0.50;

        $image_info = getimagesize($watermark_filename);
        $width_aux = $image_info[0];
        $height_aux = $image_info[1];

        $new_width;
        $new_height;
        $multiplier_factor;

        if ($width_aux < $height_aux) {
            $new_height = $height_wtm;
            $multiplier_factor = $width_aux / $height_aux;
            $new_width = round($new_height * $multiplier_factor);
        } else {
            $new_width = $width_wtm;
            $multiplier_factor = $height_aux / $width_aux;
            $new_height = round($new_width * $multiplier_factor);
        }

        $size = array();
        $size['width'] = $new_width;
        $size['height'] = $new_height;

        return $size;
    }

    public function getWatermarkPosDescription($position){
        switch ($position){
            case Type_WatermarkPosition::Tp_TopLeft:
                $result = 'topleft';
                break;

            case Type_WatermarkPosition::Tp_TopRigth:
                $result = 'topright';
                break;

            case Type_WatermarkPosition::Tp_BottomLeft:
                $result = 'bottomleft';
                break;

            case Type_WatermarkPosition::Tp_BottomRigth:
                $result = 'bottomright';
                break;

            case Type_WatermarkPosition::Tp_Center:
                $result = 'center';
                break;

            default : $result = 'bottomleft';
        }

        return $result;
    }

    public function getWatermarkCacheNumber(){
        $watermark_date = $this->config->get('config_watermark_date');
        return $watermark_date && $this->config->get('config_watermark') ? preg_replace("/[^0-9]/", "", $watermark_date) : '';
    }
}
