<?php

// Include manual
$root_path = dirname(__DIR__);
require_once $root_path . '/includes/auth.php';

// Koneksi database manual
try {
    $pdo = new PDO("mysql:host=localhost;dbname=soca_osce;charset=utf8", "root", "");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Koneksi database gagal: " . $e->getMessage());
}

if (!isPenguji()) {
    redirect('../login.php');
}

// CARI PENGGUJI_ID - Multiple Methods
$penguji_id = null;
$penguji_name = "Penguji";

// Method 1: Dari session penguji_id
if (!empty($_SESSION['penguji_id'])) {
    $penguji_id = $_SESSION['penguji_id'];
    echo "<!-- DEBUG: Using penguji_id from session -->";
}

// Method 2: Cari berdasarkan username (NIP) dari session
if (empty($penguji_id) && !empty($_SESSION['user_name'])) {
    echo "<!-- DEBUG: Searching by username: " . $_SESSION['user_name'] . " -->";
    $stmt = $pdo->prepare("SELECT id, nama FROM penguji WHERE nip = ?");
    $stmt->execute([$_SESSION['user_name']]);
    $penguji_data = $stmt->fetch();
    
    if ($penguji_data) {
        $penguji_id = $penguji_data['id'];
        $penguji_name = $penguji_data['nama'];
        $_SESSION['penguji_id'] = $penguji_id;
        $_SESSION['penguji_nama'] = $penguji_name;
        echo "<!-- DEBUG: Found penguji by username -->";
    } else {
        echo "<!-- DEBUG: No penguji found for username: " . $_SESSION['user_name'] . " -->";
    }
}

