<?php

class Upload
{

    private $_destination = null,
        $_errors = array(),
        $_validation,
        $_uploadedFiles,
        $_multiple,
        $_prefix,
        $_suffix,
        $_name = array();


    public function __construct($destination, $validation = array(), $uploadedFiles = array(), $multiple = false)
    {
        if (!is_dir($destination) || !is_writable($destination)) {

            $this->setError("Directory Not Available or Not Writable");
            return false;


        } else if (empty($validation)) {
            $this->setError("Validation Not Supplied");
            return false;
        } else {

            $this->_multiple = $multiple;
            $this->_destination = $destination;
            $this->_validation = $validation;
            $this->_uploadedFiles = $uploadedFiles;

            return;

        }

    }

    private function getType($string)
    {

        $ext = pathinfo($string, PATHINFO_EXTENSION);
        return strtolower($ext);


    }


    public function setPrefix($string = "")
    {

        $this->_prefix = $string;

    }

    public function setSuffix($string = "")
    {

        $this->_suffix = $string;

    }


    public function upload()
    {

        if (!empty($this->_errors)) {
            return false;
        } else if (!$this->_multiple) {

            $this->singleCheck();
        } else if ($this->_multiple) {
            $this->multiCheck();

        }



        return;
    }


    private function getRandomName()
    {

        return date("Y-m-d_H_i_s") . "_" . rand(1, 10000);

    }


    private function validate($validation = array(), $file)
    {
        foreach ($validation as $key => $value) {

            switch ($key) {
                case "type":


                    if (!in_array($this->getType(strtolower($file["name"])), explode(",", $value[0]))) {
                        $this->setError("Please Upload File In Valid Format");
                        return false;


                    }
                break;

                case("size"):
                {
                    if(number_format($_FILES["banners"]["size"][0]/(1024*1024),2)>$value)
                    {
                        $this->setError("Please Upload File Size Less Than {$value} MB");
                        return false;

                    }

                }
                    break;



            }


        }

        return true;

    }


    private function checkUploaded($file)
    {
        if (!is_uploaded_file($file)) {
            return false;
        }
        return true;
    }


    private function singleCheck()
    {

        if (!$this->checkUploaded($this->_uploadedFiles["tmp_name"])) {

            $this->setError("Please Upload File");
            return false;

        } else if (count($this->_validation) && !$this->validate($this->_validation, $this->_uploadedFiles)) {

            return false;

        }


        $filename = $this->_prefix . $this->getRandomName() . $this->_suffix . "." . $this->getType($this->_uploadedFiles["name"]);


        if (!move_uploaded_file($this->_uploadedFiles["tmp_name"], $this->_destination . $filename)) {
            $this->setError("Cant Move File,Please Try Again Later");
            return false;
        }
        else {


            $this->setImagename($filename);


            return true;


        }

    }


    private function multiCheck()
    {

        if (!$this->checkUploaded($this->_uploadedFiles["tmp_name"][0])) {
            $this->setError("Please Upload File");
            return false;
        }


        $rearrangedFiles = $this->rearrange_files($this->_uploadedFiles);



        for ($i = 0; $i < count($rearrangedFiles); $i++) {



            if (!$this->validate($this->_validation, $rearrangedFiles[$i])) {

                return false;

            }


            else {

                $filename = $this->_prefix . $this->getRandomName() . $this->_suffix . "." . $this->getType($rearrangedFiles[$i]["name"]);


                if (!move_uploaded_file($rearrangedFiles[$i]["tmp_name"], $this->_destination . $filename)) {
                    $this->setError("Cant Move File,Please Try Again Later");
                    return false;
                }

                else {

                    $this->setImagename($filename);



                }
            }



        }

        return;

    }


    private function setError($error)
    {
        $this->_errors[] = $error;
    }


    public function passed()
    {

        if (!count($this->_errors)) {
            return true;
        }
        return false;

    }


    public function displayErrors()

    {
        if (count($this->_errors)) {
            return $this->_errors;
        }
        return false;
    }


    public function getName()
    {
        if (count($this->_name)) {
            return $this->_name;

        }
        return false;

    }


    private function setImagename($filename)
    {
        $this->_name[]=$filename;
    }


    private function rearrange_files($files)
    {
        $result = array();
        foreach ($files as $key1 => $value1)
            foreach ($value1 as $key2 => $value2)
                $result[$key2][$key1] = $value2;
        return $result;


    }




    public function saveThumbs($width,$height,$destination="")
    {
        if(!count($this->_name))
        {
            $this->setError("Please Upload File");
            return false;
        }
        if($destination=="")
        {
            $destination=$this->_destination;
        }

        foreach($this->_name as $image) {

            $resizer = new ImageResizer();
        $resizer->load($this->_destination.$image);
            $resizer->resize($width,$height);
            $resizer->save($destination."thumb_".$image);



        }




    }


}



class ImageResizer {

    var $image;
    var $image_type;

    function load($filename) {

        $image_info = getimagesize($filename);
        $this->image_type = $image_info[2];
        if( $this->image_type == IMAGETYPE_JPEG ) {

            $this->image = imagecreatefromjpeg($filename);
        } elseif( $this->image_type == IMAGETYPE_GIF ) {

            $this->image = imagecreatefromgif($filename);
        } elseif( $this->image_type == IMAGETYPE_PNG ) {

            $this->image = imagecreatefrompng($filename);
        }
    }
    function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) {

        if( $image_type == IMAGETYPE_JPEG ) {
            imagejpeg($this->image,$filename,$compression);
        } elseif( $image_type == IMAGETYPE_GIF ) {

            imagegif($this->image,$filename);
        } elseif( $image_type == IMAGETYPE_PNG ) {

            imagepng($this->image,$filename);
        }
        if( $permissions != null) {

            chmod($filename,$permissions);
        }
    }
    function output($image_type=IMAGETYPE_JPEG) {

        if( $image_type == IMAGETYPE_JPEG ) {
            imagejpeg($this->image);
        } elseif( $image_type == IMAGETYPE_GIF ) {

            imagegif($this->image);
        } elseif( $image_type == IMAGETYPE_PNG ) {

            imagepng($this->image);
        }
    }
    function getWidth() {

        return imagesx($this->image);
    }
    function getHeight() {

        return imagesy($this->image);
    }
    function resizeToHeight($height) {

        $ratio = $height / $this->getHeight();
        $width = $this->getWidth() * $ratio;
        $this->resize($width,$height);
    }

    function resizeToWidth($width) {
        $ratio = $width / $this->getWidth();
        $height = $this->getheight() * $ratio;
        $this->resize($width,$height);
    }

    function scale($scale) {
        $width = $this->getWidth() * $scale/100;
        $height = $this->getheight() * $scale/100;
        $this->resize($width,$height);
    }

    function resize($width,$height) {
        $new_image = imagecreatetruecolor($width, $height);
        imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
        $this->image = $new_image;
    }

}
?>

