<?php
// ini_set('display_errors', 1);
// error_reporting(E_ALL);
require_once __DIR__ . '/include/S3Helper.php';

$message = "";

$url = 'upload_images/' . time() . "_" . basename($_FILES['upload']['name']);

/* ========= IMAGE VALIDATION (ADDED) ========= */
function isValidImage($tmpPath) {
    if (!file_exists($tmpPath)) return false;

    $allowedMime = ['image/jpeg', 'image/png', 'image/webp'];

    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime  = finfo_file($finfo, $tmpPath);
    finfo_close($finfo);

    if (!in_array($mime, $allowedMime)) return false;
    if (getimagesize($tmpPath) === false) return false;

    // Block embedded scripts
    $head = file_get_contents($tmpPath, false, null, 0, 512);
    if (preg_match('/<\?php|<script|<html|<!DOCTYPE/i', $head)) return false;

    return true;
}
/* =========================================== */

if (empty($_FILES['upload']['name'])) {
    $message = "No file uploaded.";
}
else if ($_FILES['upload']['size'] == 0) {
    $message = "The file is of zero length.";
}
else if (!is_uploaded_file($_FILES['upload']['tmp_name'])) {
    $message = "Invalid upload attempt.";
}
else if (!isValidImage($_FILES['upload']['tmp_name'])) {
    $message = "Only JPG, PNG or WEBP images are allowed.";
}
else {
    
    $s3 = new S3Helper();

    $filename = time() . '_' . basename($_FILES['upload']['name']);
    $tmpPath  = $_FILES['upload']['tmp_name'];
     $s3Url = $s3->upload(
        $tmpPath,
        'upload_images/',
        $filename
    );

    if (!$s3Url) {
        $message = "Error moving uploaded file. Check permissions.";
    } else {
        $url = $s3Url; 
    }
    // if (!move_uploaded_file($_FILES['upload']['tmp_name'], $url)) {
    //     $message = "Error moving uploaded file. Check permissions.";
    // }
    // $url = "http://admin.quicklly.com/" . $url;
}

$funcNum = $_GET['CKEditorFuncNum'];
echo "<script type='text/javascript'>
window.parent.CKEDITOR.tools.callFunction($funcNum, '$url', '$message');
</script>";
?>
