<?php
header('Content-Type: application/json');
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/db.php';

$response = [
    'success' => false,
    'message' => '',
    'user' => null,
    'profile' => null,
    'experiences' => [],
    'educations' => []
];

$username = trim($_GET['username'] ?? '');

if (empty($username)) {
    $response['message'] = "Username is required.";
    echo json_encode($response);
    exit();
}

try {
    $stmt = $pdo->prepare("SELECT id, username, email, role, headline, location, about_summary, skills, profile_picture_url, banner_picture_url FROM users WHERE username = ?");
    $stmt->execute([$username]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        $response['message'] = "User not found.";
    } else {
        $response['user'] = $user;
        $user_id = $user['id'];
        $role = $user['role'];

        if ($role === 'speaker') {
            $stmt = $pdo->prepare("SELECT * FROM speaker_profiles WHERE user_id = ?");
            $stmt->execute([$user_id]);
            $response['profile'] = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
        } elseif ($role === 'organizer') {
            $stmt = $pdo->prepare("SELECT * FROM organizer_profiles WHERE user_id = ?");
            $stmt->execute([$user_id]);
            $response['profile'] = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
        } elseif ($role === 'sponsor') {
            $stmt = $pdo->prepare("SELECT * FROM sponsor_profiles WHERE user_id = ?");
            $stmt->execute([$user_id]);
            $response['profile'] = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
        }

        $stmt = $pdo->prepare("SELECT * FROM user_experiences WHERE user_id = ? ORDER BY start_date DESC");
        $stmt->execute([$user_id]);
        $response['experiences'] = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

        $stmt = $pdo->prepare("SELECT * FROM user_educations WHERE user_id = ? ORDER BY start_date DESC");
        $stmt->execute([$user_id]);
        $response['educations'] = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

        $response['success'] = true;
    }
} catch (PDOException $e) {
    $response['message'] = "Database error: " . $e->getMessage();
}

echo json_encode($response);