// Method 3: Fallback - cari semua kemungkinan
if (empty($penguji_id) && !empty($_SESSION['user_id'])) {
    echo "<!-- DEBUG: Fallback search by user_id -->";
    // Coba cari penguji dengan berbagai cara
    $stmt = $pdo->prepare("
        SELECT p.id, p.nama 
        FROM penguji p 
        WHERE p.nip IN (SELECT username FROM users WHERE id = ?)
           OR p.id = ?
    ");
    $stmt->execute([$_SESSION['user_id'], $_SESSION['user_id']]);
    $penguji_data = $stmt->fetch();
    
    if ($penguji_data) {
        $penguji_id = $penguji_data['id'];
        $penguji_name = $penguji_data['nama'];
        $_SESSION['penguji_id'] = $penguji_id;
        $_SESSION['penguji_nama'] = $penguji_name;
    }
}

// ERROR jika masih tidak ditemukan
if (empty($penguji_id)) {
    echo "<h2>Error: Data Penguji Tidak Ditemukan</h2>";
    echo "<div style='background: #f8d7da; padding: 15px; border-radius: 5px;'>";
    echo "<h3>Debug Information:</h3>";
    echo "Session user_id: " . ($_SESSION['user_id'] ?? 'NULL') . "<br>";
    echo "Session user_name: " . ($_SESSION['user_name'] ?? 'NULL') . "<br>";
    echo "Session role: " . ($_SESSION['role'] ?? 'NULL') . "<br>";
    echo "Session penguji_id: " . ($_SESSION['penguji_id'] ?? 'NULL') . "<br>";
    echo "</div>";
    exit;
}

// Ambil data penguji lengkap
$stmt = $pdo->prepare("SELECT * FROM penguji WHERE id = ?");
$stmt->execute([$penguji_id]);
$penguji = $stmt->fetch();

if (!$penguji) {
    echo "<h2>Error: Data Penguji Tidak Valid</h2>";
    echo "<p>Penguji ID: {$penguji_id} tidak ditemukan di database.</p>";
    exit;
}

// Simpan ke session
$_SESSION['penguji_id'] = $penguji['id'];
$_SESSION['penguji_nama'] = $penguji['nama'];

echo "<!-- DEBUG FINAL: penguji_id = {$penguji['id']}, penguji_name = {$penguji['nama']} -->";

// Ambil ujian aktif yang diassign ke penguji ini
$stmt = $pdo->prepare("
    SELECT DISTINCT 
        u.id as ujian_id,
        u.nama_ujian,
        u.tanggal_ujian,
        u.status,
        ps.peran
    FROM ujian u 
    INNER JOIN ujian_stations us ON u.id = us.ujian_id 
    INNER JOIN penguji_station ps ON us.station_id = ps.station_id 
    WHERE u.status = 'aktif' 
    AND ps.penguji_id = ?
    AND ps.ujian_id = u.id
    ORDER BY u.tanggal_ujian DESC
");
$stmt->execute([$penguji_id]);
$ujian_aktif = $stmt->fetchAll();

// Ambil stations untuk penguji ini
$stations = [];
if (!empty($ujian_aktif)) {
    $stmt = $pdo->prepare("
        SELECT 
            s.id as station_id,
            s.nama_station,
            us.urutan,
            u.nama_ujian,
            u.id as ujian_id,
            ps.peran
        FROM stations s
        INNER JOIN ujian_stations us ON s.id = us.station_id
        INNER JOIN penguji_station ps ON s.id = ps.station_id
        INNER JOIN ujian u ON us.ujian_id = u.id
        WHERE ps.penguji_id = ?
        AND u.status = 'aktif'
        ORDER BY us.urutan
    ");
    $stmt->execute([$penguji_id]);
    $stations = $stmt->fetchAll();
}

// DEBUG: Log data yang ditemukan
error_log("Found penguji: " . $penguji['nama'] . " (ID: " . $penguji_id . ")");
error_log("Stations assigned: " . count($stations));
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard Penguji - SOCA OSCE</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
            line-height: 1.6;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        /* Header Styles */
        .main-header {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
        }
        
        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
        }
        
        .header-title h1 {
            font-size: 2rem;
            color: #6a11cb;
            margin-bottom: 0.5rem;
            font-weight: 700;
        }
        
        .header-title .subtitle {
            color: #7f8c8d;
            font-size: 1.1rem;
            font-weight: 500;
        }
        
        .user-section {
            display: flex;
            align-items: center;
            gap: 1.5rem;
        }
        
        .user-info {
            background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
            color: white;
            padding: 1rem 1.5rem;
            border-radius: 10px;
            text-align: center;
            box-shadow: 0 4px 15px rgba(106, 17, 203, 0.3);
        }
        
        .user-info strong {
            display: block;
            font-size: 0.85rem;
            opacity: 0.9;
            margin-bottom: 0.25rem;
        }
        
        .user-name {
            font-size: 1.1rem;
            font-weight: 600;
        }
        
        .logout-btn {
            background: #e74c3c;
            color: white;
            border: none;
            padding: 0.85rem 1.5rem;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            box-shadow: 0 4px 15px rgba(231, 76, 60, 0.3);
        }
        
        .logout-btn:hover {
            background: #c0392b;
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(231, 76, 60, 0.4);
        }
        
        /* Card Styles */
        .card {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
        }
        
        .card h3 {
            color: #764ba2;
            margin-bottom: 1.5rem;
            font-size: 1.5rem;
            font-weight: 700;
            border-bottom: 3px solid #764ba2;
            padding-bottom: 0.75rem;
        }
        
        /* Station Grid */
        .station-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
            gap: 1.5rem;
            margin-top: 1.5rem;
        }
        
        .station-card {
            background: white;
            border: 2px solid #e9ecef;
            border-radius: 12px;
            padding: 1.5rem;
            transition: all 0.3s ease;
            text-decoration: none;
            color: inherit;
            display: block;
            border-left: 5px solid #6a11cb;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
        }
        
        .station-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 12px 30px rgba(106, 17, 203, 0.2);
            border-color: #6a11cb;
        }
        
        .station-header {
            margin-bottom: 1rem;
        }
        
        .station-name {
            font-size: 1.4rem;
            font-weight: 700;
            color: #2c3e50;
            margin-bottom: 0.5rem;
        }
        
        .station-ujian {
            font-size: 1.1rem;
            color: #7f8c8d;
            font-weight: 500;
        }
        
        .station-info {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1rem;
            margin: 1.5rem 0;
            padding: 1.5rem 0;
            border-top: 2px solid #f8f9fa;
            border-bottom: 2px solid #f8f9fa;
        }
        
        .info-item {
            text-align: center;
        }
        
        .info-label {
            font-size: 0.9rem;
            color: #7f8c8d;
            margin-bottom: 0.5rem;
            font-weight: 500;
        }
        
        .info-value {
            font-size: 1.2rem;
            font-weight: 700;
            color: #2c3e50;
        }
        
        .btn-action {
            display: block;
            width: 100%;
            padding: 1rem;
            background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
            color: white;
            text-align: center;
            border-radius: 8px;
            text-decoration: none;
            font-weight: 600;
            transition: all 0.3s;
            border: none;
            cursor: pointer;
            font-family: inherit;
            font-size: 1.1rem;
            box-shadow: 0 4px 15px rgba(106, 17, 203, 0.3);
        }
        
        .btn-action:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(106, 17, 203, 0.4);
        }
        
        /* Empty State */
        .empty-state {
            text-align: center;
            padding: 3rem;
            color: #7f8c8d;
        }
        
        .empty-state i {
            font-size: 4rem;
            margin-bottom: 1rem;
            color: #bdc3c7;
        }
        
        .empty-state h3 {
            color: #6a11cb;
            margin-bottom: 1rem;
            font-size: 1.5rem;
        }
        
        /* Alert Styles */
        .alert {
            padding: 1.5rem;
            border-radius: 10px;
            margin-bottom: 1.5rem;
            border-left: 5px solid;
        }
        
        .alert-info {
            background: linear-gradient(135deg, #e3f2fd 0%, #f3e5f5 100%);
            border-color: #6a11cb;
            color: #2c3e50;
        }
        
        .alert-warning {
            background: linear-gradient(135deg, #fff3e0 0%, #fce4ec 100%);
            border-color: #ff9800;
            color: #2c3e50;
        }
        
        .alert strong {
            display: block;
            margin-bottom: 0.75rem;
            font-size: 1.2rem;
            color: #6a11cb;
            font-weight: 600;
        }
        
        .alert ul {
            margin: 0.75rem 0 0 1.5rem;
            padding: 0;
        }
        
        .alert li {
            margin-bottom: 0.5rem;
            font-weight: 500;
        }
        
        /* Responsive Design */
        @media (max-width: 768px) {
            .container {
                padding: 15px;
            }
            
            .header-content {
                flex-direction: column;
                text-align: center;
            }
            
            .header-title h1 {
                font-size: 1.6rem;
            }
            
            .user-section {
                flex-direction: column;
                width: 100%;
            }
            
            .logout-btn {
                width: 100%;
                justify-content: center;
            }
            
            .station-grid {
                grid-template-columns: 1fr;
            }
            
            .station-info {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- Main Header -->
        <div class="main-header">
            <div class="header-content">
                <div class="header-title">
                    <h1>Dashboard Penguji</h1>
                    <div class="subtitle">Sistem Penilaian Objective Structured Clinical Examination</div>
                </div>
                <div class="user-section">
                    <div class="user-info">
                        <strong>Anda login sebagai:</strong>
                        <div class="user-name">
                            <?php echo htmlspecialchars($penguji['nama']); ?>
                        </div>
                    </div>
                    <button class="logout-btn" onclick="confirmLogout()">
                        <i class="fas fa-sign-out-alt"></i> Logout
                    </button>
                </div>
            </div>
        </div>

        <?php if (empty($stations)): ?>
            <div class="card">
                <div class="empty-state">
                    <i class="fas fa-clipboard-list"></i>
                    <h3>Belum Ada Assignment</h3>
                    <p>Anda belum diassign ke station manapun. Silakan hubungi administrator.</p>
                </div>
            </div>
        <?php else: ?>
            <!-- Daftar Station -->
            <div class="card">
                <h3>Station yang Diassign kepada Anda</h3>
                
                <div class="station-grid">
                    <?php foreach ($stations as $station): ?>
                        <a href="daftar_peserta.php?ujian_id=<?php echo $station['ujian_id']; ?>&station_id=<?php echo $station['station_id']; ?>" 
                           class="station-card">
                            <div class="station-header">
                                <div class="station-name"><?php echo htmlspecialchars($station['nama_station']); ?></div>
                                <div class="station-ujian"><?php echo htmlspecialchars($station['nama_ujian']); ?></div>
                            </div>
                            
                            <div class="station-info">
                                <div class="info-item">
                                    <div class="info-label">Urutan Station</div>
                                    <div class="info-value"><?php echo $station['urutan']; ?></div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Status</div>
                                    <div class="info-value" style="color: #27ae60;">Aktif</div>
                                </div>
                            </div>
                            
                            <div class="btn-action">
                                Lihat Daftar Peserta
                            </div>
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Informasi Ujian Aktif -->
            <div class="card">
                <h3>Informasi Ujian</h3>
                <div class="alert alert-info">
                    <strong>Anda terdaftar sebagai penguji pada ujian berikut:</strong>
                    <ul>
                        <?php foreach ($ujian_aktif as $ujian): ?>
                            <li>
                                <strong><?php echo htmlspecialchars($ujian['nama_ujian']); ?></strong> 
                                (<?php echo date('d/m/Y', strtotime($ujian['tanggal_ujian'])); ?>)
                                - Sebagai <?php echo ucfirst($ujian['peran'] ?? 'penguji'); ?>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            </div>
        <?php endif; ?>

        <!-- Panduan Penguji -->
        <div class="card">
            <h3>Panduan Penguji</h3>
            <div class="alert alert-warning">
                <strong>Petunjuk Penilaian:</strong>
                <ul>
                    <li>Klik pada station untuk melihat daftar peserta</li>
                    <li>Pastikan penilaian dilakukan sesuai rubrik yang telah ditentukan</li>
                    <li>Simpan penilaian setelah selesai menilai setiap peserta</li>
                    <li>Hubungi administrator jika menemui kendala teknis</li>
                </ul>
            </div>
        </div>
    </div>

    <script>
        // Tambahkan konfirmasi sebelum masuk ke daftar peserta
        document.addEventListener('DOMContentLoaded', function() {
            const stationCards = document.querySelectorAll('.station-card');
            
            stationCards.forEach(card => {
                card.addEventListener('click', function(e) {
                    const stationName = this.querySelector('.station-name').textContent;
                    const ujianName = this.querySelector('.station-ujian').textContent;
                    
                    if (!confirm(`Mulai penilaian untuk:\n${stationName}\n${ujianName}\n\nLanjutkan?`)) {
                        e.preventDefault();
                    }
                });
            });
        });

        // Fungsi logout dengan konfirmasi
        function confirmLogout() {
            if (confirm('Apakah Anda yakin ingin logout?')) {
                window.location.href = '../logout.php';
            }
        }
    </script>
</body>
</html>