<?php
require_once '../includes/auth.php';

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

// Cek role penguji
if ($_SESSION['role'] !== 'penguji') {
    header("Location: ../unauthorized.php");
    exit();
}

$penguji_id = $_SESSION['user_id'];
$success_message = "";
$error_message = "";

// Ambil data penguji yang login
try {
    $stmt = $pdo->prepare("SELECT id, nama, nip FROM penguji WHERE id = ?");
    $stmt->execute([$penguji_id]);
    $penguji = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$penguji) {
        session_destroy();
        header("Location: ../login.php");
        exit();
    }
} catch (PDOException $e) {
    die("Error mengambil data penguji: " . $e->getMessage());
}

// Ambil station yang diassign ke penguji ini
try {
    $assignedStations = $pdo->prepare("
        SELECT 
            ps.id as assignment_id,
            ps.station_id,
            ps.ujian_id,
            ps.peran,
            ps.urutan,
            s.nama_station,
            s.deskripsi,
            u.nama_ujian,
            u.tanggal_ujian
        FROM penguji_station ps
        JOIN stations s ON ps.station_id = s.id
        JOIN ujian u ON ps.ujian_id = u.id
        WHERE ps.penguji_id = ?
        ORDER BY u.tanggal_ujian DESC, ps.urutan
    ");
    $assignedStations->execute([$penguji_id]);
    $stations = $assignedStations->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    die("Error mengambil data station: " . $e->getMessage());
}

// Proses input nilai EBD
if (isset($_POST['submit_nilai_ebd'])) {
    $peserta_station_id = $_POST['peserta_station_id'];
    $peran = $_POST['peran'];
    
    // Ambil semua nilai komponen EBD
    $nilai_ask = $_POST['nilai_ask'] ?? 0;
    $nilai_acquire = $_POST['nilai_acquire'] ?? 0;
    $nilai_appraise = $_POST['nilai_appraise'] ?? 0;
    $nilai_apply = $_POST['nilai_apply'] ?? 0;
    $nilai_assess = $_POST['nilai_assess'] ?? 0;
    $catatan = $_POST['catatan'] ?? '';
    
    // Hitung total nilai
    $total_nilai = $nilai_ask + $nilai_acquire + $nilai_appraise + $nilai_apply + $nilai_assess;
    
    try {
        // Update nilai berdasarkan peran penguji
        if ($peran === 'penguji1') {
            $stmt = $pdo->prepare("
                UPDATE peserta_station 
                SET nilai_penguji1 = ?, 
                    catatan_penguji1 = ?,
                    nilai_ask_p1 = ?,
                    nilai_acquire_p1 = ?,
                    nilai_appraise_p1 = ?,
                    nilai_apply_p1 = ?,
                    nilai_assess_p1 = ?,
                    updated_at = NOW() 
                WHERE id = ?
            ");
            $stmt->execute([$total_nilai, $catatan, $nilai_ask, $nilai_acquire, $nilai_appraise, $nilai_apply, $nilai_assess, $peserta_station_id]);
        } elseif ($peran === 'penguji2') {
            $stmt = $pdo->prepare("
                UPDATE peserta_station 
                SET nilai_penguji2 = ?, 
                    catatan_penguji2 = ?,
                    nilai_ask_p2 = ?,
                    nilai_acquire_p2 = ?,
                    nilai_appraise_p2 = ?,
                    nilai_apply_p2 = ?,
                    nilai_assess_p2 = ?,
                    updated_at = NOW() 
                WHERE id = ?
            ");
            $stmt->execute([$total_nilai, $catatan, $nilai_ask, $nilai_acquire, $nilai_appraise, $nilai_apply, $nilai_assess, $peserta_station_id]);
        } elseif ($peran === 'penguji3') {
            $stmt = $pdo->prepare("
                UPDATE peserta_station 
                SET nilai_penguji3 = ?, 
                    catatan_penguji3 = ?,
                    nilai_ask_p3 = ?,
                    nilai_acquire_p3 = ?,
                    nilai_appraise_p3 = ?,
                    nilai_apply_p3 = ?,
                    nilai_assess_p3 = ?,
                    updated_at = NOW() 
                WHERE id = ?
            ");
            $stmt->execute([$total_nilai, $catatan, $nilai_ask, $nilai_acquire, $nilai_appraise, $nilai_apply, $nilai_assess, $peserta_station_id]);
        }
        
        $success_message = "Nilai EBD berhasil disimpan! Total: " . $total_nilai;
        
    } catch (PDOException $e) {
        $error_message = "Error menyimpan nilai: " . $e->getMessage();
    }
}

// Proses update status peserta
if (isset($_POST['update_status'])) {
    $peserta_station_id = $_POST['peserta_station_id'];
    $status = $_POST['status'];
    
    try {
        $stmt = $pdo->prepare("UPDATE peserta_station SET status = ?, updated_at = NOW() WHERE id = ?");
        $stmt->execute([$status, $peserta_station_id]);
        $success_message = "Status berhasil diupdate!";
    } catch (PDOException $e) {
        $error_message = "Error mengupdate status: " . $e->getMessage();
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Penilaian OSCE - SOCA System</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.0/font/bootstrap-icons.css">
    <style>
        :root {
            --primary-color: #3b5998;
            --secondary-color: #f8f9fa;
        }
        
        .sidebar {
            width: 280px;
            background: linear-gradient(to bottom, var(--primary-color), #2d4373);
            color: white;
            position: fixed;
            height: 100vh;
            overflow-y: auto;
        }
        
        .content {
            margin-left: 280px;
            padding: 30px;
            background-color: #f5f7fb;
            min-height: 100vh;
        }
        
        .page-header {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            margin-bottom: 25px;
        }
        
        .card {
            border: none;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            margin-bottom: 20px;
        }
        
        .station-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .ebd-header {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
        }
        
        .badge-status {
            font-size: 0.8rem;
            padding: 5px 10px;
        }
        
        .nilai-input {
            width: 70px;
            text-align: center;
        }
        
        .participant-card {
            transition: all 0.3s ease;
            border-left: 4px solid transparent;
        }
        
        .participant-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        }
        
        .status-badge {
            position: absolute;
            top: 10px;
            right: 10px;
        }
        
        .nilai-display {
            font-size: 1.5rem;
            font-weight: bold;
            text-align: center;
        }
        
        .ebd-component {
            border-left: 4px solid #f5576c;
            background-color: #f8f9fa;
        }
        
        .component-title {
            font-weight: 600;
            color: #495057;
            margin-bottom: 5px;
        }
        
        .component-description {
            font-size: 0.85rem;
            color: #6c757d;
        }
        
        .total-score {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            border-radius: 8px;
            padding: 15px;
            text-align: center;
        }
    </style>
</head>
<body>
    <!-- Sidebar -->
    <div class="sidebar">
        <div class="sidebar-header">
            <h4>SOCA OSCE System</h4>
            <small>Panel Penguji</small>
        </div>
        <div class="sidebar-content py-3">
            <div class="text-center mb-4">
                <div class="bg-white rounded-circle d-inline-flex align-items-center justify-content-center mb-2" style="width: 60px; height: 60px;">
                    <i class="bi bi-person-check text-primary" style="font-size: 1.5rem;"></i>
                </div>
                <h6 class="mb-1"><?= htmlspecialchars($penguji['nama']) ?></h6>
                <small class="text-muted"><?= htmlspecialchars($penguji['nip']) ?></small>
            </div>
            
            <ul class="nav flex-column">
                <li class="nav-item">
                    <a class="nav-link active" href="penilaian.php">
                        <i class="bi bi-clipboard-check me-2"></i>Penilaian
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="profile.php">
                        <i class="bi bi-person me-2"></i>Profile
                    </a>
                </li>
                <li class="nav-item mt-4">
                    <a class="nav-link" href="../logout.php">
                        <i class="bi bi-box-arrow-right me-2"></i>Logout
                    </a>
                </li>
            </ul>
        </div>
    </div>

    <!-- Main Content -->
    <div class="content">
        <!-- Page Header -->
        <div class="page-header">
            <div class="row align-items-center">
                <div class="col">
                    <h2 class="mb-0"><i class="bi bi-clipboard-check me-2"></i>Penilaian OSCE</h2>
                    <p class="text-muted mb-0">Halaman penilaian untuk <?= htmlspecialchars($penguji['nama']) ?></p>
                </div>
                <div class="col-auto">
                    <div class="bg-light rounded-pill px-3 py-1">
                        <small class="text-muted">
                            <i class="bi bi-geo-alt me-1"></i>
                            <?= count($stations) ?> Station
                        </small>
                    </div>
                </div>
            </div>
        </div>

        <!-- Alert Messages -->
        <?php if ($success_message): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="bi bi-check-circle me-2"></i><?= $success_message ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <?php if ($error_message): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="bi bi-exclamation-triangle me-2"></i><?= $error_message ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <?php if (empty($stations)): ?>
            <div class="card">
                <div class="card-body text-center py-5">
                    <i class="bi bi-inbox display-1 text-muted mb-3"></i>
                    <h4 class="text-muted">Belum Ada Assignment</h4>
                    <p class="text-muted">Anda belum diassign ke station manapun. Silakan hubungi administrator.</p>
                </div>
            </div>
        <?php else: ?>
            <!-- Station Cards -->
            <?php foreach ($stations as $station): ?>
                <div class="card">
                    <div class="card-header <?= strpos($station['nama_station'], 'EBD') !== false ? 'ebd-header' : 'station-header' ?>">
                        <div class="row align-items-center">
                            <div class="col">
                                <h5 class="card-title mb-0">
                                    <i class="bi bi-geo-alt me-2"></i>
                                    Station <?= $station['urutan'] ?>: <?= htmlspecialchars($station['nama_station']) ?>
                                </h5>
                                <small class="opacity-75">
                                    <?= htmlspecialchars($station['nama_ujian']) ?> • 
                                    <?= date('d/m/Y', strtotime($station['tanggal_ujian'])) ?>
                                </small>
                            </div>
                            <div class="col-auto">
                                <span class="badge bg-light text-dark">
                                    <i class="bi bi-person-check me-1"></i>
                                    <?= ucfirst($station['peran']) ?>
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <!-- Deskripsi Khusus untuk Station EBD -->
                        <?php if (strpos($station['nama_station'], 'EBD') !== false): ?>
                            <div class="alert alert-info">
                                <h6><i class="bi bi-info-circle me-2"></i>Scenario EBD</h6>
                                <p class="mb-0">
                                    <strong>Mahasiswa semester 6</strong> sedang menyusun skripsi tentang alternatif bahan irigasi untuk perawatan saluran akar. 
                                    Bahan yang akan diteliti adalah <strong>Propolis</strong>. Bahan ini diharapkan bisa membuat steril saluran akar seperti bahan 
                                    <em>chlorhexidine</em> yang sudah sering digunakan. Mahasiswa tersebut kemudian melakukan tahapan EBD terlebih dahulu.
                                </p>
                            </div>
                            
                            <!-- Komponen Penilaian EBD -->
                            <div class="row mb-4">
                                <div class="col-12">
                                    <h6 class="border-bottom pb-2 mb-3">Komponen Penilaian EBD (5A's)</h6>
                                </div>
                            </div>
                        <?php endif; ?>
                        
                        <?php if ($station['deskripsi']): ?>
                            <p class="text-muted mb-3"><?= htmlspecialchars($station['deskripsi']) ?></p>
                        <?php endif; ?>
                        
                        <!-- Ambil peserta yang diassign ke station ini -->
                        <?php
                        try {
                            $pesertaStmt = $pdo->prepare("
                                SELECT 
                                    ps.id as peserta_station_id,
                                    ps.peserta_id,
                                    p.nama as peserta_nama,
                                    p.nim,
                                    ps.status,
                                    ps.nilai_penguji1,
                                    ps.nilai_penguji2,
                                    ps.nilai_penguji3,
                                    ps.catatan_penguji1,
                                    ps.catatan_penguji2,
                                    ps.catatan_penguji3,
                                    ps.nilai_ask_p1,
                                    ps.nilai_acquire_p1,
                                    ps.nilai_appraise_p1,
                                    ps.nilai_apply_p1,
                                    ps.nilai_assess_p1
                                FROM peserta_station ps
                                JOIN peserta p ON ps.peserta_id = p.id
                                WHERE ps.station_id = ? AND ps.ujian_id = ?
                                ORDER BY p.nama
                            ");
                            $pesertaStmt->execute([$station['station_id'], $station['ujian_id']]);
                            $pesertaList = $pesertaStmt->fetchAll(PDO::FETCH_ASSOC);
                        } catch (PDOException $e) {
                            $pesertaList = [];
                        }
                        ?>
                        
                        <?php if (empty($pesertaList)): ?>
                            <div class="text-center py-4">
                                <i class="bi bi-people display-4 text-muted mb-3"></i>
                                <p class="text-muted">Belum ada peserta yang diassign ke station ini</p>
                            </div>
                        <?php else: ?>
                            <div class="row">
                                <?php foreach ($pesertaList as $peserta): ?>
                                    <div class="col-md-6 col-lg-4 mb-4">
                                        <div class="card participant-card h-100">
                                            <div class="card-body position-relative">
                                                <!-- Status Badge -->
                                                <span class="badge status-badge 
                                                    <?= $peserta['status'] === 'selesai' ? 'bg-success' : 
                                                       ($peserta['status'] === 'sedang_berlangsung' ? 'bg-warning' : 'bg-secondary') ?>">
                                                    <?= $peserta['status'] === 'selesai' ? 'Selesai' : 
                                                       ($peserta['status'] === 'sedang_berlangsung' ? 'Sedang Dinilai' : 'Belum Mulai') ?>
                                                </span>
                                                
                                                <!-- Info Peserta -->
                                                <h6 class="card-title"><?= htmlspecialchars($peserta['peserta_nama']) ?></h6>
                                                <p class="card-text text-muted small mb-3">
                                                    NIM: <?= htmlspecialchars($peserta['nim']) ?>
                                                </p>
                                                
                                                <?php if (strpos($station['nama_station'], 'EBD') !== false): ?>
                                                    <!-- Form Penilaian EBD -->
                                                    <form method="POST" action="" class="ebd-form">
                                                        <input type="hidden" name="peserta_station_id" value="<?= $peserta['peserta_station_id'] ?>">
                                                        <input type="hidden" name="peran" value="<?= $station['peran'] ?>">
                                                        
                                                        <!-- Komponen ASK -->
                                                        <div class="ebd-component p-3 mb-2 rounded">
                                                            <div class="component-title">ASK (0-20)</div>
                                                            <div class="component-description mb-2">
                                                                Mengidentifikasi pertanyaan klinis yang tepat berdasarkan scenario
                                                            </div>
                                                            <input type="number" class="form-control form-control-sm nilai-input" 
                                                                   name="nilai_ask" min="0" max="20" 
                                                                   value="<?= $peserta['nilai_ask_p1'] ?? 0 ?>" required>
                                                        </div>
                                                        
                                                        <!-- Komponen ACQUIRE -->
                                                        <div class="ebd-component p-3 mb-2 rounded">
                                                            <div class="component-title">ACQUIRE (0-20)</div>
                                                            <div class="component-description mb-2">
                                                                Mencari bukti ilmiah yang relevan dari sumber yang terpercaya
                                                            </div>
                                                            <input type="number" class="form-control form-control-sm nilai-input" 
                                                                   name="nilai_acquire" min="0" max="20" 
                                                                   value="<?= $peserta['nilai_acquire_p1'] ?? 0 ?>" required>
                                                        </div>
                                                        
                                                        <!-- Komponen APPRAISE -->
                                                        <div class="ebd-component p-3 mb-2 rounded">
                                                            <div class="component-title">APPRAISE (0-20)</div>
                                                            <div class="component-description mb-2">
                                                                Menilai kritis bukti yang ditemukan (validitas, reliabilitas)
                                                            </div>
                                                            <input type="number" class="form-control form-control-sm nilai-input" 
                                                                   name="nilai_appraise" min="0" max="20" 
                                                                   value="<?= $peserta['nilai_appraise_p1'] ?? 0 ?>" required>
                                                        </div>
                                                        
                                                        <!-- Komponen APPLY -->
                                                        <div class="ebd-component p-3 mb-2 rounded">
                                                            <div class="component-title">APPLY (0-20)</div>
                                                            <div class="component-description mb-2">
                                                                Mengaplikasikan bukti yang sudah diappraise ke kasus klinis
                                                            </div>
                                                            <input type="number" class="form-control form-control-sm nilai-input" 
                                                                   name="nilai_apply" min="0" max="20" 
                                                                   value="<?= $peserta['nilai_apply_p1'] ?? 0 ?>" required>
                                                        </div>
                                                        
                                                        <!-- Komponen ASSESS -->
                                                        <div class="ebd-component p-3 mb-2 rounded">
                                                            <div class="component-title">ASSESS (0-20)</div>
                                                            <div class="component-description mb-2">
                                                                Mengevaluasi outcome dari penerapan bukti tersebut
                                                            </div>
                                                            <input type="number" class="form-control form-control-sm nilai-input" 
                                                                   name="nilai_assess" min="0" max="20" 
                                                                   value="<?= $peserta['nilai_assess_p1'] ?? 0 ?>" required>
                                                        </div>
                                                        
                                                        <!-- Total Score -->
                                                        <div class="total-score mb-2">
                                                            <div class="fw-bold">TOTAL NILAI</div>
                                                            <div class="h4 mb-0" id="totalDisplay_<?= $peserta['peserta_station_id'] ?>">
                                                                <?= ($peserta['nilai_ask_p1'] ?? 0) + ($peserta['nilai_acquire_p1'] ?? 0) + 
                                                                    ($peserta['nilai_appraise_p1'] ?? 0) + ($peserta['nilai_apply_p1'] ?? 0) + 
                                                                    ($peserta['nilai_assess_p1'] ?? 0) ?>
                                                            </div>
                                                            <small>/ 100</small>
                                                        </div>
                                                        
                                                        <!-- Catatan -->
                                                        <textarea class="form-control form-control-sm mb-2" 
                                                                  name="catatan" 
                                                                  rows="2" 
                                                                  placeholder="Catatan untuk peserta..."><?= $peserta['catatan_penguji1'] ?? '' ?></textarea>
                                                        
                                                        <button type="submit" name="submit_nilai_ebd" class="btn btn-success btn-sm w-100">
                                                            <i class="bi bi-check-circle me-1"></i>Simpan Nilai EBD
                                                        </button>
                                                    </form>
                                                <?php else: ?>
                                                    <!-- Form Penilaian Regular (untuk station non-EBD) -->
                                                    <!-- ... (kode form regular seperti sebelumnya) ... -->
                                                <?php endif; ?>
                                                
                                                <!-- Update Status -->
                                                <form method="POST" action="" class="mt-2">
                                                    <input type="hidden" name="peserta_station_id" value="<?= $peserta['peserta_station_id'] ?>">
                                                    <div class="btn-group w-100">
                                                        <button type="submit" name="update_status" value="belum_mulai" 
                                                                class="btn btn-sm <?= $peserta['status'] === 'belum_mulai' ? 'btn-secondary' : 'btn-outline-secondary' ?>">
                                                            Belum
                                                        </button>
                                                        <button type="submit" name="update_status" value="sedang_berlangsung" 
                                                                class="btn btn-sm <?= $peserta['status'] === 'sedang_berlangsung' ? 'btn-warning' : 'btn-outline-warning' ?>">
                                                            Proses
                                                        </button>
                                                        <button type="submit" name="update_status" value="selesai" 
                                                                class="btn btn-sm <?= $peserta['status'] === 'selesai' ? 'btn-success' : 'btn-outline-success' ?>">
                                                            Selesai
                                                        </button>
                                                    </div>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Auto calculate total for EBD forms
        document.querySelectorAll('.ebd-form').forEach(form => {
            const inputs = form.querySelectorAll('input[type="number"]');
            const totalDisplay = form.querySelector('[id^="totalDisplay"]');
            
            function updateTotal() {
                let total = 0;
                inputs.forEach(input => {
                    total += parseInt(input.value) || 0;
                });
                if (totalDisplay) {
                    totalDisplay.textContent = total;
                    
                    // Update color based on score
                    if (total >= 80) {
                        totalDisplay.className = 'h4 mb-0 text-success';
                    } else if (total >= 60) {
                        totalDisplay.className = 'h4 mb-0 text-warning';
                    } else {
                        totalDisplay.className = 'h4 mb-0 text-danger';
                    }
                }
            }
            
            inputs.forEach(input => {
                input.addEventListener('input', updateTotal);
            });
            
            // Initial calculation
            updateTotal();
        });

        // Auto submit form ketika nilai diubah (untuk EBD)
        document.querySelectorAll('.ebd-form input[type="number"]').forEach(input => {
            input.addEventListener('change', function() {
                // Tidak auto-submit untuk EBD karena ada multiple inputs
                // User harus klik tombol submit manual
            });
        });

        // Confirmation untuk update status
        document.querySelectorAll('button[name="update_status"]').forEach(button => {
            button.addEventListener('click', function(e) {
                const status = this.value;
                const statusText = status === 'belum_mulai' ? 'Belum Mulai' : 
                                 status === 'sedang_berlangsung' ? 'Sedang Berlangsung' : 'Selesai';
                
                if (!confirm(`Ubah status menjadi "${statusText}"?`)) {
                    e.preventDefault();
                }
            });
        });

        // Real-time update indicator
        setInterval(() => {
            document.querySelectorAll('.alert').forEach(alert => {
                if (alert.classList.contains('alert-success')) {
                    setTimeout(() => {
                        alert.classList.remove('show');
                    }, 5000);
                }
            });
        }, 1000);
    </script>
</body>
</html>