<?php
session_start();
header('Content-Type: application/json');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode([
        'success' => false,
        'message' => 'User not logged in'
    ]);
    exit;
}

$host = 'localhost';
$db = 'zemaraim_interior';
$user = 'zemaraim';
$password = '8wwxk]-X3Kx]CJ]5';

try {
    $connection = new mysqli($host, $user, $password, $db);
    
    if ($connection->connect_error) {
        throw new Exception('Database connection failed');
    }

    $user_id = $_SESSION['user_id'];
    
    // Fetch user data including avatar
    $stmt = $connection->prepare("SELECT id, name, email, avatar FROM users WHERE id = ?");
    
    if (!$stmt) {
        throw new Exception('Statement preparation failed');
    }
    
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $user_data = $result->fetch_assoc();
    
    $stmt->close();
    $connection->close();

    if ($user_data) {
        // Prepare avatar URL
        $avatar_url = '';
        if (!empty($user_data['avatar'])) {
            // If avatar is stored as URL or path
            if (filter_var($user_data['avatar'], FILTER_VALIDATE_URL)) {
                $avatar_url = $user_data['avatar'];
            } else {
                // If it's a relative path, prepend the base URL
                $avatar_url = 'uploads/avatars/' . $user_data['avatar'];
            }
        }

        echo json_encode([
            'success' => true,
            'user' => [
                'id' => $user_data['id'],
                'name' => $user_data['name'],
                'email' => $user_data['email'],
                'avatar' => $avatar_url
            ]
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'User not found'
        ]);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
