<?php
require_once __DIR__ . '/../../config/cors.php';
require_once __DIR__ . '/../../config/jwt.php';

$user = auth_required();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405); echo json_encode(['error' => 'Method not allowed']); exit;
}

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

$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime  = finfo_file($finfo, $_FILES['photo']['tmp_name']);
finfo_close($finfo);
$allowed = ['image/jpeg', 'image/png'];
if (!in_array($mime, $allowed)) {
    http_response_code(400); echo json_encode(['error' => 'Only JPG/PNG allowed']); exit;
}

$ext  = $mime === 'image/png' ? 'png' : 'jpg';
$name = 'photo_' . $user['id'] . '_' . time() . ".$ext";
$dest = UPLOAD_DIR . $name;

if (!is_dir(UPLOAD_DIR)) mkdir(UPLOAD_DIR, 0755, true);
move_uploaded_file($_FILES['photo']['tmp_name'], $dest);

echo json_encode(['success' => true, 'path' => $name, 'url' => UPLOAD_URL . $name]);
