<?php

class Images {

    public $handleimg;
    public $original;
    public $handlethumb;
    public $oldoriginal;

    /*
      Apre l'immagine da manipolare
     */

    public function openImg($file) {

        $this->original = $file;

        if ($this->extension($file) == 'jpg' || $this->extension($file) == 'jpeg') {
            $this->handleimg = imagecreatefromjpeg($file);
        } elseif ($this->extension($file) == 'png') {
            $this->handleimg = imagecreatefrompng($file);
        } elseif ($this->extension($file) == 'gif') {
            $this->handleimg = imagecreatefromgif($file);
        } elseif ($this->extension($file) == 'bmp') {
            $this->handleimg = imagecreatefromwbmp($file);
        }
    }

    public function getWidth() {
        return imageSX($this->handleimg);
    }

    /*
      Ottiene la larghezza proporzionata all'immagine partendo da un'altezza
     */

    public function getRightWidth($newheight) {
        $oldw = $this->getWidth();
        $oldh = $this->getHeight();

        $neww = ($oldw * $newheight) / $oldh;

        return $neww;
    }

    /*
      Ottiene l'altezza dell'immagine
     */

    public function getHeight() {
        return imageSY($this->handleimg);
    }

    /*
      Ottiene l'altezza proporzionata all'immagine partendo da una larghezza
     */

    public function getRightHeight($newwidth) {
        $oldw = $this->getWidth();
        $oldh = $this->getHeight();

        $newh = ($oldh * $newwidth) / $oldw;

        return $newh;
    }

    /*
      Crea una miniatura dell'immagine
     */

    public function creaThumb($newWidth, $newHeight) {
        $oldw = $this->getWidth();
        $oldh = $this->getHeight();

        $this->handlethumb = imagecreatetruecolor($newWidth, $newHeight);
        return imagecopyresampled($this->handlethumb, $this->handleimg, 0, 0, 0, 0, $newWidth, $newHeight, $oldw, $oldh);
    }

    /*
      Ritaglia un pezzo dell'immagine
     */

    public function cropThumb($width, $height, $x, $y) {
        $oldw = $this->getWidth();
        $oldh = $this->getHeight();

        $this->handlethumb = imagecreatetruecolor($width, $height);

        return imagecopy($this->handlethumb, $this->handleimg, 0, 0, $x, $y, $width, $height);
    }

    /*
      Salva su file la Thumbnail
     */

    public function saveThumb($path, $qualityJpg = 100) {
        if ($this->extension($this->original) == 'jpg' || $this->extension($this->original) == 'jpeg') {
            return imagejpeg($this->handlethumb, $path, $qualityJpg);
        } elseif ($this->extension($this->original) == 'png') {
            return imagepng($this->handlethumb, $path);
        } elseif ($this->extension($this->original) == 'gif') {
            return imagegif($this->handlethumb, $path);
        } elseif ($this->extension($this->original) == 'bmp') {
            return imagewbmp($this->handlethumb, $path);
        }
    }

    /*
      Stampa a video la Thumbnail
     */

    public function printThumb() {
        if ($this->extension($this->original) == 'jpg' || $this->xtension($this->original) == 'jpeg') {
            header("Content-Type: image/jpeg");
            imagejpeg($this->handlethumb);
        } elseif ($this->extension($this->original) == 'png') {
            header("Content-Type: image/png");
            imagepng($this->handlethumb);
        } elseif ($this->extension($this->original) == 'gif') {
            header("Content-Type: image/gif");
            imagegif($this->handlethumb);
        } elseif ($this->extension($this->original) == 'bmp') {
            header("Content-Type: image/bmp");
            imagewbmp($this->handlethumb);
        }
    }

    /*
      Distrugge le immagine per liberare le risorse
     */

    public function closeImg() {
        imagedestroy($this->handleimg);
        imagedestroy($this->handlethumb);
    }

    /*
      Imposta la thumbnail come immagine sorgente,
      in questo modo potremo combinare la funzione crea con la funzione crop
     */

    public function setThumbAsOriginal() {
        $this->oldoriginal = $this->handleimg;
        $this->handleimg = $this->handlethumb;
    }

    /*
      Resetta l'immagine originale
     */

    public function resetOriginal() {
        $this->handleimg = $this->oldoriginal;
    }

    /*
      Estrae l'estensione da un file o un percorso
     */

//		private function extension($percorso)
//		{
//			if(preg_match("[\|\\]", $percorso))
//			{
//				// da percorso
//				$nome = $this->nomefile($percorso);
//				
//				$spezzo = explode(".", $nome);
//				
//				return strtolower(trim(array_pop($spezzo)));
//			}
//			else
//			{
//				//da file
//				$spezzo = explode(".", $percorso);
//				
//				return strtolower(trim(array_pop($spezzo)));
//			}
//		}
    private function extension($percorso) {
        return strtolower(pathinfo($percorso, PATHINFO_EXTENSION));
    }

    /*
      Estrae il nome del file da un percorso
     */

    private function nomefile($path, $ext = true) {
        $diviso = spliti("[/|\\]", $path);

        if ($ext) {
            return trim(array_pop($diviso));
        } else {
            $nome = explode(".", trim(array_pop($diviso)));

            array_pop($nome);

            return trim(implode(".", $nome));
        }
    }
    
