<?php
require_once '../../config/db.php';
require_once '../../core/Auth.php';

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

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

try {
    $user_id = Auth::check();
    
    if (!isset($_FILES['avatar'])) {
        throw new Exception("No file uploaded");
    }

    $file = $_FILES['avatar'];
    
    // Validation
    $allowed_types = ['image/jpeg', 'image/png', 'image/webp'];
    if (!in_array($file['type'], $allowed_types)) {
        throw new Exception("Invalid file type. Only JPG, PNG, WEBP allowed.");
    }
    
    if ($file['size'] > 5 * 1024 * 1024) { // 5MB
        throw new Exception("File too large. Max 5MB.");
    }

    // Prepare path
    $upload_dir = '../../uploads/avatars/';
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }
    
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = 'user_' . $user_id . '_' . time() . '.' . $ext;
    $target_path = $upload_dir . $filename;
    
    if (move_uploaded_file($file['tmp_name'], $target_path)) {
        // Construct public URL
        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
        $host = $_SERVER['HTTP_HOST'];
        // Ajustar la ruta base según la estructura del servidor del usuario
        // Detectar si estamos en carpeta 'KLKAPP TEST' o raíz
        $script_dir = dirname($_SERVER['SCRIPT_NAME']); // /Juuvix_Shop/KLKAPP TEST/server/api/upload
        $base_url = str_replace('/server/api/upload', '', $script_dir); // /Juuvix_Shop/KLKAPP TEST
        
        $public_url = "$protocol://$host$base_url/server/uploads/avatars/" . $filename;
        
        // Update DB
        global $pdo; // Ensure $pdo is available
        $stmt = $pdo->prepare("UPDATE users SET avatar = ? WHERE id = ?");
        $stmt->execute([$public_url, $user_id]);
        
        echo json_encode([
            'success' => true, // Frontend expects this
            'status' => 'success',
            'message' => 'Avatar updated',
            'url' => $public_url
        ]);
        
    } else {
        throw new Exception("Failed to save file.");
    }

} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['error' => $e->getMessage()]);
}
?>
