<?php
class UploadPicture {


    private $db;

    public function __construct() {
        $this->db = DBConnectorFactory::loadDriver();
    }


    /**
     * Generic function to get an uploaded $_FILE[name_of_file] and save it to a specific path 
     * @param [[Type]] $FileName The name of the input[file] tag that is assigned in the client-side
     * @param [[Type]] $SavePath Destination path
     */
    public function SaveUploadedPhoto($FileName,$SavePath){
        if(!isset($_FILES[$FileName]))return false;
        $SaveToPath = substr($SavePath,0,strrpos($SavePath,"/")+1);
        $SaveAsFile = substr($SavePath,strrpos($SavePath,"/")+1);
        $SaveAsExtention = explode(".",$SaveAsFile);
        $SaveAsExtention = strtolower($SaveAsExtention[count($SaveAsExtention)-1]);
        $SaveAsFile = substr($SaveAsFile,0,strrpos($SaveAsFile,"."));
        $fileType = explode(".",basename($_FILES[$FileName]['name']));
        $fileType = strtolower($fileType[count($fileType)-1]);
        $DestinationFile = $SaveToPath.$SaveAsFile.".";
        unlink($DestinationFile.$fileType);
        move_uploaded_file($_FILES[$FileName]['tmp_name'],$DestinationFile.$fileType);
        if($fileType == "png" && $SaveAsExtention == "jpg"){
            unlink($DestinationFile."jpg");
            $image = imagecreatefrompng($DestinationFile.$fileType);
            imagejpeg($image, $DestinationFile.$SaveAsExtention, 100);
            imagedestroy($image);
            unlink($DestinationFile.$fileType);
        }
        return file_exists($DestinationFile.$SaveAsExtention);
    }
}


