<?php

class TrataImagem
{
    /**
     * Método para cortar a imagem.
     *
     * @param  string  $imgFull
     * @param  string  $imgCrop
     * @param  int $x
     * @param  int $y
     * @param  int $w
     * @param  int $h
     * @param  int $cw
     * @param  int $ch
     * @param  int $quality
     */
    public static function crop($imgFull = '', $imgCrop = '', $x = 0, $y = 0, $w = 0, $h = 0, $cw = 0, $ch = 0, $quality = 100)
    {
        $sizes = self::getProperties($imgFull);

        switch ($sizes['type']) {
            case 'jpg':
                         
                $src_img = imagecreatefromjpeg($imgFull);
                $dst_img = imagecreatetruecolor($cw, $ch);
                imagecopyresampled($dst_img, $src_img, 0, 0, $x, $y, $cw, $ch, $w, $h);
                imagejpeg($dst_img, $imgCrop, $quality);
            
                break;
            case 'png':
                $quality = ceil($quality / 10); // for png quality is compression, 0-9, 9 full compression
                $quality = (0 == $quality) ? 9 : (($quality - 1) % 9);

                $src_img = imagecreatefrompng($imgFull);
                $dst_img = imagecreatetruecolor($cw, $ch);
                imagealphablending($dst_img, false);
                imagecopyresampled($dst_img, $src_img, 0, 0, $x, $y, $cw, $ch, $w, $h);
                imagesavealpha($dst_img, true);
                imagepng($dst_img, $imgCrop, $quality);
                break;
            case 'gif':
                $src_img = imagecreatefromgif($imgFull);
                $dst_img = imagecreatetruecolor($cw, $ch);
                imagecopyresampled($dst_img, $src_img, 0, 0, $x, $y, $cw, $ch, $w, $h);
                imagegif($dst_img, $imgCrop); //no quality option available
                break;
        }

        imagedestroy($dst_img);
        imagedestroy($src_img);
    }

    /**
     * Método para redimensionar a imagem.
     *
     * @param  string  $img
     * @param  string  $neww
     * @param  string  $newh
     * @param  int $quality
     */
    public static function resize($img = '', $neww = '', $newh = '', $quality = 100)
    {
        $sizes = self::getProperties($img);
        $oldw = $sizes['w'];
        $oldh = $sizes['h'];

        switch ($sizes['type']) {
            //resize jpg
            case 'jpg':
                $src_img = imagecreatefromjpeg($img);
                $dst_img = imagecreatetruecolor($neww, $newh);
                imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $neww, $newh, $oldw, $oldh);
                imagejpeg($dst_img, $img, $quality);
                break;
            //resize png
            case 'png':
                $quality = ceil($quality / 10); // for png quality is compression, 0-9, 9 full compression
                $quality = (0 == $quality) ? 9 : (($quality - 1) % 9);

                $src_img = imagecreatefrompng($img);
                $dst_img = imagecreatetruecolor($neww, $newh);
                imagealphablending($dst_img, false);
                imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $neww, $newh, $oldw, $oldh);
                imagesavealpha($dst_img, true);
                imagepng($dst_img, $img, $quality);

