<?php
/**
 * Profile photo upload — wires up the existing `users.avatar` column,
 * which exists in the schema but was never written to or read as an
 * actual image anywhere in the app (only used as a CSS class name for
 * the initials circle). This is the first real producer/consumer of it.
 */
session_start();
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'Not signed in.']);
    exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || empty($_FILES['avatar'])) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'No file received.']);
    exit;
}

include_once("config/db.php");

$uid  = (int)$_SESSION['user_id'];
$file = $_FILES['avatar'];

if ($file['error'] !== UPLOAD_ERR_OK) {
    echo json_encode(['ok' => false, 'error' => 'Upload failed. Please try again.']);
    exit;
}

// 4MB cap, image-only — validated by real MIME sniffing, not just the
// client-supplied extension/mimetype (which can't be trusted).
if ($file['size'] > 4 * 1024 * 1024) {
    echo json_encode(['ok' => false, 'error' => 'Image is too large (max 4MB).']);
    exit;
}

$finfo     = new finfo(FILEINFO_MIME_TYPE);
$mime      = $finfo->file($file['tmp_name']);
$ext_byMime = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp', 'image/gif' => 'gif'];

if (!isset($ext_byMime[$mime])) {
    echo json_encode(['ok' => false, 'error' => 'Please upload a JPG, PNG, WEBP, or GIF image.']);
    exit;
}

$dir = __DIR__ . '/uploads/avatars';
if (!is_dir($dir)) {
    mkdir($dir, 0755, true);
}

// Old avatar (if any) — remove it once the new one is safely saved, so we
// don't accumulate orphaned files every time someone changes their photo.
$old_stmt = $conn->prepare("SELECT avatar FROM users WHERE id=?");
$old_stmt->bind_param("i", $uid);
$old_stmt->execute();
$old_avatar = $old_stmt->get_result()->fetch_assoc()['avatar'] ?? null;

$filename = 'avatar_' . $uid . '_' . time() . '.' . $ext_byMime[$mime];
$dest     = $dir . '/' . $filename;

if (!move_uploaded_file($file['tmp_name'], $dest)) {
    echo json_encode(['ok' => false, 'error' => 'Could not save the image. Please try again.']);
    exit;
}

$upd = $conn->prepare("UPDATE users SET avatar=?, updated_at=NOW() WHERE id=?");
$upd->bind_param("si", $filename, $uid);

if (!$upd->execute()) {
    @unlink($dest);
    echo json_encode(['ok' => false, 'error' => 'Could not update your profile. Please try again.']);
    exit;
}

if ($old_avatar && $old_avatar !== $filename && file_exists($dir . '/' . $old_avatar)) {
    @unlink($dir . '/' . $old_avatar);
}

echo json_encode(['ok' => true, 'url' => 'uploads/avatars/' . $filename]);
