<?php
/**
 * Get User Profile - Refresh User Data
 * Returns updated user information including PRO status
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

require_once 'config.php';

// Only allow POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode([
        'success' => false,
        'message' => 'Method not allowed'
    ]);
    exit;
}

try {
    // Get JSON input
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($input['user_id'])) {
        throw new Exception('User ID is required');
    }
    
    $userId = (int)$input['user_id'];
    
    // Get database connection
    $pdo = getDBConnection();
    
    // Get user data with PRO status
    $stmt = $pdo->prepare("
        SELECT 
            u.id,
            u.email,
            u.user_name,
            u.full_name,
            u.user_level,
            u.is_pro,
            u.pro_expires_at,
            u.is_verified,
            u.profile_picture,
            u.created_at,
            u.updated_at
        FROM users u
        WHERE u.id = ? AND u.is_deleted = 0
    ");
    
    $stmt->execute([$userId]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$user) {
        throw new Exception('User not found');
    }
    
    // Format the response
    $response = [
        'id' => (int)$user['id'],
        'email' => $user['email'],
        'user_name' => $user['user_name'],
        'full_name' => $user['full_name'],
        'user_level' => $user['user_level'],
        'is_pro' => (bool)$user['is_pro'],
        'pro_expires_at' => $user['pro_expires_at'],
        'is_verified' => (bool)$user['is_verified'],
        'profile_picture' => $user['profile_picture'],
        'created_at' => $user['created_at'],
        'updated_at' => $user['updated_at'],
    ];
    
    echo json_encode([
        'success' => true,
        'message' => 'User profile retrieved successfully',
        'data' => $response
    ]);
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
