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

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

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

// 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']);
        $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 = ?
            WHERE event_id = ? AND judge_id = ?
        ");
        
        $update_stmt->execute([
            $status,
            $timestamp,
            $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,
                '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,
                    j.first_name,
                    j.last_name,
                    j.role
                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,
                    j.first_name,
                    j.last_name,
                    j.role
                FROM judge_assignments ja
                JOIN judges j ON ja.judge_id = j.id
                WHERE ja.event_id = ?
                ORDER BY j.last_name, j.first_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()
    ]);
}
