<?php
require_once 'connection.php';

// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php");
    exit;
}

$username = $_SESSION['admin_username'];

// Query to get count of applicants
$sql_applicants = "SELECT COUNT(*) as total FROM pelamar";
$result_applicants = $conn->query($sql_applicants);
$row_applicants = $result_applicants->fetch_assoc();
$total_applicants = $row_applicants['total'];

// Query to get count of completed tests
$sql_completed = "SELECT COUNT(*) as total FROM hasil_tes WHERE completed_at IS NOT NULL";
$result_completed = $conn->query($sql_completed);
$row_completed = $result_completed->fetch_assoc();
$total_completed = $row_completed['total'];

// Query to get count of cheating incidents
$sql_cheating = "SELECT COUNT(*) as total FROM cheat_detection";
$result_cheating = $conn->query($sql_cheating);
$row_cheating = $result_cheating->fetch_assoc();
$total_cheating = $row_cheating['total'];

// Query to get ALL applicants (removed LIMIT 5)
$sql_all = "SELECT p.*, 
               CASE WHEN ht.completed_at IS NOT NULL THEN 'Selesai' ELSE 'Belum Selesai' END AS status_tes,
               (SELECT COUNT(*) FROM cheat_detection cd WHERE cd.id_pelamar = p.id) AS cheat_count
               FROM pelamar p
               LEFT JOIN hasil_tes ht ON p.id = ht.id_pelamar
               ORDER BY p.created_at DESC";
