<?php
// results.php
// Enable error reporting for debugging
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', '../logs/php_errors.log');

require_once '../includes/db_connect.php';

// Check session
if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'admin') {
    error_log("Unauthorized access attempt to results.php. Session: " . print_r($_SESSION, true));
    header("Location: ../login.php");
    exit;
}

// Fetch admin username
$admin_name = 'Admin';
try {
    $stmt = $pdo->prepare("SELECT username FROM admins WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $admin = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($admin) {
        $admin_name = $admin['username'];
    }
} catch (PDOException $e) {
    error_log("Error fetching admin username: " . $e->getMessage());
}

// Get filter parameters
$exam_id = isset($_GET['exam_id']) ? intval($_GET['exam_id']) : 0;
$class_id = isset($_GET['class_id']) ? intval($_GET['class_id']) : 0;
$student_id = isset($_GET['student_id']) ? intval($_GET['student_id']) : 0;

// Initialize results data
$results = [];
$exams = [];
$students = [];
$classes = [];

try {
    // Fetch all exams for filter dropdown
    $exams = $pdo->query("SELECT id, exam_name FROM exams ORDER BY exam_date DESC")->fetchAll(PDO::FETCH_ASSOC);
    
    // Fetch all classes for filter dropdown
    $classes = $pdo->query("SELECT id, class_name FROM classes ORDER BY class_name")->fetchAll(PDO::FETCH_ASSOC);
    
    // Build query based on filter parameters
    $query = "
        SELECT 
            r.id, 
            r.exam_id, 
            e.exam_name,
            r.student_id,
            a.full_name as student_name,
            a.class_id,
            c.class_name,
            r.subject_id,
            s.name as subject_name,
            r.score, 
            r.total_questions,
            ROUND((r.score / r.total_questions) * 100, 2) as percentage,
            r.completed_at
        FROM cbt_results r
        JOIN exams e ON r.exam_id = e.id
        JOIN applicants a ON r.student_id = a.id
        LEFT JOIN classes c ON a.class_id = c.id
        JOIN subjects s ON r.subject_id = s.id
    ";
    
    $conditions = [];
    $params = [];
    
    if ($exam_id > 0) {
        $conditions[] = "r.exam_id = ?";
        $params[] = $exam_id;
    }
    
    if ($class_id > 0) {
        $conditions[] = "a.class_id = ?";
        $params[] = $class_id;
    }
    
    if ($student_id > 0) {
        $conditions[] = "r.student_id = ?";
        $params[] = $student_id;
    }
    
    if (!empty($conditions)) {
        $query .= " WHERE " . implode(" AND ", $conditions);
    }
    
    $query .= " ORDER BY r.completed_at DESC";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (PDOException $e) {
    error_log("Error fetching results: " . $e->getMessage());
    $error_message = "Error loading results. Please try again later.";
}

// Calculate statistics
$total_results = count($results);
$average_score = 0;
$highest_score = 0;
$lowest_score = 100;

if ($total_results > 0) {
    $scores = array_column($results, 'percentage');
    $average_score = round(array_sum($scores) / $total_results, 2);
    $highest_score = round(max($scores), 2);
    $lowest_score = round(min($scores), 2);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>View Results - Verbum Dei Academy & Verbum Dei Int'l College</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">
    <style>
        :root {
            --primary: #4e73df;
            --secondary: #858796;
            --success: #1cc88a;
            --info: #36b9cc;
            --warning: #f6c23e;
            --danger: #e74a3b;
            --light: #f8f9fc;
            --dark: #5a5c69;
        }
        
        body {
            background-color: #f8f9fc;
            font-family: 'Nunito', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .dashboard-header {
            background: white;
            border-radius: 15px;
            padding: 1.5rem;
            margin-bottom: 2rem;
            box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15);
        }
        
        .stat-card {
            border-radius: 15px;
            border: none;
            box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.1);
            transition: all 0.3s;
            overflow: hidden;
        }
        
        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 0.5rem 1.5rem 0 rgba(58, 59, 69, 0.2);
        }
        
        .stat-card .card-icon {
            font-size: 2rem;
            opacity: 0.3;
            position: absolute;
            right: 20px;
            top: 20px;
        }
        
        .stat-card.bg-primary {
            background: linear-gradient(135deg, var(--primary) 0%, #224abe 100%) !important;
            color: white;
        }
        
        .stat-card.bg-success {
            background: linear-gradient(135deg, var(--success) 0%, #13855c 100%) !important;
            color: white;
        }
        
        .stat-card.bg-warning {
            background: linear-gradient(135deg, var(--warning) 0%, #dda20a 100%) !important;
            color: white;
        }
        
        .stat-card.bg-info {
            background: linear-gradient(135deg, var(--info) 0%, #258391 100%) !important;
            color: white;
        }
        
        .section-title {
            position: relative;
            padding-bottom: 10px;
            margin-bottom: 2rem;
        }
        
        .section-title:after {
            content: "";
            position: absolute;
            left: 0;
            bottom: 0;
            width: 50px;
            height: 3px;
            background: var(--success);
        }
        
        .navbar {
            background: white;
            box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15);
            border-radius: 15px;
            padding: 1rem;
            margin-bottom: 2rem;
        }
        
        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: var(--success);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
        }
        
        .filter-card {
            background: white;
            border-radius: 15px;
            padding: 1.5rem;
            margin-bottom: 2rem;
            box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.1);
        }
        
        .result-card {
            background: white;
            border-radius: 15px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.1);
            transition: all 0.3s;
        }
        
        .result-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 0.5rem 1.5rem 0 rgba(58, 59, 69, 0.2);
        }
        
        .score-badge {
            font-size: 1.1rem;
            font-weight: 600;
            padding: 0.5rem 1rem;
            border-radius: 50px;
        }
        
        .score-excellent {
            background-color: rgba(28, 200, 138, 0.15);
            color: var(--success);
        }
        
        .score-good {
            background-color: rgba(246, 194, 62, 0.15);
            color: var(--warning);
        }
        
        .score-poor {
            background-color: rgba(231, 74, 59, 0.15);
            color: var(--danger);
        }
        
        .chart-container {
            position: relative;
            height: 300px;
        }
        
        .floating-action-btn {
            position: fixed;
            bottom: 2rem;
            right: 2rem;
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: var(--success);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 0.25rem 1rem rgba(28, 200, 138, 0.3);
            z-index: 100;
            transition: all 0.3s;
        }
        
        .floating-action-btn:hover {
            transform: translateY(-5px) rotate(5deg);
            box-shadow: 0 0.5rem 1.5rem rgba(28, 200, 138, 0.4);
            color: white;
        }
        
        .filter-row {
            background-color: #f8f9fc;
            border-radius: 10px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
        }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
    <!-- Top Navigation Bar -->
    <nav class="navbar navbar-expand-lg">
        <div class="container-fluid">
            <a class="navbar-brand fw-bold text-success" href="#">
                <i class="bi bi-mortarboard me-2"></i>Verbum Dei Academy & College
            </a>
            <div class="d-flex align-items-center">
                <div class="me-3">
                    <span class="text-muted">Results Management</span>
                </div>
                <div class="user-avatar me-2">
                    <?php echo strtoupper(substr($admin_name, 0, 1)); ?>
                </div>
                <a href="../logout.php" class="btn btn-sm btn-outline-danger">
                    <i class="bi bi-box-arrow-right"></i>
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <!-- Dashboard Header -->
        <div class="dashboard-header animate__animated animate__fadeIn">
            <div class="row align-items-center">
                <div class="col-md-6">
                    <h1 class="h3 fw-bold text-success mb-0">Examination Results</h1>
                    <p class="mb-0 text-muted">View and analyze CBT exam results</p>
                </div>
                <div class="col-md-6 text-md-end">
                    <a href="admin_dashboard.php" class="btn btn-success">
                        <i class="bi bi-arrow-left me-1"></i> Back to Dashboard
                    </a>
                    <span class="badge bg-light text-dark ms-2">
                        <i class="bi bi-calendar me-1"></i> <?php echo date('l, F j, Y'); ?>
                    </span>
                </div>
            </div>
        </div>
        
        <?php if (isset($error_message)): ?>
            <div class="alert alert-danger animate__animated animate__shakeX mb-4"><?php echo htmlspecialchars($error_message); ?></div>
        <?php endif; ?>
        
        <!-- Stats Cards -->
        <div class="row g-4 mb-4">
            <div class="col-xl-3 col-md-6">
                <div class="stat-card card bg-primary text-white animate__animated animate__fadeInUp">
                    <div class="card-body">
                        <i class="bi bi-clipboard-data card-icon"></i>
                        <h5 class="card-title text-uppercase mb-2">Total Results</h5>
                        <h2 class="mb-0 fw-bold"><?php echo $total_results; ?></h2>
                        <p class="mb-0 small mt-2">Examination records</p>
                    </div>
                </div>
            </div>
            
            <div class="col-xl-3 col-md-6">
                <div class="stat-card card bg-success text-white animate__animated animate__fadeInUp animate__delay-1s">
                    <div class="card-body">
                        <i class="bi bi-graph-up card-icon"></i>
                        <h5 class="card-title text-uppercase mb-2">Average Score</h5>
                        <h2 class="mb-0 fw-bold"><?php echo $average_score; ?>%</h2>
                        <p class="mb-0 small mt-2">Across all results</p>
                    </div>
                </div>
            </div>
            
            <div class="col-xl-3 col-md-6">
                <div class="stat-card card bg-warning text-white animate__animated animate__fadeInUp animate__delay-2s">
                    <div class="card-body">
                        <i class="bi bi-trophy card-icon"></i>
                        <h5 class="card-title text-uppercase mb-2">Highest Score</h5>
                        <h2 class="mb-0 fw-bold"><?php echo $highest_score; ?>%</h2>
                        <p class="mb-0 small mt-2">Best performance</p>
                    </div>
                </div>
            </div>
            
            <div class="col-xl-3 col-md-6">
                <div class="stat-card card bg-info text-white animate__animated animate__fadeInUp animate__delay-3s">
                    <div class="card-body">
                        <i class="bi bi-graph-down card-icon"></i>
                        <h5 class="card-title text-uppercase mb-2">Lowest Score</h5>
                        <h2 class="mb-0 fw-bold"><?php echo $lowest_score; ?>%</h2>
                        <p class="mb-0 small mt-2">Needs improvement</p>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Filter Section -->
        <div class="filter-card animate__animated animate__fadeIn">
            <h3 class="section-title">Filter Results</h3>
            
            <form method="GET" action="results.php">
                <div class="filter-row">
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Select Exam</label>
                            <select class="form-select" name="exam_id">
                                <option value="0">All Exams</option>
                                <?php foreach ($exams as $exam): ?>
                                    <option value="<?php echo $exam['id']; ?>" <?php echo $exam_id == $exam['id'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($exam['exam_name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Select Class</label>
                            <select class="form-select" name="class_id">
                                <option value="0">All Classes</option>
                                <?php foreach ($classes as $class): ?>
                                    <option value="<?php echo $class['id']; ?>" <?php echo $class_id == $class['id'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($class['class_name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Student ID (Optional)</label>
                            <input type="number" class="form-control" name="student_id" placeholder="Enter Student ID" value="<?php echo $student_id > 0 ? $student_id : ''; ?>">
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-12 text-end">
                            <button type="submit" class="btn btn-success">
                                <i class="bi bi-filter me-1"></i> Apply Filters
                            </button>
                            <a href="results.php" class="btn btn-outline-secondary ms-2">
                                <i class="bi bi-arrow-repeat me-1"></i> Reset
                            </a>
                        </div>
                    </div>
                </div>
            </form>
        </div>
        
        <!-- Results Section -->
        <div class="row">
            <div class="col-12">
                <div class="card animate__animated animate__fadeIn">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-4">
                            <h3 class="section-title mb-0">Examination Results</h3>
                            <?php if ($total_results > 0): ?>
                                <button class="btn btn-outline-success" onclick="exportToCSV()">
                                    <i class="bi bi-download me-1"></i> Export CSV
                                </button>
                            <?php endif; ?>
                        </div>
                        
                        <?php if ($total_results === 0): ?>
                            <div class="text-center py-5">
                                <i class="bi bi-clipboard-x" style="font-size: 3rem; color: #dee2e6;"></i>
                                <h4 class="mt-3 text-muted">No Results Found</h4>
                                <p class="text-muted">Try adjusting your filters to see results</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-hover" id="resultsTable">
                                    <thead>
                                        <tr>
                                            <th>Student</th>
                                            <th>Class</th>
                                            <th>Exam</th>
                                            <th>Subject</th>
                                            <th>Score</th>
                                            <th>Percentage</th>
                                            <th>Date</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($results as $result): 
                                            $score_class = 'score-excellent';
                                            if ($result['percentage'] < 70) $score_class = 'score-good';
                                            if ($result['percentage'] < 50) $score_class = 'score-poor';
                                        ?>
                                            <tr>
                                                <td><?php echo htmlspecialchars($result['student_name']); ?></td>
                                                <td><?php echo htmlspecialchars($result['class_name']); ?></td>
                                                <td><?php echo htmlspecialchars($result['exam_name']); ?></td>
                                                <td><?php echo htmlspecialchars($result['subject_name']); ?></td>
                                                <td><?php echo $result['score']; ?>/<?php echo $result['total_questions']; ?></td>
                                                <td>
                                                    <span class="<?php echo $score_class; ?> score-badge">
                                                        <?php echo $result['percentage']; ?>%
                                                    </span>
                                                </td>
                                                <td><?php echo date('M j, Y', strtotime($result['completed_at'])); ?></td>
                                                <td>
                                                    <a href="result_details.php?id=<?php echo $result['id']; ?>" class="btn btn-sm btn-outline-primary">
                                                        <i class="bi bi-eye"></i> View
                                                    </a>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Performance Charts -->
        <?php if ($total_results > 0): ?>
        <div class="row mt-4">
            <div class="col-lg-6 mb-4">
                <div class="card animate__animated animate__fadeIn">
                    <div class="card-body">
                        <h3 class="section-title">Score Distribution</h3>
                        <div class="chart-container">
                            <canvas id="scoreChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-6 mb-4">
                <div class="card animate__animated animate__fadeIn">
                    <div class="card-body">
                        <h3 class="section-title">Performance Overview</h3>
                        <div class="chart-container">
                            <canvas id="performanceChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <!-- Floating Action Button -->
    <a href="admin_dashboard.php" class="floating-action-btn animate__animated animate__bounceIn">
        <i class="bi bi-house-door-fill"></i>
    </a>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Add animation to cards on scroll
            const observer = new IntersectionObserver((entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        entry.target.classList.add('animate__fadeIn');
                    }
                });
            }, {threshold: 0.1});
            
            document.querySelectorAll('.card').forEach(card => {
                observer.observe(card);
            });
            
            <?php if ($total_results > 0): ?>
            // Initialize charts
            const scoreCtx = document.getElementById('scoreChart').getContext('2d');
            const scoreChart = new Chart(scoreCtx, {
                type: 'bar',
                data: {
                    labels: ['0-49%', '50-69%', '70-89%', '90-100%'],
                    datasets: [{
                        label: 'Number of Students',
                        data: [
                            <?php echo count(array_filter($results, function($r) { return $r['percentage'] < 50; })); ?>,
                            <?php echo count(array_filter($results, function($r) { return $r['percentage'] >= 50 && $r['percentage'] < 70; })); ?>,
                            <?php echo count(array_filter($results, function($r) { return $r['percentage'] >= 70 && $r['percentage'] < 90; })); ?>,
                            <?php echo count(array_filter($results, function($r) { return $r['percentage'] >= 90; })); ?>
                        ],
                        backgroundColor: [
                            'rgba(231, 74, 59, 0.7)',
                            'rgba(246, 194, 62, 0.7)',
                            'rgba(54, 185, 204, 0.7)',
                            'rgba(28, 200, 138, 0.7)'
                        ],
                        borderColor: [
                            'rgba(231, 74, 59, 1)',
                            'rgba(246, 194, 62, 1)',
                            'rgba(54, 185, 204, 1)',
                            'rgba(28, 200, 138, 1)'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                precision: 0
                            }
                        }
                    }
                }
            });
            
            const performanceCtx = document.getElementById('performanceChart').getContext('2d');
            const performanceChart = new Chart(performanceCtx, {
                type: 'doughnut',
                data: {
                    labels: ['Excellent (90-100%)', 'Good (70-89%)', 'Average (50-69%)', 'Poor (0-49%)'],
                    datasets: [{
                        data: [
                            <?php echo count(array_filter($results, function($r) { return $r['percentage'] >= 90; })); ?>,
                            <?php echo count(array_filter($results, function($r) { return $r['percentage'] >= 70 && $r['percentage'] < 90; })); ?>,
                            <?php echo count(array_filter($results, function($r) { return $r['percentage'] >= 50 && $r['percentage'] < 70; })); ?>,
                            <?php echo count(array_filter($results, function($r) { return $r['percentage'] < 50; })); ?>
                        ],
                        backgroundColor: [
                            'rgba(28, 200, 138, 0.7)',
                            'rgba(54, 185, 204, 0.7)',
                            'rgba(246, 194, 62, 0.7)',
                            'rgba(231, 74, 59, 0.7)'
                        ],
                        borderColor: [
                            'rgba(28, 200, 138, 1)',
                            'rgba(54, 185, 204, 1)',
                            'rgba(246, 194, 62, 1)',
                            'rgba(231, 74, 59, 1)'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom'
                        }
                    }
                }
            });
            <?php endif; ?>
        });
        
        function exportToCSV() {
            // Simple CSV export implementation
            let csv = [];
            let rows = document.querySelectorAll('#resultsTable tr');
            
            for (let i = 0; i < rows.length; i++) {
                let row = [], cols = rows[i].querySelectorAll('td, th');
                
                for (let j = 0; j < cols.length - 1; j++) { // Skip actions column
                    row.push('"' + cols[j].innerText.replace(/"/g, '""') + '"');
                }
                
                csv.push(row.join(','));
            }
            
            // Download CSV file
            let csvStr = csv.join('\n');
            let hiddenElement = document.createElement('a');
            hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvStr);
            hiddenElement.target = '_blank';
            hiddenElement.download = 'exam_results.csv';
            hiddenElement.click();
        }
    </script>
</body>
</html>