<?php
require_once 'config.php';

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

function respond($success, $message, $extra = [])
{
    echo json_encode(array_merge([
        'success' => $success,
        'message' => $message
    ], $extra));
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    respond(false, 'Invalid request method');
}

$token = trim($_POST['token'] ?? '');
if ($token === '') {
    respond(false, 'Token required');
}

if (!isset($_FILES['profile_image']) || !is_array($_FILES['profile_image'])) {
    respond(false, 'No file uploaded');
}

$file = $_FILES['profile_image'];

if ($file['error'] !== UPLOAD_ERR_OK) {
    respond(false, 'Upload error');
}

$maxSize = 5 * 1024 * 1024;
if ($file['size'] > $maxSize) {
    respond(false, 'File too large (max 5MB)');
}

$tmpPath = $file['tmp_name'];
if (!is_uploaded_file($tmpPath)) {
    respond(false, 'Invalid upload');
}

$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = $finfo ? finfo_file($finfo, $tmpPath) : '';
if ($finfo) {
    finfo_close($finfo);
}

$mimeToExt = [
    'image/jpeg' => 'jpg',
    'image/png' => 'png',
    'image/gif' => 'gif',
    'image/webp' => 'webp'
];

if (!isset($mimeToExt[$mimeType])) {
    respond(false, 'Invalid file type. Allowed: jpg, png, gif, webp');
}

$uploadDir = __DIR__ . '/uploads/profile/';
if (!is_dir($uploadDir) && !mkdir($uploadDir, 0755, true)) {
    respond(false, 'Failed to create upload directory');
}

if (!is_writable($uploadDir)) {
    respond(false, 'Upload directory is not writable');
}

$ext = $mimeToExt[$mimeType];
$newName = 'profile_' . bin2hex(random_bytes(8)) . '.' . $ext;
$targetPath = $uploadDir . $newName;

if (!move_uploaded_file($tmpPath, $targetPath)) {
    respond(false, 'Failed to save file');
}

$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$scriptDir = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/');
$imageUrl = $protocol . '://' . $_SERVER['HTTP_HOST'] . $scriptDir . '/uploads/profile/' . $newName;

$sql = "UPDATE users SET profile_pic = ? WHERE token = ? LIMIT 1";
$stmt = $conn->prepare($sql);

if (!$stmt) {
    @unlink($targetPath);
    respond(false, 'Database prepare failed');
}

$stmt->bind_param('ss', $imageUrl, $token);

if (!$stmt->execute()) {
    $stmt->close();
    @unlink($targetPath);
    respond(false, 'Database update failed: ' . $stmt->error);
}

if ($stmt->affected_rows < 1) {
    $stmt->close();
    @unlink($targetPath);
    respond(false, 'Invalid token or user not found');
}

$stmt->close();
$conn->close();

respond(true, 'Profile picture updated', [
    'image_url' => $imageUrl
]);
?>