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

$message = '';
$assigned_judge_names = [];

$selected_event_id = $_GET['event_id'] ?? null;
$selected_control_point_id = $_GET['control_point_id'] ?? null;

// Handle control point creation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_control_point'])) {
    $event_id = $_POST['event_id'];
    $control_point_name = trim($_POST['control_point_name']);
    $description = trim($_POST['description'] ?? '');
    
    try {
        // Get next sort order
        $sort_stmt = $pdo->prepare("SELECT COALESCE(MAX(sort_order), 0) + 1 FROM event_control_points WHERE event_id = ?");
        $sort_stmt->execute([$event_id]);
        $sort_order = $sort_stmt->fetchColumn();
        
        $stmt = $pdo->prepare("INSERT INTO event_control_points (event_id, control_point_name, description, sort_order, status, weight) VALUES (?, ?, ?, ?, 1, 1.0)");
        $stmt->execute([$event_id, $control_point_name, $description, $sort_order]);
        
        header("Location: judge_assign.php?event_id=" . $event_id . "&msg=control_point_created");
        exit;
    } catch (Exception $e) {
        $message = '<div class="alert alert-danger">Error creating control point: ' . htmlspecialchars($e->getMessage()) . '</div>';
    }
}

// Handle control point editing
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_control_point'])) {
    $event_id = $_POST['event_id'];
    $control_point_id = $_POST['control_point_id'];
    $control_point_name = trim($_POST['control_point_name']);
    $description = trim($_POST['description'] ?? '');
    $status = (int)$_POST['status'];
    $weight = (float)$_POST['weight'];
    
    try {
        // Validate weight range
        if ($weight < 0 || $weight > 2) {
            throw new Exception("Weight must be between 0 and 2");
        }
        
        // Verify control point belongs to this event
        $verify_stmt = $pdo->prepare("SELECT id FROM event_control_points WHERE id = ? AND event_id = ?");
        $verify_stmt->execute([$control_point_id, $event_id]);
        if (!$verify_stmt->fetchColumn()) {
            throw new Exception("Invalid control point or access denied");
        }
        
        $stmt = $pdo->prepare("UPDATE event_control_points SET control_point_name = ?, description = ?, status = ?, weight = ? WHERE id = ? AND event_id = ?");
        $stmt->execute([$control_point_name, $description, $status, $weight, $control_point_id, $event_id]);
        
        header("Location: judge_assign.php?event_id=" . $event_id . "&msg=control_point_updated");
        exit;
    } catch (Exception $e) {
        $message = '<div class="alert alert-danger">Error updating control point: ' . htmlspecialchars($e->getMessage()) . '</div>';
    }
}

// Handle control point deletion
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_control_point'])) {
    $event_id = $_POST['event_id'];
    $control_point_id = $_POST['control_point_id'];
    
    try {
        // Verify control point belongs to this event
        $verify_stmt = $pdo->prepare("SELECT id FROM event_control_points WHERE id = ? AND event_id = ?");
        $verify_stmt->execute([$control_point_id, $event_id]);
        if (!$verify_stmt->fetchColumn()) {
            throw new Exception("Invalid control point or access denied");
        }
        
        // Check if control point has judge assignments
        $judge_check = $pdo->prepare("SELECT COUNT(*) FROM judge_assignments WHERE control_point_id = ?");
        $judge_check->execute([$control_point_id]);
        $judge_count = $judge_check->fetchColumn();
        
        if ($judge_count > 0) {
            throw new Exception("Cannot delete control point with assigned judges. Please unassign judges first.");
        }
        
        $stmt = $pdo->prepare("DELETE FROM event_control_points WHERE id = ? AND event_id = ?");
        $stmt->execute([$control_point_id, $event_id]);
        
        header("Location: judge_assign.php?event_id=" . $event_id . "&msg=control_point_deleted");
        exit;
    } catch (Exception $e) {
        $message = '<div class="alert alert-danger">Error deleting control point: ' . htmlspecialchars($e->getMessage()) . '</div>';
    }
}

