<?php
/**
 * Judge Status API
 * Handles judge status updates and retrieval
 */

require_once '../includes/db.php';

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

// Simple session check without redirect
session_start();

// For POST requests, verify user is authenticated
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_SESSION['judge_id']) && !isset($_SESSION['user_id'])) {
        echo json_encode([
            'success' => false,
            'error' => 'Authentication required. Please log in.'
        ]);
        exit;
    }
}

// Get request method
$method = $_SERVER['REQUEST_METHOD'];

try {
    if ($method === 'POST') {
        // Update judge status
        $input = json_decode(file_get_contents('php://input'), true);
        
        if (!isset($input['event_id']) || !isset($input['judge_id']) || !isset($input['status'])) {
            echo json_encode([
                'success' => false,
                'error' => 'Missing required fields: event_id, judge_id, status'
            ]);
            exit;
        }
        
        $event_id = intval($input['event_id']);
        $judge_id = intval($input['judge_id']);
        $status = trim($input['status']);
        $heat_number = isset($input['heat_number']) ? intval($input['heat_number']) : null;
        $run_number = isset($input['run_number']) ? intval($input['run_number']) : null;
        $timestamp = $input['timestamp'] ?? date('Y-m-d H:i:s');
        
        // Validate status
        $valid_statuses = ['ready', 'pending', 'danger', 'warning', 'info', 'off'];
        if (!in_array($status, $valid_statuses)) {
            echo json_encode([
                'success' => false,
                'error' => 'Invalid status. Must be one of: ' . implode(', ', $valid_statuses)
            ]);
            exit;
        }
        
        // Check if judge assignment exists
        $check_stmt = $pdo->prepare("
            SELECT id FROM judge_assignments 
            WHERE event_id = ? AND judge_id = ?
        ");
        $check_stmt->execute([$event_id, $judge_id]);
        $assignment = $check_stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$assignment) {
            echo json_encode([
                'success' => false,
                'error' => 'Judge assignment not found for this event'
            ]);
            exit;
        }
        
        // Update judge status
        $update_stmt = $pdo->prepare("
            UPDATE judge_assignments 
            SET status = ?, 
                status_updated_at = ?,
                heat_number = ?,
                run_number = ?
            WHERE event_id = ? AND judge_id = ?
        ");
        
        $update_stmt->execute([
            $status,
            $timestamp,
            $heat_number,
            $run_number,
            $event_id,
            $judge_id
        ]);
        
        echo json_encode([
            'success' => true,
            'message' => 'Judge status updated successfully',
            'data' => [
                'event_id' => $event_id,
                'judge_id' => $judge_id,
                'status' => $status,
                'heat_number' => $heat_number,
                'run_number' => $run_number,
                'timestamp' => $timestamp
            ]
        ]);
        
    } elseif ($method === 'GET') {
        // Get judge status(es)
        
        if (isset($_GET['event_id']) && isset($_GET['judge_id'])) {
            // Get specific judge status
            $event_id = intval($_GET['event_id']);
            $judge_id = intval($_GET['judge_id']);
            
            $stmt = $pdo->prepare("
                SELECT 
                    ja.id,
                    ja.event_id,
                    ja.judge_id,
                    ja.status,
                    ja.status_updated_at,
                    ja.heat_number,
                    ja.run_number,
                    j.name as judge_name,
                    j.is_head
                FROM judge_assignments ja
                JOIN judges j ON ja.judge_id = j.id
                WHERE ja.event_id = ? AND ja.judge_id = ?
            ");
            $stmt->execute([$event_id, $judge_id]);
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($result) {
                echo json_encode([
                    'success' => true,
                    'data' => $result
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'error' => 'Judge assignment not found'
                ]);
            }
            
        } elseif (isset($_GET['event_id'])) {
            // Get all judge statuses for an event
            $event_id = intval($_GET['event_id']);
            
            $stmt = $pdo->prepare("
                SELECT 
                    ja.id,
                    ja.event_id,
                    ja.judge_id,
                    ja.status,
                    ja.status_updated_at,
                    ja.heat_number,
                    ja.run_number,
                    j.name as judge_name,
                    j.is_head
                FROM judge_assignments ja
                JOIN judges j ON ja.judge_id = j.id
                WHERE ja.event_id = ?
                ORDER BY j.name
            ");
            $stmt->execute([$event_id]);
            $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            echo json_encode([
                'success' => true,
                'count' => count($results),
                'data' => $results
            ]);
            
        } else {
            echo json_encode([
                'success' => false,
                'error' => 'Missing required parameter: event_id'
            ]);
        }
        
    } else {
        echo json_encode([
            'success' => false,
            'error' => 'Method not allowed. Use GET or POST'
        ]);
    }
    
} catch (PDOException $e) {
    echo json_encode([
        'success' => false,
        'error' => 'Database error: ' . $e->getMessage()
    ]);
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
