<?php
require_once '../../includes/functions.php';
setCORSHeaders();

// Enable comprehensive logging
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);

// Log API call
logApiCall('user/profile.php');

// Verify API Hash
try {
    verifyAPIHash();
    error_log("✅ API Hash verification passed for profile endpoint");
} catch (Exception $e) {
    logError("API Hash verification failed", ['endpoint' => 'user/profile.php', 'error' => $e->getMessage()]);
    sendError('Invalid API hash', 401);
}

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    logError("Invalid request method", ['method' => $_SERVER['REQUEST_METHOD'], 'endpoint' => 'user/profile.php']);
    sendError('Method not allowed', 405);
}

// Get authorization header
$headers = getallheaders();
$authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
error_log("Authorization Header: " . $authHeader);

if (empty($authHeader) || !preg_match('/Bearer\s+(.*)$/i', $authHeader, $matches)) {
    logError("Missing or invalid authorization header", ['header' => $authHeader, 'endpoint' => 'user/profile.php']);
    sendError('Authorization token required', 401);
}

$token = $matches[1];
error_log("Extracted Token: " . substr($token, 0, 20) . "...");

try {
    $payload = verifyJWT($token);
    if (!$payload || !isset($payload['user_id'])) {
        logError("Invalid JWT token", ['token_preview' => substr($token, 0, 20), 'endpoint' => 'user/profile.php']);
        sendError('Invalid or expired token', 401);
    }
    error_log("✅ JWT token verified successfully for user profile");
    error_log("User ID: " . $payload['user_id']);
} catch (Exception $e) {
    logError("JWT verification error", ['error' => $e->getMessage(), 'endpoint' => 'user/profile.php']);
    sendError('Token verification failed', 401);
}

$userId = $payload['user_id'];

// Get user profile
try {
    $user = getUserById($userId);
    if (!$user) {
        logError("User not found", ['user_id' => $userId, 'endpoint' => 'user/profile.php']);
        sendError('User not found', 404);
    }
    error_log("✅ User profile retrieved successfully for user ID: $userId");
} catch (Exception $e) {
    logError("Error retrieving user profile", ['user_id' => $userId, 'error' => $e->getMessage(), 'endpoint' => 'user/profile.php']);
    sendError('Database error while retrieving user profile', 500);
}

// Get user orders
$stmt = $pdo->prepare("
    SELECT o.id, o.quantity, o.total_coins, o.status, o.created_at,
           p.name as product_name, p.price_coins as product_price
    FROM orders o
    JOIN products p ON o.product_id = p.id
    WHERE o.user_id = ?
    ORDER BY o.created_at DESC
    LIMIT 10
");
$stmt->execute([$userId]);
$orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get recent transactions
$stmt = $pdo->prepare("
    SELECT type, amount, coin_type, description, created_at
    FROM transactions
    WHERE user_id = ?
    ORDER BY created_at DESC
    LIMIT 10
");
$stmt->execute([$userId]);
$transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);

sendResponse([
    'success' => true,
    'data' => [
        'profile' => $user,
        'recent_orders' => $orders,
        'recent_transactions' => $transactions
    ]
]);
?>