// Handle judge assignment save
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['judge_ids']) && isset($_POST['event_id'])) {
    $event_id = $_POST['event_id'];
    $control_point_id = $_POST['control_point_id'] ?? null;
    $judge_ids = $_POST['judge_ids'];

    // Convert empty string to NULL for general judging
    if ($control_point_id === '' || $control_point_id === '0') {
        $control_point_id = null;
    }

    try {
        // Validate control_point_id if provided (not NULL)
        if ($control_point_id !== null) {
            $cp_check = $pdo->prepare("SELECT id FROM event_control_points WHERE id = ? AND event_id = ?");
            $cp_check->execute([$control_point_id, $event_id]);
            if (!$cp_check->fetchColumn()) {
                throw new Exception("Invalid control point selected. Please refresh the page and try again.");
            }
        }

        // Check for existing assignments to other control points
        $conflicts = [];
        if (!empty($judge_ids)) {
            $in = implode(',', array_fill(0, count($judge_ids), '?'));
            $params = array_merge([$event_id], $judge_ids);
            
            if ($control_point_id !== null) {
                $conflict_sql = "
                    SELECT ja.judge_id, u.username, 
                           CASE 
                               WHEN ja.control_point_id IS NULL THEN 'General Judging'
                               ELSE ecp.control_point_name
                           END as control_point_name
                    FROM judge_assignments ja
                    JOIN users u ON ja.judge_id = u.id
                    LEFT JOIN event_control_points ecp ON ja.control_point_id = ecp.id
                    WHERE ja.event_id = ? AND ja.judge_id IN ($in) AND (ja.control_point_id != ? OR ja.control_point_id IS NULL)
                ";
                $params[] = $control_point_id;
            } else {
                $conflict_sql = "
                    SELECT ja.judge_id, u.username, 
                           CASE 
                               WHEN ja.control_point_id IS NULL THEN 'General Judging'
                               ELSE ecp.control_point_name
                           END as control_point_name
                    FROM judge_assignments ja
                    JOIN users u ON ja.judge_id = u.id
                    LEFT JOIN event_control_points ecp ON ja.control_point_id = ecp.id
                    WHERE ja.event_id = ? AND ja.judge_id IN ($in) AND ja.control_point_id IS NOT NULL
                ";
            }
            
            $conflict_stmt = $pdo->prepare($conflict_sql);
            $conflict_stmt->execute($params);
            $conflicts = $conflict_stmt->fetchAll(PDO::FETCH_ASSOC);
        }

        // If conflicts exist and no force flag, show warning
        if (!empty($conflicts) && !isset($_POST['force_assign'])) {
            $conflict_list = [];
            foreach ($conflicts as $conflict) {
                $conflict_list[] = $conflict['username'] . ' (assigned to ' . $conflict['control_point_name'] . ')';
            }
            
            $message = '<div class="alert alert-warning">
                <i class="bi bi-exclamation-triangle-fill me-2"></i>
                <strong>Warning: Some judges are already assigned to other control points:</strong>
                <ul class="mb-2">' . implode('', array_map(fn($item) => '<li>' . $item . '</li>', $conflict_list)) . '</ul>
                <form method="post" class="d-inline">
                    ' . implode('', array_map(fn($id) => '<input type="hidden" name="judge_ids[]" value="' . $id . '">', $judge_ids)) . '
                    <input type="hidden" name="event_id" value="' . $event_id . '">
                    <input type="hidden" name="control_point_id" value="' . ($control_point_id ?? '') . '">
                    <input type="hidden" name="force_assign" value="1">
                    <button type="submit" class="btn btn-warning btn-sm me-2">
                        <i class="bi bi-check-circle me-1"></i>Assign Anyway (Multi-assignment)
                    </button>
                </form>
                <button type="button" class="btn btn-secondary btn-sm" onclick="this.closest(\'.alert\').remove()">Cancel</button>
            </div>';
        } else {
            // Remove existing assignments for this event/control point combination
            if ($control_point_id !== null) {
                $pdo->prepare("DELETE FROM judge_assignments WHERE event_id = ? AND control_point_id = ?")->execute([$event_id, $control_point_id]);
            } else {
                $pdo->prepare("DELETE FROM judge_assignments WHERE event_id = ? AND control_point_id IS NULL")->execute([$event_id]);
            }

            // Validate judge IDs exist
            if (!empty($judge_ids)) {
                $judge_in = implode(',', array_fill(0, count($judge_ids), '?'));
                $judge_check = $pdo->prepare("SELECT id FROM users WHERE id IN ($judge_in)");
                $judge_check->execute($judge_ids);
                $valid_judges = $judge_check->fetchAll(PDO::FETCH_COLUMN);
                
                if (count($valid_judges) !== count($judge_ids)) {
                    throw new Exception("Some selected judges are invalid. Please refresh the page and try again.");
                }

                // Re-insert assignments with proper NULL handling
                $insert = $pdo->prepare("INSERT INTO judge_assignments (event_id, judge_id, control_point_id) VALUES (?, ?, ?)");
                foreach ($judge_ids as $jid) {
                    $insert->execute([$event_id, $jid, $control_point_id]);
                }
            }

            $control_point_name = 'General Judging';
            if ($control_point_id !== null) {
                $cp_stmt = $pdo->prepare("SELECT control_point_name FROM event_control_points WHERE id = ?");
                $cp_stmt->execute([$control_point_id]);
                $control_point_name = $cp_stmt->fetchColumn() ?: 'Unknown Control Point';
            }

            $redirect_url = "judge_assign.php?event_id=" . $event_id;
            if ($control_point_id !== null) {
                $redirect_url .= "&control_point_id=" . $control_point_id;
            }
            $redirect_url .= "&msg=success";
            
            header("Location: " . $redirect_url);
            exit;
        }
    } catch (Exception $e) {
        $message = '<div class="alert alert-danger">Error assigning judges: ' . htmlspecialchars($e->getMessage()) . '</div>';
    }
}


// Handle unassign action
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['unassign_judge_id'])) {
    $event_id = $_POST['event_id'];
    $judge_id = $_POST['unassign_judge_id'];
    $control_point_id = $_POST['control_point_id'] ?? null;
    
    // Convert empty string to NULL
    if ($control_point_id === '' || $control_point_id === '0') {
        $control_point_id = null;
    }
    
    try {
        if ($control_point_id !== null) {
            $stmt = $pdo->prepare("DELETE FROM judge_assignments WHERE event_id = ? AND judge_id = ? AND control_point_id = ?");
            $stmt->execute([$event_id, $judge_id, $control_point_id]);
        } else {
            $stmt = $pdo->prepare("DELETE FROM judge_assignments WHERE event_id = ? AND judge_id = ? AND control_point_id IS NULL");
            $stmt->execute([$event_id, $judge_id]);
        }
        
        $redirect_url = "judge_assign.php?event_id=" . $event_id;
        if ($control_point_id !== null) {
            $redirect_url .= "&control_point_id=" . $control_point_id;
        }
        $redirect_url .= "&msg=unassigned";
        
        header("Location: " . $redirect_url);
        exit;
    } catch (Exception $e) {
        $message = '<div class="alert alert-danger">Error unassigning judge: ' . htmlspecialchars($e->getMessage()) . '</div>';
    }
}

