<?php
require_once 'config.php';
requireLogin();

// Only admin and guru can access this page
if (!in_array($_SESSION['role'], ['admin', 'guru'])) {
    header('Location: dashboard.php?error=access_denied');
    exit();
}

// Get filter parameters
$filter_subject = $_GET['subject'] ?? '';
$filter_class = $_GET['class'] ?? '';
$filter_status = $_GET['status'] ?? '';
$filter_date_from = $_GET['date_from'] ?? '';
$filter_date_to = $_GET['date_to'] ?? '';
$export = $_GET['export'] ?? '';

// Build query based on filters and user role
$whereConditions = [];
$params = [];

if ($_SESSION['role'] === 'guru') {
    $whereConditions[] = "t.subject = ?";
    $params[] = $_SESSION['subject'];
}

if (!empty($filter_subject) && $_SESSION['role'] === 'admin') {
    $whereConditions[] = "t.subject = ?";
    $params[] = $filter_subject;
}

if (!empty($filter_class)) {
    $whereConditions[] = "u.class = ?";
    $params[] = $filter_class;
}

if (!empty($filter_status)) {
    if ($filter_status === 'dinilai') {
        $whereConditions[] = "t.grade IS NOT NULL";
    } elseif ($filter_status === 'belum_dinilai') {
        $whereConditions[] = "t.grade IS NULL";
    }
}

if (!empty($filter_date_from)) {
    $whereConditions[] = "DATE(t.submit_date) >= ?";
    $params[] = $filter_date_from;
}

if (!empty($filter_date_to)) {
    $whereConditions[] = "DATE(t.submit_date) <= ?";
    $params[] = $filter_date_to;
}

$whereClause = !empty($whereConditions) ? 'WHERE ' . implode(' AND ', $whereConditions) : '';

try {
    $query = "
        SELECT t.*, u.name as student_name, u.class as student_class, u.nis
        FROM tasks t 
        JOIN users u ON t.student_id = u.id 
        $whereClause
        ORDER BY t.submit_date DESC
    ";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $tasks = $stmt->fetchAll();
    
    // Get statistics
    $statsQuery = "
        SELECT 
            COUNT(*) as total_tasks,
            COUNT(CASE WHEN t.grade IS NOT NULL THEN 1 END) as graded_tasks,
            COUNT(CASE WHEN t.grade IS NULL THEN 1 END) as ungraded_tasks,
            AVG(CASE WHEN t.grade IS NOT NULL THEN t.grade END) as avg_grade,
            COUNT(DISTINCT t.student_id) as unique_students
        FROM tasks t 
        JOIN users u ON t.student_id = u.id 
        $whereClause
    ";
    
    $statsStmt = $pdo->prepare($statsQuery);
    $statsStmt->execute($params);
    $stats = $statsStmt->fetch();
    
    // Get subject list for filter (admin only)
    if ($_SESSION['role'] === 'admin') {
        $subjectStmt = $pdo->prepare("SELECT DISTINCT subject FROM tasks ORDER BY subject");
        $subjectStmt->execute();
        $subjects = $subjectStmt->fetchAll(PDO::FETCH_COLUMN);
    }
    
    // Get class list for filter
    $classStmt = $pdo->prepare("SELECT DISTINCT class FROM users WHERE class IS NOT NULL AND class != '' ORDER BY class");
    $classStmt->execute();
    $classes = $classStmt->fetchAll(PDO::FETCH_COLUMN);
    
} catch(PDOException $e) {
    $error = 'Database error: ' . $e->getMessage();
    $tasks = [];
    $stats = [];
}

