<?php

/*
 * Handles all uploads
 */

class Upload {

    public function __construct() {
        
    }

    private static function generateRandomString($length = 5) {
        // Function to generate a random string of 5 chars.
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; // Chars to use
        $charactersLength = strlen($characters); // Check string length
        $randomString = ''; // An empty var to store our randomstring
        for ($i = 0; $i < $length; $i++) {
            // Here we loop until we filled our string with the wanted length.
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString; // Returns our randomstring.
    }

    public static function handleUpload($file = false) {
        $filename = $file['name']; // Get filename
        $size = $file['size']; // Gets filesize
        $tempname = $file['tmp_name']; // Where did php upload our data to?
        $type = $file['type']; // Unused in current state.
        $ext = explode('.', $file['name']); // end() doesnt like us using explode directly.
        $extension = strtolower(end($ext)); // Get the extension of the file.
        $randomname = Upload::generateRandomString(); // We give our file a random name - It will be this.

        $cwd = getcwd(); // Our websites CWD (Current working dir)
        $uploadPath = $cwd .'/'. Config::$file_path . $randomname . '.' . $extension;

        if (!in_array($extension, Config::$file_types)) {
            // Error! This file does not have an acceptable filetype
            return false; // Return false when upload fails.
        }

        if ($size > Config::$file_size) {
            // Filesize is configured in config, defined in bytes.
            return false; // Return false when upload fails.
        }

        if (empty($errors)) {
            // Do fileupload
            // move_uploaded_file is self-explanatory. We move the file into the correct path.
            $makeUpload = move_uploaded_file($tempname, $uploadPath);

            if (!$makeUpload) {
                return false; // Return false when upload fails.
            } else {
                // Return where the image was uploaded to.
                return Config::$sys_url.Config::$file_path.$randomname.'.'.$extension;
            }
        }
    }

}