                break;
            //resize gif
            case 'gif' :
                $src_img = imagecreatefromgif($img);
                $dst_img = imagecreatetruecolor($neww, $newh);
                imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $neww, $newh, $oldw, $oldh);
                imagegif($dst_img, $img); //no quality option available
                break;
        }

        imagedestroy($dst_img);
        imagedestroy($src_img);
    }

    /**
     * Exibe a propriedade da imagem.
     *
     * @param  string $src
     * @return array
     */
    public static function getProperties($src = '')
    {
        $sizes = getimagesize($src);

        $imgtypes = array(
            '1' => 'gif',
            '2' => 'jpg',
            '3' => 'png',
            '4' => 'png',
        );

        $retorno = array(
            'w' => $sizes[0],
            'h' => $sizes[1],
            'type' => $imgtypes[$sizes[2]],
            'mime' => $sizes['mime'],
        );

        return $retorno;
    }

    /**
     * Método que prepara o crop padrão.
     *
     * @param  string $dest
     * @param  string $destCrop
     * @param  string $cw
     * @param  string $ch
     * @return mixed
     */
    public static function preparaCropDefault($dest = '', $destCrop = '', $cw = '', $ch = '')
    {
            
        if (strpos($destCrop, 'thumb')) {
            self::resize_crop_image_thumb(244, 244, $dest, $destCrop);
        } else { 
            $prop = self::getProperties($dest);
            $w = $prop['w'];
            $h = $prop['h'];
            $ratioFull = $w / $h;
            $ratioCrop = $cw / $ch;

            $percentualW = $cw / $w;
            $percentualH = $ch / $h;

            if ($ratioFull > $ratioCrop) {
                // height
                $nh = $ch / $percentualH;
                $nw = $h * $ratioCrop;
                $x = ($w - $nw) * .5;
                $y = 0;
            } else {
                // width
                $nw = $cw / $percentualW;
                $nh = $w / $ratioCrop;
                $x = 0;
                $y = ($h - $nh) * .5;
            }
            
            $crop = self::crop($dest, $destCrop, $x, $y, $nw, $nh, $cw, $ch, 100);
        }
    }

    /**
     * Método que prepara o crop do JS.
     *
     * @param  string $param
     * @param  string $imgFull
     * @return mixed
     */
    public static function preparaCropJS($param = '', $imgFull = '')
    {
        $imgFull = str_replace(Util::baseUrl(), Util::baseDir(), $param['src']);

        $prop = self::getProperties($imgFull);
        $percentual = $prop['w'] / $param['widthPreview'];

        $x = $param['x'] * $percentual;
        $y = $param['y'] * $percentual;
        $w = $param['w'] * $percentual;
        $h = $param['h'] * $percentual;
        $imgCrop = str_replace('full/', '', $imgFull);
        $cw = $param['cropWidth'];
        $ch = $param['cropHeight'];
        $imgThumb =  str_replace('/produto/', '/produto/thumb/', $imgCrop);
        
        
        $crop = self::crop($imgFull, $imgCrop, $x, $y, $w, $h, $cw, $ch, 100);
        self::resize_crop_image_thumb(244, 244, $imgCrop, $imgThumb, 100  );
    }

     public static function resize_crop_image_thumb($max_width, $max_height, $source_file, $dst_dir, $quality = 100){
        $imgsize = getimagesize($source_file);
        $width = $imgsize[0];
        $height = $imgsize[1];
        $mime = $imgsize['mime'];

        switch($mime){
            case 'image/gif':
                $image_create = "imagecreatefromgif";
                $image = "imagegif";
                break;

            case 'image/png':
                $image_create = "imagecreatefrompng";
                $image = "imagepng";
                $quality = 7;
                break;

            case 'image/jpeg':
                $image_create = "imagecreatefromjpeg";
                $image = "imagejpeg";
                $quality = 80;
                break;

            default:
                return false;
                break;
        }

        

        if ($height > $width) { 
            $indice = $width/$max_width;
            $heigh_final = (int)$height/$indice;
            $dst_img = imagecreatetruecolor($max_width, $heigh_final);
            $src_img = $image_create($source_file);
            imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $max_width, $heigh_final, $width,  $height);
        } else if ($width > $height){
            $indice = $height/$max_height;
            $width_final = (int)$width/$indice;
            $dst_img = imagecreatetruecolor($width_final, $max_height);
            $src_img = $image_create($source_file);
            imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $width_final, $max_height, $width,  $height);
            
        } else {
            $dst_img = imagecreatetruecolor($width, $height);
            $src_img = $image_create($source_file);
            imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $width, $height, $width,  $height);
        }

        $image($dst_img, $dst_dir, $quality);

        if($dst_img)imagedestroy($dst_img);
        if($src_img)imagedestroy($src_img);

        //crop
        $dst_img2 = imagecreatetruecolor($max_width, $max_width);
        $src_img = $image_create($dst_dir);
        $im2 = imagecrop($src_img, ['x' => 0, 'y' => 0, 'width' => $max_width, 'height' => $max_height]);
        $image($im2, $dst_dir, $quality);
        ;
        if($im2)imagedestroy($im2);
        if($src_img)imagedestroy($src_img);
    }
}
