<?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,
    'site_name' => 'EventPortal',
    'logo_url' => '',
    'data' => []
];

try {
    $stmt_c = $pdo->query("SELECT key, value FROM system_settings");
    $configs = $stmt_c->fetchAll(PDO::FETCH_KEY_PAIR) ?: [];
    $response['site_name'] = $configs['site_name'] ?? 'EventPortal';
    $response['logo_url'] = $configs['site_logo'] ?? '';

    $type = $_GET['type'] ?? 'team';

    if ($type === 'team') {
        $stmt = $pdo->query("
            SELECT u.username, u.email, u.employee_code, u.profile_picture_url, d.title as designation_title 
            FROM users u 
            LEFT JOIN designations d ON u.designation_id = d.id 
            WHERE u.role = 'user' 
            ORDER BY d.id ASC, u.id ASC
        ");
        $response['data'] = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        $response['success'] = true;
    } elseif ($type === 'speakers') {
        $stmt = $pdo->query("
            SELECT sp.*, u.profile_picture_url 
            FROM speaker_profiles sp 
            LEFT JOIN users u ON sp.user_id = u.id 
            ORDER BY sp.id DESC
        ");
        $response['data'] = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        $response['success'] = true;
    } elseif ($type === 'organizers') {
        $stmt = $pdo->query("
            SELECT op.*, u.profile_picture_url 
            FROM organizer_profiles op 
            LEFT JOIN users u ON op.user_id = u.id 
            ORDER BY op.id DESC
        ");
        $response['data'] = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        $response['success'] = true;
    } elseif ($type === 'sponsors') {
        $stmt = $pdo->query("
            SELECT sp.*, u.profile_picture_url 
            FROM sponsor_profiles sp 
            LEFT JOIN users u ON sp.user_id = u.id 
            ORDER BY sp.id DESC
        ");
        $response['data'] = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        $response['success'] = true;
    } else {
        $response['message'] = "Invalid directory type.";
    }
} catch (PDOException $e) {
    $response['message'] = "Database error: " . $e->getMessage();
}

echo json_encode($response);