// Handle success messages
if (isset($_GET['msg'])) {
    switch ($_GET['msg']) {
        case 'success':
            $message = '<div class="alert alert-success alert alert-dismissible fade show">
                <i class="bi bi-check-circle-fill me-2"></i>
                Judges assigned successfully!
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>';
            break;
        case 'unassigned':
            $message = '<div class="alert alert-warning alert alert-dismissible fade show">
                <i class="bi bi-person-dash me-2"></i>
                Judge unassigned successfully!
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>';
            break;
        case 'control_point_created':
            $message = '<div class="alert alert-success alert alert-dismissible fade show">
                <i class="bi bi-geo-alt-fill me-2"></i>
                Control point created successfully!
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>';
            break;
        case 'control_point_updated':
            $message = '<div class="alert alert-success alert alert-dismissible fade show">
                <i class="bi bi-pencil-square me-2"></i>
                Control point updated successfully!
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>';
            break;
        case 'control_point_deleted':
            $message = '<div class="alert alert-warning alert alert-dismissible fade show">
                <i class="bi bi-trash me-2"></i>
                Control point deleted successfully!
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>';
            break;
    }
}

// Load events and judges
$events = $pdo->query("SELECT * FROM events ORDER BY date DESC")->fetchAll(PDO::FETCH_ASSOC);
$judges = $pdo->query("SELECT id, username, judge_id as is_head FROM users ORDER BY username")->fetchAll(PDO::FETCH_ASSOC);

