<?php
include '../includes/auth.php';
include '../includes/db.php';

header('Content-Type: application/json');

// Check if required parameters are provided
if (!isset($_GET['judge_id']) && !isset($_GET['username'])) {
    echo json_encode([
        'success' => false,
        'message' => 'Judge ID or username required'
    ]);
    exit;
}

try {
    // Build query based on available parameters
    if (isset($_GET['judge_id']) && is_numeric($_GET['judge_id'])) {
        // Search by judge user ID
        $judge_id = intval($_GET['judge_id']);
        $stmt = $pdo->prepare("
            SELECT u.id, u.username, u.password, u.judge_id, u.created_at,
                   COUNT(ja.event_id) as event_count
            FROM users u
            LEFT JOIN judge_assignments ja ON u.id = ja.judge_id
            WHERE u.id = ? AND u.role = 'judge'
            GROUP BY u.id, u.username, u.password, u.judge_id, u.created_at
        ");
        $stmt->execute([$judge_id]);
    } else {
        // Search by username
        $username = $_GET['username'];
        $stmt = $pdo->prepare("
            SELECT u.id, u.username, u.password, u.judge_id, u.created_at,
                   COUNT(ja.event_id) as event_count
            FROM users u
            LEFT JOIN judge_assignments ja ON u.id = ja.judge_id
            WHERE u.username = ? AND u.role = 'judge'
            GROUP BY u.id, u.username, u.password, u.judge_id, u.created_at
        ");
        $stmt->execute([$username]);
    }
    
    $judge = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($judge) {
        echo json_encode([
            'success' => true,
            'judge' => $judge
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Judge not found'
        ]);
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
