<?php

/*
 *  Vinnorokom Facebook Quiz App V.2.1.2
 *  by arirah@vinnorokom
 *  ----------------------------------
 *  Upload class files 
 *  @param files
 *  @param extensions
 *  @param saving path 
 * 
 *  @return filename
 * 
 */

class Upload extends Eloquent
{
    protected $image_max_size = 500000;

    public function uploadFile($file, $validextensions, $path)
    {
        $file_name = '';
        chmod($path, 0777); // Set CHMOD file permission 

        if (isset($file['type'])) {
            ///$validextensions = array("jpeg", "jpg", "png"); // Valid image file extention
            $temporary = explode('.', $file['name']);
            $file_extension = end($temporary);
            if ((($file['type'] == 'image/png') || ($file['type'] == 'image/jpg') || ($file['type'] == 'image/jpeg')
                    ) && ($file['size'] < $this->image_max_size)//Approx. 100kb files can be uploaded.
                    && in_array($file_extension, $validextensions)) {
                if ($file['error'] > 0) {
                    return false; // Return error code 
                } else {
                    if (file_exists($path.$file['name'])) {
                        $sourcePath = $file['tmp_name']; // Storing source path of the file in a variable
                        $file_name = '1_'.$file['name'];
                        $targetPath = $path.$file_name; // Change file name if already exist 
                        // move_uploaded_file($sourcePath, $targetPath); // Moving Uploaded file
                        //return $file_name; // Image Uploaded Successfully...
                    } else {
                        $sourcePath = $file['tmp_name'];
                        $file_name = $file['name'];
                        $targetPath = $path.$file_name; // Target path where file is to be stored
                        //move_uploaded_file($sourcePath, $targetPath);
                        //return $file['name'];
                    }

                    move_uploaded_file($sourcePath, $targetPath);

                    return $file_name;
                }
            } else {
                return false; // 'no-image.jpg';
            }
        }
    }
}