// Load control points for selected event
$control_points = [];
if ($selected_event_id) {
    $stmt = $pdo->prepare("SELECT id, control_point_name, description, sort_order, status, weight FROM event_control_points WHERE event_id = ? ORDER BY sort_order, control_point_name");
    $stmt->execute([$selected_event_id]);
    $control_points = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Load currently assigned judges
$assigned_judges = [];
$assigned_judges_details = [];
if ($selected_event_id) {
    if ($selected_control_point_id) {
        $stmt = $pdo->prepare("SELECT judge_id FROM judge_assignments WHERE event_id = ? AND control_point_id = ?");
        $stmt->execute([$selected_event_id, $selected_control_point_id]);
    } else {
        $stmt = $pdo->prepare("SELECT judge_id FROM judge_assignments WHERE event_id = ? AND control_point_id IS NULL");
        $stmt->execute([$selected_event_id]);
    }
    $assigned_judges = array_column($stmt->fetchAll(PDO::FETCH_ASSOC), 'judge_id');
    
    // Get assigned judges details
    if (!empty($assigned_judges)) {
        $in = implode(',', array_fill(0, count($assigned_judges), '?'));
        $stmt = $pdo->prepare("SELECT id, username, judge_id as is_head FROM users WHERE id IN ($in) ORDER BY username");
        $stmt->execute($assigned_judges);
        $assigned_judges_details = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}
// Load judge assignments for ALL control points to show conflicts
$judge_assignments_map = [];
if ($selected_event_id) {
    $stmt = $pdo->prepare("
        SELECT ja.judge_id, 
               CASE 
                   WHEN ja.control_point_id IS NULL THEN 'General Judging'
                   ELSE ecp.control_point_name
               END as control_point_name,
               ja.control_point_id
        FROM judge_assignments ja
        LEFT JOIN event_control_points ecp ON ja.control_point_id = ecp.id
        WHERE ja.event_id = ?
        ORDER BY ecp.sort_order, control_point_name
    ");
    $stmt->execute([$selected_event_id]);
    $all_judge_assignments = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Group by judge_id for easy lookup
    foreach ($all_judge_assignments as $assignment) {
        if (!isset($judge_assignments_map[$assignment['judge_id']])) {
            $judge_assignments_map[$assignment['judge_id']] = [];
        }
        $judge_assignments_map[$assignment['judge_id']][] = $assignment;
    }
}
// Load ALL assignments for table view
$all_assignments = [];
if ($selected_event_id) {
    $stmt = $pdo->prepare("
        SELECT ja.judge_id, ja.control_point_id, u.username, u.judge_id as is_head,
               CASE 
                   WHEN ja.control_point_id IS NULL THEN 'General Judging'
                   ELSE ecp.control_point_name
               END as control_point_name,
               COALESCE(ecp.sort_order, 0) as sort_order
        FROM judge_assignments ja
        JOIN users u ON ja.judge_id = u.id
        LEFT JOIN event_control_points ecp ON ja.control_point_id = ecp.id
        WHERE ja.event_id = ?
        ORDER BY sort_order, control_point_name, u.username
    ");
    $stmt->execute([$selected_event_id]);
    $all_assignments = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Organize assignments by control point
$assignments_by_cp = [];
foreach ($all_assignments as $assignment) {
    $cp_key = $assignment['control_point_id'] ?? 'general';
    if (!isset($assignments_by_cp[$cp_key])) {
        $assignments_by_cp[$cp_key] = [
            'name' => $assignment['control_point_name'],
            'sort_order' => $assignment['sort_order'],
            'judges' => []
        ];
    }
    $assignments_by_cp[$cp_key]['judges'][] = $assignment;
}

// Get control point name for display
$current_control_point_name = 'General Judging';
if ($selected_control_point_id) {
    $cp_stmt = $pdo->prepare("SELECT control_point_name FROM event_control_points WHERE id = ?");
    $cp_stmt->execute([$selected_control_point_id]);
    $current_control_point_name = $cp_stmt->fetchColumn() ?: 'Unknown Control Point';
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Assign Judges to Event</title>
   <?php include_once '../includes/stylesheets.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>

    <style>
        .card-hover:hover {
            transform: translateY(-2px);
            transition: transform 0.2s ease-in-out;
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15) !important;
        }
        .cursor-pointer {
            cursor: pointer;
        }
        .table tbody tr {
            transition: background-color 0.2s ease-in-out;
        }
        .table tbody tr:hover {
            background-color: rgba(0, 123, 255, 0.05) !important;
        }
        .judge-checkbox:checked + label {
            font-weight: bold;
        }
    </style>
</head>
<body class="body-bg-aurora-bright">
    <?php include '../menu.php'; ?>
    
    <div class="container-fluid container-StyleScore p-4">
        <div class="row justify-content-center">

                <!-- event action menu. -->
<div class="row mb-3">
    <div class="col-12">
        <?php       
        $use_localStorage = true;
        $show_header = false;
        //$show_public_view = false;
        include 'event_actions_menu.php'; 
        ?>
        <div class="d-flex justify-content-end mt-2">
            <button type="button" class="btn btn-outline-info btn-sm" onclick="openJudgeAssignHelp()">
                <i class="bi bi-question-circle me-1"></i> Help
            </button>
        </div>
    </div>
</div>
            <div class="col-md-12">
                
                <!-- Page Header -->
                <div class="border-0 shadow-none card border-0 shadow-sm mb-3 card-hover">
                    <div class="border-0 shadow-none card-body py-2 bg-primary text-white text-center">
                        <h5 class="mb-0 fw-bold">
                            <i class="bi bi-person-check-fill me-1"></i>
                            Assign Judges to Event Control Points
                        </h5>
                    </div>
                </div>

                <?php if (!empty($message)) echo $message; ?>

                <!-- Step 1: Select Event -->
                <div class="border-0 shadow-none card border-0 shadow-sm mb-3 card-hover">
                    <div class="border-0 shadow-none card-body py-2">
                        <div class="d-flex align-items-center mb-2">
                            <h6 class="mb-0 fw-bold text-primary">
                                <i class="bi bi-calendar-event me-1"></i>
                                Step 1: Select Event
                            </h6>
                        </div>
                        <form method="get" class="load-event-selection">
                            <select class="form-select form-select-sm" name="event_id" onchange="this.form.submit()" required>
                                <option value="">-- Select Event --</option>
                                <?php foreach ($events as $e): ?>
                                    <option value="<?= $e['id'] ?>" <?= $selected_event_id == $e['id'] ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($e['name']) ?> (<?= date('M d, Y', strtotime($e['date'])) ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </form>
                    </div>
                </div>

                <!-- Step 2 & 3: Control Points and Judge Assignment in columns (only show if event is selected) -->
                <?php if ($selected_event_id): ?>
                    <div class="row">
                        <!-- Left Column: Control Points & Assignment -->
                        <div class="col-md-6">
                            <!-- Control Points -->
                            <div class="border-0 shadow-none card border-0 shadow-sm mb-3 card-hover">
                                <div class="border-0 shadow-none card-body py-2">
                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                        <h6 class="mb-0 fw-bold text-info">
                                            <i class="bi bi-geo-alt me-1"></i>
                                            Step 2: Select Control Point
                                        </h6>
                                        <button class="btn btn-info btn-sm" data-bs-toggle="modal" data-bs-target="#createControlPointModal">
                                            <i class="bi bi-plus-circle me-1"></i>Add
                                        </button>
                                    </div>
                                <div class="border-0 shadow-none card-content">
                                    <!-- General Judging (no specific control point) -->
                                    <div class="border-0 shadow-none card border p-3 mb-3 cursor-pointer <?= !$selected_control_point_id ? 'border-success bg-success-subtle bg-opacity-20 text-success border-1 shadow-sm' : 'border-warning bg-warning bg-opacity-10' ?>" 
                                         onclick="selectControlPoint(null)">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <div>
                                                <h6 class="mb-1 <?= !$selected_control_point_id ? 'fw-bold' : '' ?>">
                                                    <i class="bi bi-star-fill me-1"></i>
                                                    General Judging
                                                    <?= !$selected_control_point_id ? '<i class="bi bi-check-circle-fill ms-2 text-success"></i>' : '' ?>
                                                </h6>
                                                <small class="<?= !$selected_control_point_id ? 'text-success' : 'text-muted' ?>">Overall event judging</small>
                                            </div>
                                            <span class="badge bg-<?= !$selected_control_point_id ? 'success' : 'warning' ?>">
                                                <?= !$selected_control_point_id ? 'SELECTED' : 'Default' ?>
                                            </span>
                                        </div>
                                    </div>

                                    <!-- Specific Control Points -->
                                    <?php foreach ($control_points as $cp): ?>
                                        <div class="border-0 shadow-none card border p-3 mb-3 cursor-pointer <?= $selected_control_point_id == $cp['id'] ? 'border-primary bg-primary-subtle bg-opacity-20 text-primary border-1 shadow-sm' : 'border-secondary bg-light' ?>" 
                                             onclick="selectControlPoint(<?= $cp['id'] ?>)">
                                            <div class="d-flex justify-content-between align-items-start">
                                                <div class="flex-grow-1">
                                                    <h6 class="mb-1 <?= $selected_control_point_id == $cp['id'] ? 'fw-bold' : '' ?>">
                                                        <i class="bi bi-geo-alt-fill me-1"></i>
                                                        <?= htmlspecialchars($cp['control_point_name']) ?>
                                                        <?= $selected_control_point_id == $cp['id'] ? '<i class="bi bi-check-circle-fill ms-2 text-primary"></i>' : '' ?>
                                                        <?php if ($cp['status'] == 0): ?>
                                                            <span class="badge bg-secondary ms-2">Inactive</span>
                                                        <?php endif; ?>
                                                    </h6>
                                                    <?php if ($cp['description']): ?>
                                                        <small class="text-muted d-block mb-1"><?= htmlspecialchars($cp['description']) ?></small>
                                                    <?php endif; ?>
                                                    <div class="small">
                                                        <?php if ($selected_control_point_id == $cp['id']): ?>
                                                            <span class="badge bg-primary me-1 fw-bold">SELECTED</span>
                                                        <?php endif; ?>
                                                        <span class="badge bg-secondary me-1">Order: <?= $cp['sort_order'] ?></span>
                                                        <span class="badge bg-info">Weight: <?= number_format($cp['weight'], 1) ?></span>
                                                    </div>
                                                </div>
                                                <div class="d-flex flex-column gap-1">
                                                    <?php if ($selected_control_point_id == $cp['id']): ?>
                                                        <div class="text-center mb-1">
                                                            <i class="bi bi-arrow-right-circle-fill text-primary fs-5"></i>
                                                        </div>
                                                    <?php endif; ?>
                                                    <button type="button" class="btn btn-sm <?= $selected_control_point_id == $cp['id'] ? 'btn-primary' : 'btn-outline-primary' ?>" 
                                                            onclick="event.stopPropagation(); editControlPoint(<?= $cp['id'] ?>, '<?= htmlspecialchars($cp['control_point_name'], ENT_QUOTES) ?>', '<?= htmlspecialchars($cp['description'], ENT_QUOTES) ?>', <?= $cp['status'] ?>, <?= $cp['weight'] ?>)"
                                                            title="Edit Control Point">
                                                        <i class="bi bi-pencil"></i>
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>

                                    <?php if (empty($control_points)): ?>
                                        <div class="alert alert-info mt-3">
                                            <i class="bi bi-info-circle me-2"></i>
                                            No control points defined for this event. You can assign judges to general judging or create specific control points.
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Judge Assignment -->
                            <div class="border-0 shadow-none card border-0 shadow-sm mb-3 card-hover">
                                <div class="border-0 shadow-none card-body py-2">
                                    <h6 class="mb-2 fw-bold text-success">
                                        <i class="bi bi-people me-1"></i>
                                        Step 3: Assign Judges
                                    </h6>
                                    <div class="alert py-2 mb-2 <?= $selected_control_point_id ? 'alert-info border-info' : 'alert-warning border-warning' ?>">
                                        <small>
                                            <strong>Event:</strong> <?= htmlspecialchars($events[array_search($selected_event_id, array_column($events, 'id'))]['name']) ?><br>
                                            <strong>Control Point:</strong> 
                                            <span class="badge bg-<?= $selected_control_point_id ? 'primary' : 'success' ?> small fw-bold">
                                                <i class="bi bi-<?= $selected_control_point_id ? 'geo-alt-fill' : 'star-fill' ?> me-1"></i>
                                                <?= htmlspecialchars($current_control_point_name) ?>
                                                <i class="bi bi-check-circle-fill ms-1"></i>
                                            </span>
                                            </span>
                                        </small>
                                    </div>
                                    
                                    <form method="post" id="assignForm">
                                        <input type="hidden" name="event_id" value="<?= $selected_event_id ?>">
                                        <input type="hidden" name="control_point_id" value="<?= $selected_control_point_id ?>">
                                        
                                        <h6 class="fw-bold mb-3">Available Judges (<?= count($judges) ?>):</h6>
                                        
                                        <?php if (empty($judges)): ?>
                                            <div class="alert alert-info">
                                                <i class="bi bi-info-circle me-2"></i>
                                                No judges available. <a href="judge_add.php">Add judges first</a>.
                                            </div>
                                        <?php else: ?>
                                            <div class="table-responsive">
                                                <table class="table table-bordered table-hover">
                                                    <thead class="table-dark">
                                                        <tr>
                                                            <th style="width: 50px;" class="text-center">
                                                                <input type="checkbox" id="selectAll" class="form-check-input" 
                                                                       onchange="toggleAllJudgesTable(this)">
                                                            </th>
                                                            <th>Judge Name</th>
                                                            <th style="width: 120px;" class="text-center">Role</th>
                                                            <th style="width: 150px;" class="text-center">Current Assignment</th>
                                                            <th style="width: 80px;" class="text-center">Judge ID</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php foreach ($judges as $j): ?>
                                                            <?php
                                                            // Check if this judge is assigned to any control points
                                                            $judge_other_assignments = [];
                                                            if (isset($judge_assignments_map[$j['id']])) {
                                                                foreach ($judge_assignments_map[$j['id']] as $assignment) {
                                                                    // Skip current control point
                                                                    if (($selected_control_point_id && $assignment['control_point_id'] == $selected_control_point_id) || 
                                                                        (!$selected_control_point_id && $assignment['control_point_id'] === null)) {
                                                                        continue;
                                                                    }
                                                                    $judge_other_assignments[] = $assignment['control_point_name'];
                                                                }
                                                            }
                                                            
                                                            $is_assigned_here = in_array($j['id'], $assigned_judges);
                                                            $has_other_assignments = !empty($judge_other_assignments);
                                                            ?>
                                                            
                                                            <tr class="<?= $is_assigned_here ? 'table-success' : '' ?> <?= $has_other_assignments ? 'table-warning' : '' ?>">
                                                                <td class="text-center">
                                                                    <input class="form-check-input judge-checkbox" type="checkbox" 
                                                                           name="judge_ids[]" value="<?= $j['id'] ?>" 
                                                                           id="judge_<?= $j['id'] ?>"
                                                                           <?= $is_assigned_here ? 'checked' : '' ?>>
                                                                </td>
                                                                <td>
                                                                    <label for="judge_<?= $j['id'] ?>" class="mb-0 cursor-pointer">
                                                                        <strong><?= htmlspecialchars($j['username']) ?></strong>
                                                                        <?php if ($is_assigned_here): ?>
                                                                            <i class="bi bi-check-circle-fill text-success ms-2" title="Currently assigned here"></i>
                                                                        <?php endif; ?>
                                                                    </label>
                                                                </td>
                                                                <td class="text-center">
                                                                    <?php if ($j['is_head'] == 1): ?>
                                                                        <span class="badge bg-warning">
                                                                            <i class="bi bi-star-fill"></i> Head Judge
                                                                        </span>
                                                                    <?php else: ?>
                                                                        <span class="badge bg-secondary">
                                                                            <i class="bi bi-person"></i> Judge
                                                                        </span>
                                                                    <?php endif; ?>
                                                                </td>
                                                                <td class="text-center">
                                                                    <?php if ($has_other_assignments): ?>
                                                                        <div>
                                                                            <span class="badge bg-info mb-1" title="Multi-assigned">
                                                                                <i class="bi bi-layers"></i> Multi
                                                                            </span>
                                                                            <div class="small text-muted">
                                                                                <?php foreach ($judge_other_assignments as $cp_name): ?>
                                                                                    <div class="badge bg-light text-dark border mb-1"><?= htmlspecialchars($cp_name) ?></div>
                                                                                <?php endforeach; ?>
                                                                            </div>
                                                                        </div>
                                                                    <?php elseif ($is_assigned_here): ?>
                                                                        <span class="badge bg-success">
                                                                            <i class="bi bi-check-circle"></i> Assigned Here
                                                                        </span>
                                                                    <?php else: ?>
                                                                        <span class="text-muted small">
                                                                            <i class="bi bi-dash-circle"></i> Available
                                                                        </span>
                                                                    <?php endif; ?>
                                                                </td>
                                                                <td class="text-center">
                                                                    <small class="text-muted"><?= $j['id'] ?></small>
                                                                </td>
                                                            </tr>
                                                        <?php endforeach; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                            
                                            <div class="d-grid gap-2 mt-4">
                                                <button type="submit" class="btn btn-success btn-lg btn-custom">
                                                    <i class="bi bi-floppy-fill me-2"></i>Save Judge Assignments
                                                </button>
                                                <button type="button" class="btn btn-outline-secondary" onclick="toggleAllJudges()">
                                                    <i class="bi bi-check-all me-2"></i>Toggle All Judges
                                                </button>
                                            </div>
                                        <?php endif; ?>
                                    </form>
                                </div>
                            </div>
                        </div>
                         </div>
                        <!-- Right Column: Current Assignments Table -->
                        <div class="col-md-6">
                            <div class="border-0 shadow-none card border-0 shadow-sm mb-3 card-hover">
                                <div class="border-0 shadow-none card-body py-2">
                                    <h6 class="mb-2 fw-bold text-info">
                                        <i class="bi bi-table me-1"></i>
                                        Current Judge Assignments
                                    </h6>
                                    <?php if (empty($assignments_by_cp)): ?>
                                        <div class="text-center text-muted py-3">
                                            <i class="bi bi-person-x display-6 opacity-25"></i>
                                            <p class="small mb-0 mt-2">No Judges Assigned</p>
                                            <small class="text-muted">Select a control point and assign judges to see them here.</small>
                                        </div>
                                    <?php else: ?>
                                        <div class="table-responsive">
                                            <table class="table table-bordered">
                                                <thead class="table-light">
                                                    <tr>
                                                        <th>Control Point</th>
                                                        <th>Assigned Judges</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <!-- General Judging Row -->
                                                    <?php if (isset($assignments_by_cp['general'])): ?>
                                                        <tr>
                                                            <td class="cp-general">
                                                                <i class="bi bi-star-fill me-1"></i>
                                                                <strong>General Judging</strong>
                                                                <br><small class="text-muted">Overall event judging</small>
                                                            </td>
                                                            <td>
                                                                <?php foreach ($assignments_by_cp['general']['judges'] as $judge): ?>
                                                                    <span class="badge bg-light text-dark border me-1 mb-1 <?= $judge['is_head'] == 1 ? 'bg-warning text-dark' : '' ?>">
                                                                        <?php if ($judge['is_head'] == 1): ?>
                                                                            <i class="bi bi-star-fill me-1"></i>
                                                                        <?php endif; ?>
                                                                        <?= htmlspecialchars($judge['username']) ?>
                                                                        <form method="post" class="d-inline">
                                                                            <input type="hidden" name="event_id" value="<?= $selected_event_id ?>">
                                                                            <input type="hidden" name="control_point_id" value="">
                                                                            <input type="hidden" name="unassign_judge_id" value="<?= $judge['judge_id'] ?>">
                                                                            <button type="submit" class="btn btn-sm btn-outline-danger ms-1 py-0 px-1" 
                                                                                    onclick="return confirm('Remove <?= htmlspecialchars($judge['username']) ?> from General Judging?')"
                                                                                    title="Remove Judge">×</button>
                                                                        </form>
                                                                    </span>
                                                                <?php endforeach; ?>
                                                            </td>
                                                        </tr>
                                                    <?php else: ?>
                                                        <tr>
                                                            <td class="cp-general">
                                                                <i class="bi bi-star-fill me-1"></i>
                                                                <strong>General Judging</strong>
                                                                <br><small class="text-muted">Overall event judging</small>
                                                            </td>
                                                            <td class="empty-cell">No judges assigned</td>
                                                        </tr>
                                                    <?php endif; ?>

                                                    <!-- Specific Control Points -->
                                                    <?php foreach ($control_points as $cp): ?>
                                                        <tr>
                                                            <td>
                                                                <i class="bi bi-geo-alt-fill me-1"></i>
                                                                <strong><?= htmlspecialchars($cp['control_point_name']) ?></strong>
                                                                <?php if ($cp['description']): ?>
                                                                    <br><small class="text-muted"><?= htmlspecialchars($cp['description']) ?></small>
                                                                <?php endif; ?>
                                                                <br><span class="badge bg-secondary">Order: <?= $cp['sort_order'] ?></span>
                                                            </td>
                                                            <td>
                                                                <?php if (isset($assignments_by_cp[$cp['id']])): ?>
                                                                    <?php foreach ($assignments_by_cp[$cp['id']]['judges'] as $judge): ?>
                                                                        <span class="badge bg-light text-dark border me-1 mb-1 <?= $judge['is_head'] == 1 ? 'bg-warning text-dark' : '' ?>">
                                                                            <?php if ($judge['is_head'] == 1): ?>
                                                                                <i class="bi bi-star-fill me-1"></i>
                                                                            <?php endif; ?>
                                                                            <?= htmlspecialchars($judge['username']) ?>
                                                                            <form method="post" class="d-inline">
                                                                                <input type="hidden" name="event_id" value="<?= $selected_event_id ?>">
                                                                                <input type="hidden" name="control_point_id" value="<?= $cp['id'] ?>">
                                                                                <input type="hidden" name="unassign_judge_id" value="<?= $judge['judge_id'] ?>">
                                                                                <button type="submit" class="btn btn-sm btn-outline-danger ms-1 py-0 px-1" 
                                                                                        onclick="return confirm('Remove <?= htmlspecialchars($judge['username']) ?> from <?= htmlspecialchars($cp['control_point_name']) ?>?')"
                                                                                        title="Remove Judge">×</button>
                                                                            </form>
                                                                        </span>
                                                                    <?php endforeach; ?>
                                                                <?php else: ?>
                                                                    <span class="empty-cell">No judges assigned</span>
                                                                <?php endif; ?>
                                                            </td>
                                                        </tr>
                                                    <?php endforeach; ?>
                                                </tbody>
                                            </table>
                                        </div>

                                        <div class="mt-3">
                                            <div class="row text-center">
                                                <div class="col-4">
                                                    <div class="p-2 bg-light rounded">
                                                        <strong><?= count($assignments_by_cp) ?></strong>
                                                        <br><small class="text-muted">Control Points</small>
                                                    </div>
                                                </div>
                                                <div class="col-4">
                                                    <div class="p-2 bg-light rounded">
                                                        <strong><?= count($all_assignments) ?></strong>
                                                        <br><small class="text-muted">Total Assignments</small>
                                                    </div>
                                                </div>
                                                <div class="col-4">
                                                    <div class="p-2 bg-light rounded">
                                                        <strong><?= count(array_unique(array_column($all_assignments, 'judge_id'))) ?></strong>
                                                        <br><small class="text-muted">Unique Judges</small>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="mt-3 p-3 bg-success bg-opacity-10 rounded">
                                            <small class="text-success">
                                                <i class="bi bi-info-circle me-1"></i>
                                                <strong>Legend:</strong> 
                                                <span class="badge bg-light text-dark border me-2">Regular Judge</span>
                                                <span class="badge bg-warning text-dark"><i class="bi bi-star-fill me-1"></i>Head Judge</span>
                                            </small>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Help Modal -->
    <div class="modal fade" id="judgeAssignHelpModal" tabindex="-1" aria-labelledby="judgeAssignHelpTitle" aria-hidden="true">
        <div class="modal-dialog modal-xl modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title" id="judgeAssignHelpTitle">
                        <i class="bi bi-question-circle me-2"></i>Judge Assignment – Help
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body p-0">
                    <iframe id="judgeAssignHelpIframe" style="width:100%; height:80vh; border:none;" title="Judge Assignment Help"></iframe>
                </div>
            </div>
        </div>
    </div>

    <!-- Create Control Point Modal -->
    <div class="modal fade" id="createControlPointModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="bi bi-geo-alt-fill me-2"></i>
                        Create New Control Point
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="post">
                    <div class="modal-body">
                        <input type="hidden" name="event_id" value="<?= $selected_event_id ?>">
                        <input type="hidden" name="create_control_point" value="1">
                        
                        <div class="mb-3">
                            <label class="form-label">Control Point Name</label>
                            <input type="text" class="form-control" name="control_point_name" required 
                                   placeholder="e.g., Start Gate, Jump 1, Finish Line">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Description (Optional)</label>
                            <textarea class="form-control" name="description" rows="3" 
                                      placeholder="Brief description of this control point"></textarea>
                        </div>
                        
                        <div class="alert alert-info">
                            <i class="bi bi-info-circle me-2"></i>
                            Control points allow you to assign specific judges to different areas or aspects of judging within an event.
                            <br><small class="text-muted mt-1 d-block"><strong>Note:</strong> If you encounter database errors, you may need to run the SQL migration script: <code>/admin/sql/add_control_point_fields.sql</code></small>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-plus-circle me-2"></i>Create Control Point
                        </button>
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Edit Control Point Modal -->
    <div class="modal fade" id="editControlPointModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="bi bi-pencil-square me-2"></i>
                        Edit Control Point
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="post" id="editControlPointForm">
                    <div class="modal-body">
                        <input type="hidden" name="event_id" value="<?= $selected_event_id ?>">
                        <input type="hidden" name="control_point_id" id="edit_control_point_id">
                        <input type="hidden" name="edit_control_point" value="1">
                        
                        <div class="mb-3">
                            <label class="form-label">Control Point Name</label>
                            <input type="text" class="form-control" name="control_point_name" id="edit_control_point_name" required 
                                   placeholder="e.g., Start Gate, Jump 1, Finish Line">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Description (Optional)</label>
                            <textarea class="form-control" name="description" id="edit_description" rows="3" 
                                      placeholder="Brief description of this control point"></textarea>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Status</label>
                                    <select class="form-select" name="status" id="edit_status">
                                        <option value="1">Active</option>
                                        <option value="0">Inactive</option>
                                    </select>
                                    <div class="form-text">Inactive control points won't be available for judging</div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Weight</label>
                                    <input type="number" class="form-control" name="weight" id="edit_weight" 
                                           step="0.1" min="0" max="2" value="1.0" placeholder="1.0">
                                    <div class="form-text">Score calculation multiplier (e.g., 0.8 for 80% weight)</div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="alert alert-info">
                            <i class="bi bi-info-circle me-2"></i>
                            <strong>Weight Usage:</strong> This multiplier affects how scores from this control point contribute to the final score calculation. A weight of 1.0 means full contribution, 0.8 means 80% contribution.
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-check-circle me-2"></i>Update Control Point
                        </button>
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="button" class="btn btn-danger" onclick="deleteControlPoint()">
                            <i class="bi bi-trash me-2"></i>Delete
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    
    <script>
        function openJudgeAssignHelp() {
            const modalEl = document.getElementById('judgeAssignHelpModal');
            const iframe = document.getElementById('judgeAssignHelpIframe');
            if (iframe && !iframe.src) {
                iframe.src = '../help/judge_assign_help.html';
            }
            const modal = new bootstrap.Modal(modalEl);
            modal.show();
        }
        function selectControlPoint(controlPointId) {
            const url = new URL(window.location);
            url.searchParams.set('event_id', '<?= $selected_event_id ?>');
            
            if (controlPointId) {
                url.searchParams.set('control_point_id', controlPointId);
            } else {
                url.searchParams.delete('control_point_id');
            }
            
            window.location.href = url.toString();
        }

        function editControlPoint(id, name, description, status, weight) {
            // Populate the edit modal form
            document.getElementById('edit_control_point_id').value = id;
            document.getElementById('edit_control_point_name').value = name;
            document.getElementById('edit_description').value = description;
            document.getElementById('edit_status').value = status;
            document.getElementById('edit_weight').value = weight;
            
            // Show the modal
            const modal = new bootstrap.Modal(document.getElementById('editControlPointModal'));
            modal.show();
        }

        function deleteControlPoint() {
            const controlPointId = document.getElementById('edit_control_point_id').value;
            const controlPointName = document.getElementById('edit_control_point_name').value;
            
            if (confirm(`Are you sure you want to delete the control point "${controlPointName}"? This action cannot be undone.`)) {
                // Create a form to submit the delete request
                const form = document.createElement('form');
                form.method = 'POST';
                form.style.display = 'none';
                
                const eventIdInput = document.createElement('input');
                eventIdInput.type = 'hidden';
                eventIdInput.name = 'event_id';
                eventIdInput.value = '<?= $selected_event_id ?>';
                
                const controlPointIdInput = document.createElement('input');
                controlPointIdInput.type = 'hidden';
                controlPointIdInput.name = 'control_point_id';
                controlPointIdInput.value = controlPointId;
                
                const deleteInput = document.createElement('input');
                deleteInput.type = 'hidden';
                deleteInput.name = 'delete_control_point';
                deleteInput.value = '1';
                
                form.appendChild(eventIdInput);
                form.appendChild(controlPointIdInput);
                form.appendChild(deleteInput);
                
                document.body.appendChild(form);
                form.submit();
            }
        }

        function toggleAllJudges() {
            const checkboxes = document.querySelectorAll('input[name="judge_ids[]"]');
            const allChecked = Array.from(checkboxes).every(cb => cb.checked);
            
            checkboxes.forEach(cb => {
                cb.checked = !allChecked;
                updateRowStyling(cb);
            });
            
            // Update "Select All" checkbox state
            const selectAllCheckbox = document.getElementById('selectAll');
            if (selectAllCheckbox) {
                selectAllCheckbox.checked = !allChecked;
            }
        }

        function toggleAllJudgesTable(selectAllCheckbox) {
            const checkboxes = document.querySelectorAll('input[name="judge_ids[]"]');
            
            checkboxes.forEach(cb => {
                cb.checked = selectAllCheckbox.checked;
                updateRowStyling(cb);
            });
        }

        function updateRowStyling(checkbox) {
            const row = checkbox.closest('tr');
            if (checkbox.checked) {
                if (!row.classList.contains('table-warning')) {
                    row.classList.add('table-success');
                }
            } else {
                row.classList.remove('table-success');
            }
        }

        // Update visual styling when checkboxes are clicked
        document.querySelectorAll('input[name="judge_ids[]"]').forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                updateRowStyling(this);
                
                // Update "Select All" checkbox state
                const selectAllCheckbox = document.getElementById('selectAll');
                if (selectAllCheckbox) {
                    const allCheckboxes = document.querySelectorAll('input[name="judge_ids[]"]');
                    const allChecked = Array.from(allCheckboxes).every(cb => cb.checked);
                    const someChecked = Array.from(allCheckboxes).some(cb => cb.checked);
                    
                    selectAllCheckbox.checked = allChecked;
                    selectAllCheckbox.indeterminate = someChecked && !allChecked;
                }
            });
        });

        // Auto-hide alerts after 7 seconds (except warning alerts)
        document.querySelectorAll('.alert:not(.alert alert-warning)').forEach(alert => {
            setTimeout(() => {
                if (alert.querySelector('.btn-close')) {
                    const bsAlert = new bootstrap.Alert(alert);
                    bsAlert.close();
                }
            }, 7000);
        });

        // Clean URL
        if (window.location.search.includes('msg=')) {
            const url = new URL(window.location);
            url.searchParams.delete('msg');
            window.history.replaceState({}, document.title, url.toString());
        }
    </script>

   
    <?php include 'footer.php'; ?>
</body>
</html>