<?php
// Set the content type to JSON so our JavaScript understands the response
header('Content-Type: application/json');

// 1. SECURELY GET THE API KEY
// Get the path to our secure keys.ini file, which is outside the public folder
$configPath = '/home/vnejapguxa/keys.ini';
$imgbbApiKey = '';

if (file_exists($configPath)) {
    $config = parse_ini_file($configPath, true);
    $imgbbApiKey = $config['imgbb']['apiKey'];
}

// If the API key is missing, stop and return an error
if (empty($imgbbApiKey)) {
    echo json_encode(['success' => false, 'error' => ['message' => 'Server configuration error: API key not found.']]);
    exit();
}

// 2. PREPARE THE UPLOAD
// The image data is sent from admin.js as 'image'
$imageData = $_POST['image'];

// Set up the request to the ImgBB API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.imgbb.com/1/upload?key=' . $imgbbApiKey);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ['image' => $imageData]);

// 3. EXECUTE THE UPLOAD AND RETURN THE RESULT
// Execute the cURL request
$result = curl_exec($ch);
// Check for cURL errors
if (curl_errno($ch)) {
    echo json_encode(['success' => false, 'error' => ['message' => 'cURL Error: ' . curl_error($ch)]]);
} else {
    // If successful, just pass ImgBB's response directly back to our admin.js
    echo $result;
}

// Close the cURL connection
curl_close($ch);
?>