<?php
if(!isset($_SESSION)) { 
    //session_start(); 
}
include '../includes/auth.php';
include '../includes/db.php';

// Get analytics with judge names
$results = $pdo->query("
    SELECT s.judge_id, u.username as judge_name, COUNT(*) as total_scores,
           AVG(s.score_value) as avg_score,
           MIN(s.score_value) as min_score,
           MAX(s.score_value) as max_score,
           STDDEV(s.score_value) as std_deviation
    FROM scores s
    JOIN users u ON s.judge_id = u.id
    WHERE s.status = 'OK' AND u.role = 'judge'
    GROUP BY s.judge_id, u.username
    ORDER BY total_scores DESC
")->fetchAll(PDO::FETCH_ASSOC);

// Calculate overall statistics
$overall_stats = $pdo->query("
    SELECT COUNT(*) as total_scores,
           AVG(score_value) as avg_score,
           MIN(score_value) as min_score,
           MAX(score_value) as max_score,
           STDDEV(score_value) as std_deviation
    FROM scores 
    WHERE status = 'OK'
")->fetch(PDO::FETCH_ASSOC);

// Get scoring trends by day
$daily_trends = $pdo->query("
    SELECT DATE(s.created_at) as score_date,
           COUNT(*) as scores_count,
           AVG(s.score_value) as avg_score
    FROM scores s
    WHERE s.status = 'OK' AND s.created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
    GROUP BY DATE(s.created_at)
    ORDER BY score_date DESC
    LIMIT 30
")->fetchAll(PDO::FETCH_ASSOC);

// Get score distribution
$score_distribution = $pdo->query("
    SELECT 
        CASE 
            WHEN score_value < 20 THEN '0-19'
            WHEN score_value < 40 THEN '20-39'
            WHEN score_value < 60 THEN '40-59'
            WHEN score_value < 80 THEN '60-79'
            ELSE '80-100'
        END as score_range,
        COUNT(*) as count
    FROM scores 
    WHERE status = 'OK'
    GROUP BY score_range
    ORDER BY score_range
")->fetchAll(PDO::FETCH_ASSOC);

// Get most active events - simplified without events table if relationship doesn't exist
$active_events = [];
try {
    $active_events = $pdo->query("
        SELECT 'General Scoring' as event_name, COUNT(s.id) as score_count,
               AVG(s.score_value) as avg_score
        FROM scores s
        WHERE s.status = 'OK'
        GROUP BY 'General Scoring'
        ORDER BY score_count DESC
        LIMIT 10
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    // If there's still an error, provide empty array
    $active_events = [];
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Judge Scoring Analytics</title>
    <?php include_once '../includes/stylesheets.php'; ?>
<!-- style skin holder -->
    <style>
        .stats-card {
            border: none;
            border-radius: 0.5rem;
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
            transition: all 0.3s ease;
        }
        
        .stats-card:hover {
            box-shadow: 0 0.375rem 0.75rem rgba(0, 0, 0, 0.15);
            transform: translateY(-1px);
        }
        
        .stats-card .card-header {
            border-bottom: 1px solid rgba(0,0,0,0.1);
            padding: 0.5rem 0.75rem;
        }
        
        .stats-card .card-body {
            padding: 0.75rem;
        }
        
        .metric-value {
            font-size: 1.5rem;
            font-weight: 700;
            margin-bottom: 0.125rem;
            line-height: 1.1;
        }
        
        .metric-label {
            font-size: 0.75rem;
            opacity: 0.9;
            line-height: 1.2;
        }
        
        .progress-modern {
            height: 0.375rem;
            border-radius: 0.25rem;
            background-color: #e9ecef;
        }
        
        .table-analytics {
            font-size: 0.8rem;
        }
        
        .table-analytics th {
            background-color: #f8f9fa;
            border-top: none;
            font-weight: 600;
            padding: 0.5rem 0.75rem;
        }
        
        .table-analytics td {
            padding: 0.5rem 0.75rem;
        }
        
        .badge-metric {
            font-size: 0.6rem;
            padding: 0.2rem 0.4rem;
        }
        
        .chart-container {
            position: relative;
        }
        
        .compact-header {
            font-size: 0.9rem;
            font-weight: 600;
        }
        
        .compact-text {
            font-size: 0.75rem;
            line-height: 1.3;
        }
        
        .judge-avatar {
            width: 28px;
            height: 28px;
            font-size: 0.7rem;
        }
        
        .distribution-item {
            margin-bottom: 0.75rem;
        }
        
        .trend-item {
            margin-bottom: 0.5rem;
        }
    </style>
</head>
<body class="body-bg-aurora-bright">
    <?php include '../menu.php'; ?>
<div class="container-fluid container-StyleScore p-4">
    <?php       
            $use_localStorage = true;
            $show_header = false;
            include 'event_actions_menu.php'; 
            ?>
    <!-- Header -->
    <div class="d-flex justify-content-between align-items-center mb-3">
        <div>
            <h1 class="h4 mb-1">
                <i class="fas fa-chart-line text-primary me-2"></i>Judge Scoring Analytics
            </h1>
            <p class="text-muted mb-0 small">Comprehensive analysis of judge performance and scoring patterns</p>
        </div>
        <div class="text-end">
            <small class="text-muted compact-text">
                <i class="fas fa-info-circle me-1"></i>Based on scores with "OK" status only
            </small>
        </div>
    </div>

    <!-- Key Metrics Row -->
    <div class="row g-2 mb-3">
        <div class="col-lg-2 col-md-4 col-sm-6">
            <div class="border-0 shadow-none card text-center">
                <div class="border-0 shadow-none card-body">
                    <div class="metric-value text-primary"><?= number_format($overall_stats['total_scores']) ?></div>
                    <div class="metric-label text-muted">
                        <i class="fas fa-trophy me-1"></i>Total Scores
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-2 col-md-4 col-sm-6">
            <div class="border-0 shadow-none card text-center">
                <div class="border-0 shadow-none card-body">
                    <div class="metric-value text-success"><?= number_format($overall_stats['avg_score'], 1) ?></div>
                    <div class="metric-label text-muted">
                        <i class="fas fa-chart-line me-1"></i>Average Score
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-2 col-md-4 col-sm-6">
            <div class="border-0 shadow-none card text-center">
                <div class="border-0 shadow-none card-body">
                    <div class="metric-value text-info"><?= count($results) ?></div>
                    <div class="metric-label text-muted">
                        <i class="fas fa-users me-1"></i>Active Judges
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-2 col-md-4 col-sm-6">
            <div class="border-0 shadow-none card text-center">
                <div class="border-0 shadow-none card-body">
                    <div class="metric-value text-warning"><?= $overall_stats['min_score'] ?>-<?= $overall_stats['max_score'] ?></div>
                    <div class="metric-label text-muted">
                        <i class="fas fa-arrows-alt-h me-1"></i>Score Range
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-2 col-md-4 col-sm-6">
            <div class="border-0 shadow-none card text-center">
                <div class="border-0 shadow-none card-body">
                    <div class="metric-value text-secondary"><?= number_format($overall_stats['std_deviation'], 1) ?></div>
                    <div class="metric-label text-muted">
                        <i class="fas fa-balance-scale me-1"></i>Std. Deviation
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-2 col-md-4 col-sm-6">
            <div class="border-0 shadow-none card metric-card text-center">
                <div class="border-0 shadow-none card-body">
                    <div class="metric-value"><?= count($daily_trends) ?></div>
                    <div class="metric-label">
                        <i class="fas fa-calendar me-1"></i>Active Days
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Analytics Cards Row -->
    <div class="row g-3 mb-3">
        <!-- Score Distribution -->
        <div class="col-lg-4">
            <div class="border-0 shadow-none card stats-card h-100">
                <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center py-2">
                    <h6 class="mb-0 compact-header">
                        <i class="fas fa-chart-pie text-primary me-2"></i>Score Distribution
                    </h6>
                </div>
                <div class="border-0 shadow-none card-body">
                    <?php if (!empty($score_distribution)): ?>
                        <?php 
                        $total_scores = array_sum(array_column($score_distribution, 'count'));
                        $colors = ['#dc3545', '#fd7e14', '#ffc107', '#28a745', '#20c997'];
                        ?>
                        <?php foreach ($score_distribution as $index => $dist): ?>
                            <div class="distribution-item">
                                <div class="d-flex justify-content-between align-items-center mb-1">
                                    <span class="fw-medium compact-text"><?= $dist['score_range'] ?> points</span>
                                    <small class="text-muted compact-text"><?= number_format(($dist['count'] / $total_scores) * 100, 1) ?>%</small>
                                </div>
                                <div class="progress progress-modern">
                                    <div class="progress-bar" 
                                         style="width: <?= ($dist['count'] / $total_scores) * 100 ?>%; background-color: <?= $colors[$index] ?? '#6c757d' ?>"
                                         role="progressbar"></div>
                                </div>
                                <small class="text-muted compact-text"><?= number_format($dist['count']) ?> scores</small>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="text-center text-muted py-2">
                            <i class="fas fa-chart-pie fa-lg mb-1"></i>
                            <p class="compact-text">No distribution data available</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Daily Trends -->
        <div class="col-lg-4">
            <div class="border-0 shadow-none card stats-card h-100">
                <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center py-2">
                    <h6 class="mb-0 compact-header">
                        <i class="fas fa-chart-line text-success me-2"></i>Recent Activity (30 Days)
                    </h6>
                </div>
                <div class="border-0 shadow-none card-body">
                    <?php if (!empty($daily_trends)): ?>
                        <div class="chart-container mb-2">
                            <?php 
                            $max_count = max(array_column($daily_trends, 'scores_count'));
                            $reversed_trends = array_reverse($daily_trends);
                            ?>
                            <?php foreach (array_slice($reversed_trends, -10) as $trend): ?>
                                <div class="d-flex align-items-center trend-item">
                                    <small class="text-muted me-2 compact-text" style="min-width: 50px;">
                                        <?= date('M j', strtotime($trend['score_date'])) ?>
                                    </small>
                                    <div class="progress progress-modern flex-grow-1 me-2">
                                        <div class="progress-bar bg-success" 
                                             style="width: <?= ($trend['scores_count'] / $max_count) * 100 ?>%"
                                             role="progressbar"></div>
                                    </div>
                                    <small class="fw-medium compact-text"><?= $trend['scores_count'] ?></small>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        <div class="text-center">
                            <small class="text-muted compact-text">
                                Total: <?= array_sum(array_column($daily_trends, 'scores_count')) ?> scores in 30 days
                            </small>
                        </div>
                    <?php else: ?>
                        <div class="text-center text-muted py-2">
                            <i class="fas fa-chart-line fa-lg mb-1"></i>
                            <p class="compact-text">No activity data available</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Top Events -->
        <div class="col-lg-4">
            <div class="border-0 shadow-none card stats-card h-100">
                <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center py-2">
                    <h6 class="mb-0 compact-header">
                        <i class="fas fa-star text-warning me-2"></i>Most Active Events
                    </h6>
                </div>
                <div class="border-0 shadow-none card-body">
                    <?php if (!empty($active_events)): ?>
                        <?php foreach (array_slice($active_events, 0, 8) as $index => $event): ?>
                            <div class="d-flex align-items-center mb-1">
                                <div class="badge bg-primary badge-metric me-2"><?= $index + 1 ?></div>
                                <div class="flex-grow-1">
                                    <div class="fw-medium text-truncate compact-text" style="max-width: 120px;">
                                        <?= htmlspecialchars($event['event_name']) ?>
                                    </div>
                                    <small class="text-muted compact-text">
                                        <?= $event['score_count'] ?> scores • Avg: <?= number_format($event['avg_score'], 1) ?>
                                    </small>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="text-center text-muted py-2">
                            <i class="fas fa-star fa-lg mb-1"></i>
                            <p class="compact-text">No event data available</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Judge Performance Table -->
    <div class="border-0 shadow-none card stats-card">
        <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center py-2">
            <h6 class="mb-0 compact-header">
                <i class="fas fa-users text-info me-2"></i>Individual Judge Performance
            </h6>
            <small class="text-muted compact-text">Detailed analysis by judge</small>
        </div>
        <div class="border-0 shadow-none card-body p-0">
            <div class="table-responsive">
                <table class="table table-analytics table-hover mb-0">
                    <thead>
                        <tr>
                            <th scope="col">#</th>
                            <th scope="col">Judge</th>
                            <th scope="col" class="text-center">Scores</th>
                            <th scope="col" class="text-center">Average</th>
                            <th scope="col" class="text-center">Range</th>
                            <th scope="col" class="text-center">Consistency</th>
                            <th scope="col" class="text-center">Distribution</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php if (empty($results)): ?>
                        <tr>
                            <td colspan="7" class="text-center text-muted py-3">
                                <i class="fas fa-users fa-lg mb-1 d-block"></i>
                                <span class="compact-text">No scoring data available</span>
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($results as $index => $r): ?>
                            <?php 
                            $avg_diff = $r['avg_score'] - $overall_stats['avg_score'];
                            $avg_class = $avg_diff > 0.5 ? 'text-success' : ($avg_diff < -0.5 ? 'text-danger' : 'text-secondary');
                            $range = $r['max_score'] - $r['min_score'];
                            $consistency = $r['std_deviation'] < 1 ? 'Excellent' : ($r['std_deviation'] < 2 ? 'Good' : 'Variable');
                            $consistency_class = $r['std_deviation'] < 1 ? 'success' : ($r['std_deviation'] < 2 ? 'warning' : 'danger');
                            ?>
                            <tr>
                                <td class="fw-bold"><?= $index + 1 ?></td>
                                <td>
                                    <div class="d-flex align-items-center">
                                        <div class="me-2">
                                            <div class="bg-primary rounded-circle d-flex align-items-center justify-content-center judge-avatar">
                                                <span class="text-white fw-bold"><?= strtoupper(substr($r['judge_name'], 0, 2)) ?></span>
                                            </div>
                                        </div>
                                        <div>
                                            <div class="fw-medium compact-text"><?= htmlspecialchars($r['judge_name']) ?></div>
                                            <small class="text-muted compact-text">ID: <?= $r['judge_id'] ?></small>
                                        </div>
                                    </div>
                                </td>
                                <td class="text-center">
                                    <span class="badge bg-primary badge-metric"><?= number_format($r['total_scores']) ?></span>
                                </td>
                                <td class="text-center">
                                    <div class="fw-bold <?= $avg_class ?> compact-text"><?= number_format($r['avg_score'], 2) ?></div>
                                    <?php if (abs($avg_diff) > 0.1): ?>
                                        <small class="<?= $avg_class ?> compact-text">
                                            <?= $avg_diff > 0 ? '▲' : '▼' ?> <?= number_format(abs($avg_diff), 2) ?>
                                        </small>
                                    <?php endif; ?>
                                </td>
                                <td class="text-center">
                                    <div class="fw-medium compact-text"><?= $r['min_score'] ?> - <?= $r['max_score'] ?></div>
                                    <small class="text-muted compact-text">Span: <?= $range ?></small>
                                </td>
                                <td class="text-center">
                                    <div class="fw-medium compact-text"><?= number_format($r['std_deviation'], 2) ?></div>
                                    <span class="badge bg-<?= $consistency_class ?> badge-metric"><?= $consistency ?></span>
                                </td>
                                <td class="text-center">
                                    <div class="progress progress-modern">
                                        <?php 
                                        $score_range = $overall_stats['max_score'] - $overall_stats['min_score'];
                                        if ($score_range > 0) {
                                            $min_width = (($r['min_score'] - $overall_stats['min_score']) / $score_range) * 100;
                                            $max_width = (($r['max_score'] - $overall_stats['min_score']) / $score_range) * 100;
                                            $range_width = $max_width - $min_width;
                                        } else {
                                            $min_width = 0;
                                            $range_width = 100;
                                        }
                                        ?>
                                        <div class="progress-bar bg-info" 
                                             style="margin-left: <?= $min_width ?>%; width: <?= $range_width ?>%"></div>
                                    </div>
                                    <small class="text-muted compact-text">Score Range</small>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Analytics Legend -->
    <div class="row g-3 mt-2">
        <div class="col-lg-6">
            <div class="border-0 shadow-none card stats-card">
                <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center py-2">
                    <h6 class="mb-0">
                        <i class="fas fa-info-circle text-secondary me-2"></i>Performance Indicators
                    </h6>
                </div>
                <div class="border-0 shadow-none card-body compact-content">
                    <div class="row g-2">
                        <div class="col-sm-6">
                            <h6 class="fw-bold compact-text">Average Comparison</h6>
                            <div class="compact-list">
                                <div class="compact-text">
                                    <span class="text-success">▲ Green</span> - Above overall average (+0.5)
                                </div>
                                <div class="compact-text">
                                    <span class="text-danger">▼ Red</span> - Below overall average (-0.5)
                                </div>
                                <div class="compact-text">
                                    <span class="text-secondary">• Gray</span> - Close to average
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <h6 class="fw-bold compact-text">Consistency Rating</h6>
                            <div class="compact-list">
                                <div class="compact-text">
                                    <span class="badge bg-success badge-legend">Excellent</span> Std. Dev. < 1.0
                                </div>
                                <div class="compact-text">
                                    <span class="badge bg-warning badge-legend">Good</span> Std. Dev. < 2.0
                                </div>
                                <div class="compact-text">
                                    <span class="badge bg-danger badge-legend">Variable</span> Std. Dev. ≥ 2.0
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-lg-6">
            <div class="border-0 shadow-none card stats-card">
                <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center py-2">
                    <h6 class="mb-0">
                        <i class="fas fa-lightbulb text-warning me-2"></i>Quick Insights
                    </h6>
                </div>
                <div class="border-0 shadow-none card-body compact-content">
                    <?php 
                    $most_active = !empty($results) ? $results[0] : null;
                    $most_consistent = !empty($results) ? array_reduce($results, function($carry, $item) {
                        return $carry === null || $item['std_deviation'] < $carry['std_deviation'] ? $item : $carry;
                    }) : null;
                    ?>
                    
                    <?php if ($most_active): ?>
                        <div class="compact-insight">
                            <div class="d-flex align-items-center">
                                <i class="fas fa-trophy text-warning me-2 insight-icon"></i>
                                <strong class="compact-text">Most Active Judge</strong>
                            </div>
                            <div class="text-muted compact-text">
                                <?= htmlspecialchars($most_active['judge_name']) ?> with <?= number_format($most_active['total_scores']) ?> scores
                            </div>
                        </div>
                    <?php endif; ?>
                    
                    <?php if ($most_consistent): ?>
                        <div class="compact-insight">
                            <div class="d-flex align-items-center">
                                <i class="fas fa-balance-scale text-success me-2 insight-icon"></i>
                                <strong class="compact-text">Most Consistent Judge</strong>
                            </div>
                            <div class="text-muted compact-text">
                                <?= htmlspecialchars($most_consistent['judge_name']) ?> (σ = <?= number_format($most_consistent['std_deviation'], 2) ?>)
                            </div>
                        </div>
                    <?php endif; ?>
                    
                    <div class="compact-insight">
                        <div class="d-flex align-items-center">
                            <i class="fas fa-chart-line text-info me-2 insight-icon"></i>
                            <strong class="compact-text">Overall Health</strong>
                        </div>
                        <div class="text-muted compact-text">
                            <?php 
                            $health_score = 100;
                            if ($overall_stats['std_deviation'] > 2) $health_score -= 20;
                            
                            $consistency_scores = array_column($results, 'std_deviation');
                            $good_consistency = count(array_filter($consistency_scores, function($x) { return $x < 2; }));
                            $consistency_ratio = count($results) > 0 ? $good_consistency / count($results) : 0;
                            if ($consistency_ratio < 0.7) $health_score -= 15;
                            
                            $health_class = $health_score >= 90 ? 'success' : ($health_score >= 70 ? 'warning' : 'danger');
                            ?>
                            <span class="badge bg-<?= $health_class ?> badge-legend"><?= $health_score ?>% Healthy</span>
                            <span class="compact-text">scoring environment</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

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