<?php
/**
 * upload-photo.php — POST multipart/form-data, field name "photo"
 * Saves into assets/img/gallery/ with a safe, unique filename.
 * Requires login.
 */
require_once __DIR__ . '/auth.php';
header('Content-Type: application/json');

if (empty($_FILES['photo']) || $_FILES['photo']['error'] !== UPLOAD_ERR_OK) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'No valid file uploaded']);
    exit;
}

$file = $_FILES['photo'];

// Validate size (max 8MB)
if ($file['size'] > 8 * 1024 * 1024) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'File too large (max 8MB)']);
    exit;
}

// Validate real image type (don't trust the extension or MIME header alone)
$info = @getimagesize($file['tmp_name']);
$allowed = [
    IMAGETYPE_JPEG => 'jpg',
    IMAGETYPE_PNG  => 'png',
    IMAGETYPE_WEBP => 'webp',
];
if ($info === false || !isset($allowed[$info[2]])) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'File is not a valid JPG, PNG, or WEBP image']);
    exit;
}
$ext = $allowed[$info[2]];

if (!is_dir(UPLOAD_DIR)) mkdir(UPLOAD_DIR, 0755, true);

$safeName = 'upload-' . date('Ymd-His') . '-' . bin2hex(random_bytes(4)) . '.' . $ext;
$destPath = UPLOAD_DIR . $safeName;

if (!move_uploaded_file($file['tmp_name'], $destPath)) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'Failed to save file']);
    exit;
}

echo json_encode(['ok' => true, 'url' => UPLOAD_URL_PATH . $safeName]);