     public static function addTimelineImage($objUserImageData,$width, $height)
    {
          
    	$db                             = new Db();
    	$table                          = 'users';
    	$dataArray                      = array();
    	$msg                            = array();
    	try {
            if(isset($_FILES['file']))
            {
            $fileHandler                = new Filehandler();
            $emailLogoFileDetails       = $fileHandler->handleUpload($_FILES['file']);
            $image_id                   = $emailLogoFileDetails->file_id;
            $image                      = $emailLogoFileDetails->file_path;
            
            if(!file_exists(FILE_UPLOAD_DIR."timeline"))
               mkdir(FILE_UPLOAD_DIR."timeline", 0777);
            if($width >= 1140 || $height >= 258){
                Utils::allResize($image, 'timeline', '', 258);
            }
            else{
                Utils::allResize($image, 'timeline', $width, $height);
            }
        }
        else
        {
            $image_id                   = '';
            $image                      = '';
        }
            
            $msg['file']                    = $image;
            $data                           = array();
            $tableName                      = Utils::setTablePrefix('users');
            $where ='user_id ='. $objUserImageData->user_id;
            $data['user_timeline_image_id']          = $image_id;
            $data['user_timeline_image_name']          = $image;
            $timeline_image_id                     = $db->update($tableName,$data, $where);
        } 
        catch(Exception $e){
    		$msg['msg']             = $e->getMessage();
    		$msg['msgcls']          = 'error_div';
                $msg['image_id']          = $timeline_image_id;
    	}
        $msg['image_id']          = $timeline_image_id;
        return $msg;
    }
    
     public static function addOrgTimelineImage($objUserImageData,$width, $height)
    {

    	$db                             = new Db();
    	$table                          = 'users';
    	$dataArray                      = array();
    	$msg                            = array();
    	try {
            if(isset($_FILES['file']))
            {
            $fileHandler                = new Filehandler();
            $emailLogoFileDetails       = $fileHandler->handleUpload($_FILES['file']);
            $image_id                   = $emailLogoFileDetails->file_id;
            $image                      = $emailLogoFileDetails->file_path;
            //Utils::allResize($image, 'timeline', 1140, 258);
            if($width >= 1140 || $height >= 258){
                Utils::allResize($image, 'timeline', '', 258);
            }
            else{
                Utils::allResize($image, 'timeline', $width, $height);
            }
        }
        else
        {
            $image_id                   = '';
            $image                      = '';
        }
            $msg['file']                    = $image;
            $data                           = array();
            $tableName                      = Utils::setTablePrefix('businesses');
            $where ='business_id ='. $objUserImageData->business_id;
            $data['business_timeline_image_id']          = $image_id;
            $data['business_timeline_image_name']          = $image;
            $timeline_image_id                     = $db->update($tableName,$data, $where);
        }
        catch(Exception $e){
    		$msg['msg']             = $e->getMessage();
    		$msg['msgcls']          = 'error_div';
                $msg['image_id']          = $timeline_image_id;
    	}
        $msg['image_id']          = $timeline_image_id;
        return $msg;
    }

    /**
     * Uploads group background image to db
     *
     * @param object $imageObj
     * @param int $width
     * @param int $height
     *
     * @return array
     */
    public static function addGrpTimelineImage($imageObj, $width, $height)
    {
        // TODO : better error handling
        $resArr = array();

        try{
             if(isset($_FILES['file']))
            {
            $fileHandler = new Filehandler();
            $imageUploadDetails = $fileHandler->handleUpload($_FILES['file']);
            $imageId = $imageUploadDetails->file_id;
            $image = $imageUploadDetails->file_path;
            if ($width >= 1140 || $height >= 258) {
                Utils::allResize($image, 'timeline', '', 258);
                Utils::allResize($image, 'small', '', 134);
                Utils::allResize($image, 'medium', '', 164);
                Utils::allResize($image, 'thumb', '', 50);
            } else {
                Utils::allResize($image, 'timeline', $width, $height);
                Utils::allResize($image, 'small', '', 134);
                Utils::allResize($image, 'medium', '', 164);
                Utils::allResize($image, 'thumb', '', 50);
            }
            }
            else
            {
                $imageId = '';
            $image = '';
            }
            $db = new Db();
            $data = array();
            $tableName = Utils::setTablePrefix('communities');
            $where = 'community_id =' . $imageObj->group_id;
            $data['community_image_id'] = $imageId;
            $groupImageId = $db->update($tableName, $data, $where);
            $resArr['status'] = 'SUCCESS';
            $resArr['message'] = 'Uploaded successfully';
            $resArr['data'] = $image;
        } catch (Exception $e) {
            $resArr['status'] = 'ERROR';
            $resArr['message'] = $e->getMessage();
            $resArr['data'] = null;
        }
        return $resArr;
    }

    public function orgImageUpload($businessId){
        if ($_FILES['business_image_id']['name']) {
            $fileHandler = new Filehandler();   //  print_r($_FILES); exit;
            $bannerFileDetails = $fileHandler->handleUpload($_FILES['business_image_id'], FILE_UPLOAD_DIR);
        }
        if ($bannerFileDetails->file_id > 0) {
            $additionalParameters['business_image_id'] = $bannerFileDetails->file_id;
            Utils::allResize($bannerFileDetails->file_path, 'small', 190, 134);
            Utils::allResize($bannerFileDetails->file_path, 'medium', 256, 242);
            Utils::allResize($bannerFileDetails->file_path, 'thumb', 50, 50);
        }
        $resultingId = Business::updateOrganizationImage($businessId,$businessImageId);
    }

}

?>