<?php

$oResponse = new \stdClass();
$oResponse->success = false;
$oResponse->errors = array();
$oResponse->base64 = '';

/**
 * Check for valid HTTP request method
 */
if($_SERVER['REQUEST_METHOD'] !== 'POST') {
    array_push($oResponse->errors, 'invalid-method');
    http_response_code(405);
    echo json_encode($oResponse);
    exit;
}

/**
 * Check for valid FILES array
 */
if(empty($_FILES)) {
    array_push($oResponse->errors, 'empty-uploads');
    http_response_code(400);
    echo json_encode($oResponse);
    exit;
}

/**
 * Check for valid uploaded `file`
 */
if(!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
    array_push($oResponse->errors, 'no-uploaded-file');
    http_response_code(400);
    echo json_encode($oResponse);
    exit;
}

/**
 * Retrieve & store file
 */
$oFile = $_FILES['file'];

$fileTmpPath = $oFile['tmp_name'];
$fileName = $oFile['name'];

$maxFileSize = 5 * 1024 * 1024; // 5 MB in bytes

/**
 * Check for valid file size
 */
if($oFile['size'] > $maxFileSize) {
    array_push($oResponse->errors, 'file-size-exceeded');
    echo json_encode($oResponse);
    exit;
}

require_once __DIR__ . '/../classes/class.ajax.php';
$oAjax = new Ajax();

/**
 * Retrieve & store file data
 */
$fileData = file_get_contents($fileTmpPath);

/**
 * Base64 encode file
 */
$base64EncodedFile = base64_encode($fileData);

/**
 * Pass base64 to response object
 */
$oResponse->base64 = $base64EncodedFile;

$oResponse->success = true;

$oAjax->setSuccessHeaders();
echo json_encode($oResponse);
exit;