// Handle CSV export
if ($export === 'csv') {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="laporan_tugas_' . date('Y-m-d') . '.csv"');
    
    $output = fopen('php://output', 'w');
    
    // CSV headers
    fputcsv($output, [
        'ID',
        'Nama Siswa',
        'Kelas',
        'NIS',
        'Mata Pelajaran',
        'Judul Tugas',
        'Tanggal Submit',
        'Status',
        'Nilai',
        'Ukuran File',
        'Nama File'
    ]);
    
    // CSV data
    foreach ($tasks as $task) {
        fputcsv($output, [
            $task['id'],
            $task['student_name'],
            $task['student_class'],
            $task['nis'],
            $task['subject'],
            $task['title'],
            formatDate($task['submit_date']),
            $task['grade'] ? 'Sudah Dinilai' : 'Belum Dinilai',
            $task['grade'] ?? '-',
            $task['file_size'] ? getFileSize($task['file_size']) : '-',
            $task['file_name'] ?? '-'
        ]);
    }
    
    fclose($output);
    exit();
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laporan Tugas - Sistem Pengumpulan Tugas</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body class="bg-gray-50 min-h-screen">
    <!-- Navigation -->
    <nav class="bg-white shadow-lg">
        <div class="max-w-7xl mx-auto px-4">
            <div class="flex justify-between items-center py-4">
                <div class="flex items-center">
                    <a href="dashboard.php" class="text-blue-600 hover:text-blue-800 mr-4">
                        <i class="fas fa-arrow-left text-xl"></i>
                    </a>
                    <i class="fas fa-chart-bar text-2xl text-green-600 mr-3"></i>
                    <h1 class="text-xl font-bold text-gray-800">Laporan Tugas</h1>
                </div>
                <div class="flex items-center space-x-4">
                    <span class="text-gray-600"><?php echo ucfirst($_SESSION['role']); ?>: <span class="font-medium"><?php echo htmlspecialchars($_SESSION['name']); ?></span></span>
                    <a href="logout.php" class="bg-red-500 text-white px-4 py-2 rounded-lg hover:bg-red-600 transition">
                        <i class="fas fa-sign-out-alt mr-2"></i>Logout
                    </a>
                </div>
            </div>
        </div>
    </nav>

    <div class="max-w-7xl mx-auto p-6">
        <!-- Statistics Cards -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-6 mb-8">
            <div class="bg-white rounded-xl shadow-lg p-6">
                <div class="flex items-center">
                    <div class="bg-blue-100 p-3 rounded-full">
                        <i class="fas fa-tasks text-2xl text-blue-600"></i>
                    </div>
                    <div class="ml-4">
                        <p class="text-gray-600 text-sm">Total Tugas</p>
                        <p class="text-2xl font-bold text-gray-800"><?php echo $stats['total_tasks'] ?? 0; ?></p>
                    </div>
                </div>
            </div>
            
            <div class="bg-white rounded-xl shadow-lg p-6">
                <div class="flex items-center">
                    <div class="bg-green-100 p-3 rounded-full">
                        <i class="fas fa-check-circle text-2xl text-green-600"></i>
                    </div>
                    <div class="ml-4">
                        <p class="text-gray-600 text-sm">Sudah Dinilai</p>
                        <p class="text-2xl font-bold text-gray-800"><?php echo $stats['graded_tasks'] ?? 0; ?></p>
                    </div>
                </div>
            </div>
            
            <div class="bg-white rounded-xl shadow-lg p-6">
                <div class="flex items-center">
                    <div class="bg-yellow-100 p-3 rounded-full">
                        <i class="fas fa-clock text-2xl text-yellow-600"></i>
                    </div>
                    <div class="ml-4">
                        <p class="text-gray-600 text-sm">Belum Dinilai</p>
                        <p class="text-2xl font-bold text-gray-800"><?php echo $stats['ungraded_tasks'] ?? 0; ?></p>
                    </div>
                </div>
            </div>
            
            <div class="bg-white rounded-xl shadow-lg p-6">
                <div class="flex items-center">
                    <div class="bg-purple-100 p-3 rounded-full">
                        <i class="fas fa-star text-2xl text-purple-600"></i>
                    </div>
                    <div class="ml-4">
                        <p class="text-gray-600 text-sm">Rata-rata Nilai</p>
                        <p class="text-2xl font-bold text-gray-800"><?php echo $stats['avg_grade'] ? round($stats['avg_grade'], 1) : '-'; ?></p>
                    </div>
                </div>
            </div>
            
            <div class="bg-white rounded-xl shadow-lg p-6">
                <div class="flex items-center">
                    <div class="bg-indigo-100 p-3 rounded-full">
                        <i class="fas fa-users text-2xl text-indigo-600"></i>
                    </div>
                    <div class="ml-4">
                        <p class="text-gray-600 text-sm">Siswa Aktif</p>
                        <p class="text-2xl font-bold text-gray-800"><?php echo $stats['unique_students'] ?? 0; ?></p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Filters -->
        <div class="bg-white rounded-xl shadow-lg p-6 mb-8">
            <h2 class="text-xl font-bold text-gray-800 mb-4">Filter Laporan</h2>
            
            <form method="GET" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6 gap-4">
                <?php if ($_SESSION['role'] === 'admin'): ?>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Mata Pelajaran</label>
                        <select name="subject" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500">
                            <option value="">Semua Mapel</option>
                            <?php foreach ($subjects as $subject): ?>
                                <option value="<?php echo htmlspecialchars($subject); ?>" <?php echo $filter_subject === $subject ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($subject); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                <?php endif; ?>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Kelas</label>
                    <select name="class" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500">
                        <option value="">Semua Kelas</option>
                        <?php foreach ($classes as $class): ?>
                            <option value="<?php echo htmlspecialchars($class); ?>" <?php echo $filter_class === $class ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($class); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Status</label>
                    <select name="status" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500">
                        <option value="">Semua Status</option>
                        <option value="dinilai" <?php echo $filter_status === 'dinilai' ? 'selected' : ''; ?>>Sudah Dinilai</option>
                        <option value="belum_dinilai" <?php echo $filter_status === 'belum_dinilai' ? 'selected' : ''; ?>>Belum Dinilai</option>
                    </select>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Dari Tanggal</label>
                    <input type="date" name="date_from" value="<?php echo htmlspecialchars($filter_date_from); ?>" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500">
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Sampai Tanggal</label>
                    <input type="date" name="date_to" value="<?php echo htmlspecialchars($filter_date_to); ?>" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500">
                </div>
                
                <div class="flex items-end space-x-2">
                    <button type="submit" class="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700 transition">
                        <i class="fas fa-filter mr-2"></i>Filter
                    </button>
                    <a href="?" class="bg-gray-500 text-white px-4 py-2 rounded-md hover:bg-gray-600 transition">
                        <i class="fas fa-times mr-2"></i>Reset
                    </a>
                </div>
            </form>
        </div>

        <!-- Export and Actions -->
        <div class="flex justify-between items-center mb-6">
            <h2 class="text-xl font-bold text-gray-800">Daftar Tugas</h2>
            <div class="space-x-2">
                <a href="?<?php echo http_build_query(array_merge($_GET, ['export' => 'csv'])); ?>" class="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 transition">
                    <i class="fas fa-download mr-2"></i>Export CSV
                </a>
                <button onclick="printReport()" class="bg-purple-600 text-white px-4 py-2 rounded-lg hover:bg-purple-700 transition">
                    <i class="fas fa-print mr-2"></i>Print
                </button>
            </div>
        </div>

        <!-- Tasks Table -->
        <div class="bg-white rounded-xl shadow-lg overflow-hidden">
            <div class="overflow-x-auto">
                <table class="min-w-full table-auto">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">ID</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Siswa</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Kelas</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Mata Pelajaran</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Judul Tugas</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Tanggal Submit</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Nilai</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">File</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        <?php if (empty($tasks)): ?>
                            <tr>
                                <td colspan="9" class="px-6 py-8 text-center text-gray-500">
                                    <i class="fas fa-inbox text-4xl mb-4"></i>
                                    <p>Tidak ada data tugas yang sesuai dengan filter</p>
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($tasks as $task): ?>
                                <tr class="hover:bg-gray-50">
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900"><?php echo $task['id']; ?></td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <div class="text-sm font-medium text-gray-900"><?php echo htmlspecialchars($task['student_name']); ?></div>
                                        <div class="text-sm text-gray-500">NIS: <?php echo htmlspecialchars($task['nis'] ?? '-'); ?></div>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900"><?php echo htmlspecialchars($task['student_class']); ?></td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900"><?php echo htmlspecialchars($task['subject']); ?></td>
                                    <td class="px-6 py-4 text-sm text-gray-900">
                                        <div class="font-medium"><?php echo htmlspecialchars($task['title']); ?></div>
                                        <?php if ($task['description']): ?>
                                            <div class="text-gray-500 text-xs mt-1"><?php echo htmlspecialchars(substr($task['description'], 0, 50)) . (strlen($task['description']) > 50 ? '...' : ''); ?></div>
                                        <?php endif; ?>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500"><?php echo formatDate($task['submit_date']); ?></td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full <?php echo $task['grade'] ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800'; ?>">
                                            <?php echo $task['grade'] ? 'Sudah Dinilai' : 'Belum Dinilai'; ?>
                                        </span>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                        <?php if ($task['grade']): ?>
                                            <span class="font-bold text-blue-600"><?php echo $task['grade']; ?></span>
                                        <?php else: ?>
                                            <span class="text-gray-400">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                        <?php if ($task['file_path']): ?>
                                            <div>
                                                <a href="<?php echo htmlspecialchars($task['file_path']); ?>" target="_blank" class="text-blue-600 hover:text-blue-900">
                                                    <i class="fas fa-download mr-1"></i><?php echo htmlspecialchars($task['file_name']); ?>
                                                </a>
                                                <div class="text-xs text-gray-400"><?php echo getFileSize($task['file_size']); ?></div>
                                            </div>
                                        <?php else: ?>
                                            <span class="text-gray-400">Tidak ada file</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Chart Section -->
        <?php if (!empty($tasks)): ?>
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mt-8">
                <!-- Grade Distribution Chart -->
                <div class="bg-white rounded-xl shadow-lg p-6">
                    <h3 class="text-lg font-bold text-gray-800 mb-4">Distribusi Nilai</h3>
                    <canvas id="gradeChart" width="400" height="200"></canvas>
                </div>
                
                <!-- Subject Distribution Chart -->
                <div class="bg-white rounded-xl shadow-lg p-6">
                    <h3 class="text-lg font-bold text-gray-800 mb-4">Distribusi Mata Pelajaran</h3>
                    <canvas id="subjectChart" width="400" height="200"></canvas>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <script>
        function printReport() {
            window.print();
        }

        <?php if (!empty($tasks)): ?>
        // Grade Distribution Chart
        const gradeData = <?php
            $gradeRanges = ['0-59' => 0, '60-69' => 0, '70-79' => 0, '80-89' => 0, '90-100' => 0];
            foreach ($tasks as $task) {
                if ($task['grade'] !== null) {
                    $grade = intval($task['grade']);
                    if ($grade < 60) $gradeRanges['0-59']++;
                    elseif ($grade < 70) $gradeRanges['60-69']++;
                    elseif ($grade < 80) $gradeRanges['70-79']++;
                    elseif ($grade < 90) $gradeRanges['80-89']++;
                    else $gradeRanges['90-100']++;
                }
            }
            echo json_encode($gradeRanges);
        ?>;

        const gradeCtx = document.getElementById('gradeChart').getContext('2d');
        new Chart(gradeCtx, {
            type: 'bar',
            data: {
                labels: Object.keys(gradeData),
                datasets: [{
                    label: 'Jumlah Siswa',
                    data: Object.values(gradeData),
                    backgroundColor: ['#ef4444', '#f97316', '#eab308', '#22c55e', '#3b82f6']
                }]
            },
            options: {
                responsive: true,
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            stepSize: 1
                        }
                    }
                }
            }
        });

        // Subject Distribution Chart
        const subjectData = <?php
            $subjectCount = [];
            foreach ($tasks as $task) {
                $subject = $task['subject'];
                $subjectCount[$subject] = ($subjectCount[$subject] ?? 0) + 1;
            }
            echo json_encode($subjectCount);
        ?>;

        const subjectCtx = document.getElementById('subjectChart').getContext('2d');
        new Chart(subjectCtx, {
            type: 'doughnut',
            data: {
                labels: Object.keys(subjectData),
                datasets: [{
                    data: Object.values(subjectData),
                    backgroundColor: ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#06b6d4', '#84cc16']
                }]
            },
            options: {
                responsive: true
            }
        });
        <?php endif; ?>
    </script>
</body>
</html>