<?php
session_start();
require '../includes/db.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

$user_id = $_SESSION['user_id'];

if (!isset($_FILES['avatar'])) {
    echo json_encode(['status' => 'error', 'message' => 'No file uploaded']);
    exit;
}

$file = $_FILES['avatar'];

// VALIDATION
$allowed = ['image/jpeg', 'image/png', 'image/webp'];

if (!in_array($file['type'], $allowed)) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid file type']);
    exit;
}

if ($file['size'] > 2 * 1024 * 1024) {
    echo json_encode(['status' => 'error', 'message' => 'File too large']);
    exit;
}

// SAFE NAME
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$newName = "user_" . $user_id . "_" . time() . "." . $ext;

$path = "../assets/images/avatar/" . $newName;

// MOVE FILE
if (move_uploaded_file($file['tmp_name'], $path)) {

    // GET OLD AVATAR
    $stmt = $pdo->prepare("SELECT avatar FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $old = $stmt->fetchColumn();

    // DELETE OLD FILE
    if ($old && file_exists("../assets/images/avatar/" . $old)) {
        unlink("../assets/images/avatar/" . $old);
    }

    // UPDATE DB
    $stmt = $pdo->prepare("UPDATE users SET avatar = ? WHERE id = ?");
    $stmt->execute([$newName, $user_id]);

    echo json_encode([
        'status' => 'success',
        'path' => "assets/images/avatar/" . $newName
    ]);

} else {
    echo json_encode(['status' => 'error', 'message' => 'Upload failed']);
}
?>