<?php

require "../protected/src/config.php";

// Set the Content-Type header to indicate that the response is in JSON format
header('Content-Type: application/json');

// Allow credentials (if needed)
header('Access-Control-Allow-Credentials: true');

// Optionally, set additional headers (e.g., CORS headers), Set the allowed origin
if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN'] == SITE_URL) {
    header('Access-Control-Allow-Origin: ' . SITE_URL);
}
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// Set the maximum file size to 10MB (in bytes)
$maxFileSize = 10 * 1024 * 1024; // 10MB

// Define valid image types
$validImageTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];

// Check if the file is uploaded successfully
if (isset($_FILES['upload']) && $_FILES['upload']['error'] === UPLOAD_ERR_OK) {
    $uploadDir = ARTICLE_IMAGE_PATH . "/"; // Set your upload directory
    $tempFile = $_FILES['upload']['tmp_name'];
    
    // Check file size
    if ($_FILES['upload']['size'] >= $maxFileSize) {
        echo json_encode(['error' => 'Uploaded file too big! Limit of 10MB']);
        unlink($tempFile);
        exit;
    }
    
    // Check file type
    if (! in_array($_FILES['upload']['type'], $validImageTypes)) {
        echo json_encode(['error' => 'Uploaded file not allowed image type (JPG, PNG, GIF)!']);
        unlink($tempFile);
        exit;
    }
    
    // Check if the temporary file contains PHP tags
    $fileContent = file_get_contents($tempFile);
    if (strpos($fileContent, '<?php') !== false) {
        // PHP tags detected, do not move the file and send an error response
        echo json_encode(['error' => 'Danger: Uploaded file contains PHP start tags!']);
        unlink($tempFile);
        exit;
    } 
    
    // No PHP tags detected, move the uploaded file to the specified directory
    if (UPLOAD_RND_FILE_NAMES) {
        // Generate a unique filename to prevent overwriting
        $fn = basename(uniqid('image_') . '.' . pathinfo($_FILES['upload']['name'], PATHINFO_EXTENSION));
        $uploadedFile = $uploadDir . $fn; 
    } else {
        $fn = basename($_FILES['upload']['name']);
        $uploadedFile = $uploadDir . $fn;
        if (file_exists($uploadedFile)) {
            echo json_encode(['error' => 'Failed to uploaded file: Filename already exists!']);
            exit;
        }        
    }

    if (move_uploaded_file($tempFile, $uploadedFile)) {
        // File moved successfully, send the file URL
        $fileUrl = SITE_URL . '/image.php?image=' . $fn;
        echo json_encode(['url' => $fileUrl]);
    } else {
        // Failed to move the uploaded file, send an error response
        echo json_encode(['error' => 'Failed to move the uploaded file.']);
    }
    
} else {
    // File upload failed, send an error response
    echo json_encode(['error' => 'File upload failed.']);
}