$result_all = $conn->query($sql_all);
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard</title>
    <link rel="icon" href="logo.jpg" type="image/jpg">
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
        }
        .container {
            width: 80%;
            margin: 0 auto;
            padding: 20px;
        }
        .header {
            background-color: #4CAF50;
            color: white;
            padding: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .welcome {
            font-size: 24px;
        }
        .logout {
            background-color: white;
            color: #4CAF50;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
            font-weight: bold;
        }
        .stats {
            background-color: white;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            margin-top: 20px;
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
        }
        .card {
            background-color: #e9f7e9;
            padding: 15px;
            border-radius: 5px;
            flex: 1;
            min-width: 200px;
        }
        .card h3 {
            margin-top: 0;
            color: #4CAF50;
        }
        .card.warning {
            background-color: #fff3e0;
        }
        .card.warning h3 {
            color: #ff9800;
        }
        .applicant-list {
            background-color: white;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            margin-top: 20px;
        }
        .table-container {
            overflow-x: auto;
            margin-top: 15px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            min-width: 800px;
        }
        table, th, td {
            border: 1px solid #ddd;
        }
        th, td {
            padding: 12px;
            text-align: left;
        }
        th {
            background-color: #4CAF50;
            color: white;
            position: sticky;
            top: 0;
        }
        tr:nth-child(even) {
            background-color: #f2f2f2;
        }
        tr:hover {
            background-color: #e8f5e8;
        }
        .btn-detail {
            background-color: #2196F3;
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 4px;
            cursor: pointer;
        }
        .btn-detail:hover {
            background-color: #0b7dda;
        }
        .status-completed {
            color: #4CAF50;
            font-weight: bold;
        }
        .status-pending {
            color: #f44336;
        }
        .cheat-count {
            display: inline-block;
            padding: 2px 6px;
            background-color: #f44336;
            color: white;
            border-radius: 50%;
            font-size: 12px;
            min-width: 18px;
            text-align: center;
            margin-left: 5px;
        }
        .applicant-summary {
            background-color: #e3f2fd;
            padding: 10px;
            border-radius: 4px;
            margin-bottom: 15px;
            border-left: 4px solid #2196F3;
        }
        
        /* Modal Styles */
        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0,0,0,0.4);
        }
        .modal-content {
            background-color: #fefefe;
            margin: 5% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
            max-width: 900px;
            border-radius: 5px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }
        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }
        .close:hover,
        .close:focus {
            color: black;
            text-decoration: none;
        }
        .tab {
            overflow: hidden;
            border: 1px solid #ccc;
            background-color: #f1f1f1;
            border-radius: 5px 5px 0 0;
        }
        .tab button {
            background-color: inherit;
            float: left;
            border: none;
            outline: none;
            cursor: pointer;
            padding: 10px 16px;
            transition: 0.3s;
            font-size: 16px;
        }
        .tab button:hover {
            background-color: #ddd;
        }
        .tab button.active {
            background-color: #4CAF50;
            color: white;
        }
        .tabcontent {
            display: none;
            padding: 20px;
            border: 1px solid #ccc;
            border-top: none;
            border-radius: 0 0 5px 5px;
        }
        .code-container {
            background-color: #f8f8f8;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 15px;
            max-height: 400px;
            overflow-y: auto;
            font-family: monospace;
            white-space: pre-wrap;
        }
        .download-btn {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            margin-top: 10px;
            display: inline-block;
            text-decoration: none;
        }
        .download-btn:hover {
            background-color: #45a049;
        }
        .applicant-info {
            margin-bottom: 20px;
            border-bottom: 1px solid #ddd;
            padding-bottom: 15px;
        }
        .screenshot-container {
            margin-top: 15px;
            text-align: center;
        }
        .screenshot-container img {
            max-width: 100%;
            max-height: 500px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .cheating-log {
            margin-top: 15px;
        }
        .cheating-table th, .cheating-table td {
            padding: 8px;
        }
        .cheating-table th {
            background-color: #f44336;
        }
        .time-tracking {
            margin-top: 15px;
        }
        .time-table th, .time-table td {
            padding: 8px;
        }
        .time-table th {
            background-color: #2196F3;
        }
        .badge {
            display: inline-block;
            padding: 3px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: bold;
            margin-left: 5px;
        }
        .badge-warning {
            background-color: #ff9800;
            color: white;
        }
        .badge-danger {
            background-color: #f44336;
            color: white;
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="welcome">Selamat datang, <?php echo htmlspecialchars($username); ?>!</div>
        <a href="logout.php" class="logout">Logout</a>
    </div>
    
    <div class="container">
        <div class="stats">
            <div class="card">
                <h3>Total Pelamar</h3>
                <p><?php echo $total_applicants; ?> pelamar terdaftar</p>
            </div>
            
            <div class="card">
                <h3>Tes Selesai</h3>
                <p><?php echo $total_completed; ?> pelamar telah menyelesaikan tes</p>
            </div>
            
            <div class="card warning">
                <h3>Indikasi Kecurangan</h3>
                <p><?php echo $total_cheating; ?> kecurangan terdeteksi</p>
            </div>
        </div>
        
        <div class="applicant-list">
            <h2>Daftar Semua Pelamar</h2>
            
            <div class="applicant-summary">
                <strong>Ringkasan:</strong> Menampilkan semua <?php echo $total_applicants; ?> pelamar yang terdaftar dalam sistem.
            </div>
            
            <?php if ($result_all->num_rows > 0): ?>
                <div class="table-container">
                    <table>
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Nama</th>
                                <th>Umur</th>
                                <th>Tanggal Kelulusan</th>
                                <th>Pendidikan</th>
                                <th>Institusi</th>
                                <th>Jurusan</th>
                                <th>Status Tes</th>
                                <th>Kecurangan</th>
                                <th>Tanggal Daftar</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $no = 1;
                            while($row = $result_all->fetch_assoc()): 
                            ?>
                                <tr>
                                    <td><?php echo $no++; ?></td>
                                    <td><?php echo htmlspecialchars($row['nama_lengkap']); ?></td>
                                    <td><?php echo $row['umur']; ?></td>
                                    <td><?php echo date('d/m/Y', strtotime($row['tanggal_kelulusan'])); ?></td>
                                    <td><?php echo htmlspecialchars($row['pendidikan']); ?></td>
                                    <td><?php echo htmlspecialchars($row['nama_institusi']); ?></td>
                                    <td>
                                        <?php echo htmlspecialchars($row['jurusan']); ?>
                                        <?php if ($row['tingkat']): ?>
                                            <br><small>(<?php echo htmlspecialchars($row['tingkat']); ?>)</small>
                                        <?php endif; ?>
                                    </td>
                                    <td class="<?php echo $row['status_tes'] == 'Selesai' ? 'status-completed' : 'status-pending'; ?>">
                                        <?php echo $row['status_tes']; ?>
                                    </td>
                                    <td>
                                        <?php if ($row['cheat_count'] > 0): ?>
                                            <span class="cheat-count"><?php echo $row['cheat_count']; ?></span>
                                        <?php else: ?>
                                            <span style="color: #4CAF50; font-weight: bold;">✓</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo date('d/m/Y H:i', strtotime($row['created_at'])); ?></td>
                                    <td>
                                        <button class="btn-detail" onclick="showDetails(<?php echo $row['id']; ?>)">Detail</button>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <p>Belum ada pelamar yang terdaftar.</p>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- Detail Modal -->
    <div id="detailModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeModal()">&times;</span>
            <div id="applicantInfo" class="applicant-info">
                <h2>Detail Pelamar</h2>
                <div id="detailLoader">Memuat data...</div>
            </div>
            
            <div class="tab">
                <button class="tablinks" onclick="openTab(event, 'tugas1part1')" id="defaultOpen">Tugas 1 (Bagian 1)</button>
                <button class="tablinks" onclick="openTab(event, 'tugas1part2')">Tugas 1 (Bagian 2)</button>
                <button class="tablinks" onclick="openTab(event, 'tugas2')">Tugas 2</button>
                <button class="tablinks" onclick="openTab(event, 'timeTracking')">Waktu Pengerjaan</button>
                <button class="tablinks" onclick="openTab(event, 'cheatingLog')">Log Kecurangan</button>
            </div>
            
            <div id="tugas1part1" class="tabcontent">
                <h3>HTML/CSS - Membuat Tampilan Dari Awal</h3>
                <div id="tugas1part1status"></div>
                <div class="code-container" id="tugas1part1code"></div>
                <a href="#" class="download-btn" id="download1part1">Unduh Kode</a>
            </div>
            
            <div id="tugas1part2" class="tabcontent">
                <h3>HTML/CSS - Memperbaiki Template</h3>
                <div id="tugas1part2status"></div>
                <div class="code-container" id="tugas1part2code"></div>
                <a href="#" class="download-btn" id="download1part2">Unduh Kode</a>
            </div>
            
            <div id="tugas2" class="tabcontent">
                <h3>Tugas Pemrograman</h3>
                <div id="tugas2status"></div>
                <div id="tugas2language"></div>
                <div class="code-container" id="tugas2code"></div>
                <a href="#" class="download-btn" id="download2">Unduh Kode</a>
                
                <div class="screenshot-container">
                    <h4>Screenshot Hasil Eksekusi:</h4>
                    <div id="screenshotContainer"></div>
                </div>
            </div>
            
            <div id="timeTracking" class="tabcontent">
                <h3>Waktu Pengerjaan</h3>
                <div class="time-tracking">
                    <table class="time-table" id="timeTable">
                        <thead>
                            <tr>
                                <th>Tugas</th>
                                <th>Waktu Mulai</th>
                                <th>Waktu Selesai</th>
                                <th>Durasi</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody id="timeTableBody">
                            <tr>
                                <td colspan="5">Memuat data...</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
            
            <div id="cheatingLog" class="tabcontent">
                <h3>Log Kecurangan</h3>
                <div class="cheating-log">
                    <table class="cheating-table" id="cheatingTable">
                        <thead>
                            <tr>
                                <th>Tugas</th>
                                <th>Tipe Kecurangan</th>
                                <th>Detail</th>
                                <th>Waktu</th>
                            </tr>
                        </thead>
                        <tbody id="cheatingTableBody">
                            <tr>
                                <td colspan="4">Memuat data...</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        // Get the modal
        var modal = document.getElementById("detailModal");
        
        // Function to show applicant details
        function showDetails(id) {
            // Show the modal
            modal.style.display = "block";
            
            // Reset tabs
            document.querySelectorAll('.tabcontent').forEach(function(content) {
                content.style.display = 'none';
            });
            
            document.querySelectorAll('.tablinks').forEach(function(tab) {
                tab.className = tab.className.replace(" active", "");
            });
            
            // Load applicant details via AJAX
            fetch('get_applicant_details.php?id=' + id)
                .then(response => response.json())
                .then(data => {
                    // Update applicant info
                    let applicantInfo = document.getElementById('applicantInfo');
                    applicantInfo.innerHTML = `
                        <h2>Detail Pelamar: ${data.nama_lengkap}</h2>
                        <p><strong>Umur:</strong> ${data.umur} tahun</p>
                        <p><strong>Pendidikan:</strong> ${data.pendidikan} - ${data.nama_institusi}</p>
                        <p><strong>Jurusan:</strong> ${data.jurusan}${data.tingkat ? ' ('+data.tingkat+')' : ''}</p>
                        <p><strong>Tanggal Kelulusan:</strong> ${data.tanggal_kelulusan}</p>
                        <p><strong>Tanggal Pendaftaran:</strong> ${data.created_at}</p>
                    `;
                    
                    // Update Tugas 1 Part 1
                    document.getElementById('tugas1part1status').innerHTML = `<p><strong>Status:</strong> ${data.tugas1_bagian1_status}</p>`;
                    document.getElementById('tugas1part1code').textContent = data.tugas1_bagian1_code || 'Tidak ada kode.';
                    
                    // Update Tugas 1 Part 2
                    document.getElementById('tugas1part2status').innerHTML = `<p><strong>Status:</strong> ${data.tugas1_bagian2_status}</p>`;
                    document.getElementById('tugas1part2code').textContent = data.tugas1_bagian2_code || 'Tidak ada kode.';
                    
                    // Update Tugas 2
                    document.getElementById('tugas2status').innerHTML = `<p><strong>Status:</strong> ${data.tugas2_status}</p>`;
                    document.getElementById('tugas2language').innerHTML = data.tugas2_language ? `<p><strong>Bahasa:</strong> ${data.tugas2_language}</p>` : '';
                    document.getElementById('tugas2code').textContent = data.tugas2_code || 'Tidak ada kode.';
                    
                    // Update screenshot
                    let screenshotContainer = document.getElementById('screenshotContainer');
                    if (data.tugas2_screenshot) {
                        screenshotContainer.innerHTML = `<img src="${data.tugas2_screenshot}" alt="Screenshot Hasil Eksekusi">`;
                    } else {
                        screenshotContainer.innerHTML = '<p>Tidak ada screenshot.</p>';
                    }
                    
                    // Update time tracking
                    updateTimeTracking(data);
                    
                    // Update cheating log
                    updateCheatingLog(id);
                    
                    // Set up download links
                    document.getElementById('download1part1').onclick = function() {
                        downloadCode(data.tugas1_bagian1_code, `tugas1_part1_${data.nama_lengkap}.html`);
                        return false;
                    };
                    
                    document.getElementById('download1part2').onclick = function() {
                        downloadCode(data.tugas1_bagian2_code, `tugas1_part2_${data.nama_lengkap}.html`);
                        return false;
                    };
                    
                    document.getElementById('download2').onclick = function() {
                        let extension = data.tugas2_language === 'Python' ? '.py' : '.cpp';
                        downloadCode(data.tugas2_code, `tugas2_${data.nama_lengkap}${extension}`);
                        return false;
                    };
                    
                    // Open the first tab by default
                    document.getElementById("defaultOpen").click();
                })
                .catch(error => {
                    console.error('Error:', error);
                    document.getElementById('applicantInfo').innerHTML = `
                        <h2>Error</h2>
                        <p>Gagal memuat data pelamar. Silakan coba lagi.</p>
                    `;
                });
        }
        
        // Function to update time tracking tab
        function updateTimeTracking(data) {
            let timeTableBody = document.getElementById('timeTableBody');
            let rows = [];
            
            // Function to calculate duration between two timestamps
            function calculateDuration(start, end) {
                if (!start || !end) return '-';
                
                const startDate = new Date(start);
                const endDate = new Date(end);
                const durationMs = endDate - startDate;
                
                if (durationMs < 0) return '-';
                
                const minutes = Math.floor(durationMs / (1000 * 60));
                const seconds = Math.floor((durationMs % (1000 * 60)) / 1000);
                
                return `${minutes} menit ${seconds} detik`;
            }
            
            // Function to get status class based on duration
            function getStatusClass(start, end) {
                if (!start || !end) return '';
                
                const startDate = new Date(start);
                const endDate = new Date(end);
                const durationMs = endDate - startDate;
                const minutes = Math.floor(durationMs / (1000 * 60));
                
                if (minutes > 15) {
                    return '<span class="badge badge-danger">Melebihi Batas</span>';
                } else if (minutes >= 13) {
                    return '<span class="badge badge-warning">Hampir Batas</span>';
                }
                
                return '';
            }
            
            // Add rows for each task
            if (data.tugas1_bagian1_start) {
                rows.push(`
                    <tr>
                        <td>Tugas 1 (Bagian 1)</td>
                        <td>${data.tugas1_bagian1_start ? new Date(data.tugas1_bagian1_start).toLocaleString() : '-'}</td>
                        <td>${data.tugas1_bagian1_end ? new Date(data.tugas1_bagian1_end).toLocaleString() : '-'}</td>
                        <td>${calculateDuration(data.tugas1_bagian1_start, data.tugas1_bagian1_end)}</td>
                        <td>${getStatusClass(data.tugas1_bagian1_start, data.tugas1_bagian1_end)}</td>
                    </tr>
                `);
            }
            
            if (data.tugas1_bagian2_start) {
                rows.push(`
                    <tr>
                        <td>Tugas 1 (Bagian 2)</td>
                        <td>${data.tugas1_bagian2_start ? new Date(data.tugas1_bagian2_start).toLocaleString() : '-'}</td>
                        <td>${data.tugas1_bagian2_end ? new Date(data.tugas1_bagian2_end).toLocaleString() : '-'}</td>
                        <td>${calculateDuration(data.tugas1_bagian2_start, data.tugas1_bagian2_end)}</td>
                        <td>${getStatusClass(data.tugas1_bagian2_start, data.tugas1_bagian2_end)}</td>
                    </tr>
                `);
            }
            
            if (data.tugas2_start) {
                rows.push(`
                    <tr>
                        <td>Tugas 2</td>
                        <td>${data.tugas2_start ? new Date(data.tugas2_start).toLocaleString() : '-'}</td>
                        <td>${data.tugas2_end ? new Date(data.tugas2_end).toLocaleString() : '-'}</td>
                        <td>${calculateDuration(data.tugas2_start, data.tugas2_end)}</td>
                        <td>${getStatusClass(data.tugas2_start, data.tugas2_end)}</td>
                    </tr>
                `);
            }
            
            // If no time tracking data available
            if (rows.length === 0) {
                rows.push(`
                    <tr>
                        <td colspan="5">Tidak ada data waktu pengerjaan.</td>
                    </tr>
                `);
            }
            
            timeTableBody.innerHTML = rows.join('');
        }
        
        // Function to update cheating log tab
        function updateCheatingLog(pelamar_id) {
            // Fetch cheating log data
            fetch('get_cheat_log.php?id=' + pelamar_id)
                .then(response => response.json())
                .then(data => {
                    let cheatingTableBody = document.getElementById('cheatingTableBody');
                    
                    if (data.length === 0) {
                        cheatingTableBody.innerHTML = `
                            <tr>
                                <td colspan="4">Tidak ada kecurangan terdeteksi.</td>
                            </tr>
                        `;
                        return;
                    }
                    
                    let rows = [];
                    
                    // Map task_type to readable names
                    const taskNames = {
                        'tugas1_bagian1': 'Tugas 1 (Bagian 1)',
                        'tugas1_bagian2': 'Tugas 1 (Bagian 2)',
                        'tugas2': 'Tugas 2'
                    };
                    
                    data.forEach(item => {
                        rows.push(`
                            <tr>
                                <td>${taskNames[item.task_type] || item.task_type}</td>
                                <td>${item.cheat_type}</td>
                                <td>${item.details || '-'}</td>
                                <td>${item.timestamp}</td>
                            </tr>
                        `);
                    });
                    
                    cheatingTableBody.innerHTML = rows.join('');
                })
                .catch(error => {
                    console.error('Error:', error);
                    document.getElementById('cheatingTableBody').innerHTML = `
                        <tr>
                            <td colspan="4">Gagal memuat data kecurangan. Silakan coba lagi.</td>
                        </tr>
                    `;
                });
        }
        
        // Function to close modal
        function closeModal() {
            modal.style.display = "none";
        }
        
        // When the user clicks anywhere outside of the modal, close it
        window.onclick = function(event) {
            if (event.target == modal) {
                modal.style.display = "none";
            }
        }
        
        // Tab function
        function openTab(evt, tabName) {
            var i, tabcontent, tablinks;
            
            // Hide all tab content
            tabcontent = document.getElementsByClassName("tabcontent");
            for (i = 0; i < tabcontent.length; i++) {
                tabcontent[i].style.display = "none";
            }
            
            // Remove active class from tab buttons
            tablinks = document.getElementsByClassName("tablinks");
            for (i = 0; i < tablinks.length; i++) {
                tablinks[i].className = tablinks[i].className.replace(" active", "");
            }
            
            // Show the current tab and add active class to the button
            document.getElementById(tabName).style.display = "block";
            evt.currentTarget.className += " active";
        }
        
        // Function to download code as text file
        function downloadCode(code, filename) {
            if (!code) {
                alert('Tidak ada kode untuk diunduh.');
                return;
            }
            
            const blob = new Blob([code], { type: 'text/plain' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.style.display = 'none';
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
        }
    </script>
</body>
</html>