<?php
// ============================================================
//  admin/email-upload-image.php
// ============================================================
//
//  TinyMCE-compatible image upload endpoint. The editor POSTs
//  a single image file as multipart/form-data; we store it
//  under /uploads/email-images/{year-month}/ and return the URL.
//
//  Security:
//   - Admin auth required
//   - File MUST be one of: jpg/jpeg/png/gif/webp
//   - Max 10MB per upload (large images bloat emails)
//   - Filename randomised (we don't trust user input)
//   - Stored outside the executable PHP path
//
//  Response shape (TinyMCE expects this exact format):
//   200 OK: { "location": "https://…/uploads/email-images/2026-05/abc.png" }
//   4xx:    { "error": { "message": "…" } }
// ============================================================

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/config.php';
auth_require_admin();

header('Content-Type: application/json; charset=utf-8');
header('X-Content-Type-Options: nosniff');

function eii_error(int $code, string $msg): void {
    http_response_code($code);
    echo json_encode(['error' => ['message' => $msg]]);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    eii_error(405, 'POST required');
}

if (!isset($_FILES['file']) || !is_uploaded_file($_FILES['file']['tmp_name'] ?? '')) {
    eii_error(400, 'No file uploaded');
}

$file = $_FILES['file'];

if ($file['error'] !== UPLOAD_ERR_OK) {
    eii_error(400, 'Upload failed (error code ' . $file['error'] . ')');
}

// Size limit: 10 MB per image
$max_size = 10 * 1024 * 1024;
if ($file['size'] > $max_size) {
    eii_error(413, 'Image too large — 10 MB maximum');
}

// Validate MIME type using finfo (not the client-supplied $file['type'])
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime  = $finfo->file($file['tmp_name']);
$allowed = [
    'image/jpeg' => 'jpg',
    'image/png'  => 'png',
    'image/gif'  => 'gif',
    'image/webp' => 'webp',
];
if (!isset($allowed[$mime])) {
    eii_error(415, 'Only JPEG, PNG, GIF, WebP images allowed');
}
$ext = $allowed[$mime];

// Compute storage path under DOCROOT
$year_month  = date('Y-m');
$install_root = realpath(__DIR__ . '/..');
$base_dir    = $install_root . '/uploads/email-images/' . $year_month;
if (!is_dir($base_dir)) {
    if (!@mkdir($base_dir, 0755, true) && !is_dir($base_dir)) {
        eii_error(500, 'Could not create upload directory');
    }
}

// Random filename: timestamp-randomhex.ext
$filename = sprintf('%s-%s.%s', date('YmdHis'), bin2hex(random_bytes(6)), $ext);
$dest     = $base_dir . '/' . $filename;

if (!@move_uploaded_file($file['tmp_name'], $dest)) {
    eii_error(500, 'Could not save uploaded file');
}
@chmod($dest, 0644);

// Build the absolute URL — required for emails, since they're read off-site
$url = rtrim(SITE_URL, '/') . '/uploads/email-images/' . $year_month . '/' . $filename;

echo json_encode(['location' => $url]);