<?php
session_start();
require_once '../includes/config.php';
require_once '../includes/functions.php';

// Cek apakah user sudah login dan memiliki akses admin
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] != 'admin_soal') {
    header('Location: ../login.php');
    exit;
}

// Daftar department kedokteran gigi
$departments = [
    'bedah_mulut' => 'Bedah Mulut',
    'konservasi' => 'Konservasi Gigi',
    'periodonsia' => 'Periodonsia',
    'orthodonti' => 'Orthodonti',
    'prostodonsia' => 'Prostodonsia',
    'pedodonsia' => 'Pedodonsia',
    'radiologi' => 'Radiologi Kedokteran Gigi',
    'ilmu_kesehatan_gigi_masyarakat' => 'Ilmu Kesehatan Gigi Masyarakat',
    'ilmu_material_kedokteran_gigi' => 'Ilmu Material Kedokteran Gigi',
    'odontologi_forensik' => 'Odontologi Forensik'
];

// API endpoint untuk AJAX edit
if (isset($_GET['edit']) && $_SERVER['REQUEST_METHOD'] == 'GET') {
    $id = $_GET['edit'];
    try {
        $stmt = $pdo->prepare("SELECT * FROM aspek_penilaian_praktik WHERE id = ?");
        $stmt->execute([$id]);
        $data = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($data) {
            header('Content-Type: application/json');
            echo json_encode([
                'success' => true,
                'id' => $data['id'],
                'nomor_urut' => $data['nomor_urut'],
                'aspek_yang_dinilai' => $data['aspek_yang_dinilai'],
                'skor_dinilai' => $data['skor_dinilai'],
                'keterangan_skor' => $data['keterangan_skor'],
                'status_review' => $data['status_review'] ?? 'belum'
            ]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Data tidak ditemukan']);
        }
        exit;
    } catch (PDOException $e) {
        error_log("Error fetching edit data: " . $e->getMessage());
        echo json_encode(['success' => false, 'message' => 'Gagal mengambil data']);
        exit;
    }
}

// Ambil data unik nomor registrasi untuk filter
$nomor_registrasi_list = [];
try {
    $stmt = $pdo->query("SELECT DISTINCT nomor_registrasi FROM aspek_penilaian_praktik ORDER BY nomor_registrasi");
    $nomor_registrasi_list = $stmt->fetchAll(PDO::FETCH_COLUMN);
} catch (PDOException $e) {
    error_log("Error fetching nomor registrasi: " . $e->getMessage());
}

// Ambil parameter filter
$filter_department = $_GET['department'] ?? '';
$filter_nomor_registrasi = $_GET['nomor_registrasi'] ?? '';
$filter_status = $_GET['status'] ?? '';

// Proses update status review (AJAX)
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_status'])) {
    $id = $_POST['id'];
    $status = $_POST['status'];
    
    try {
        if ($status == 'sudah') {
            $stmt = $pdo->prepare("UPDATE aspek_penilaian_praktik 
                                  SET status_review = ?, tanggal_review = NOW(), reviewer_id = ?, updated_at = NOW()
                                  WHERE id = ?");
            $stmt->execute([$status, $_SESSION['user_id'], $id]);
        } else {
            $stmt = $pdo->prepare("UPDATE aspek_penilaian_praktik 
                                  SET status_review = ?, tanggal_review = NULL, reviewer_id = NULL, updated_at = NOW()
                                  WHERE id = ?");
            $stmt->execute([$status, $id]);
        }
        
        echo json_encode(['success' => true, 'message' => 'Status berhasil diupdate']);
        exit;
    } catch (PDOException $e) {
        error_log("Error updating status: " . $e->getMessage());
        echo json_encode(['success' => false, 'message' => 'Gagal mengupdate status: ' . $e->getMessage()]);
        exit;
    }
}

// Proses edit aspek penilaian
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['edit_aspek'])) {
    $id = $_POST['id'];
    $nomor_urut = $_POST['nomor_urut'];
    $aspek_yang_dinilai = $_POST['aspek_yang_dinilai'];
    $keterangan_skor = $_POST['keterangan_skor'];
    $skor_dinilai = implode(',', $_POST['skor_dinilai'] ?? []);
    
    try {
        $stmt = $pdo->prepare("UPDATE aspek_penilaian_praktik 
                              SET aspek_yang_dinilai = ?, skor_dinilai = ?, keterangan_skor = ?, updated_at = NOW()
                              WHERE id = ?");
        $stmt->execute([$aspek_yang_dinilai, $skor_dinilai, $keterangan_skor, $id]);
        
        $success_message = 'Aspek penilaian berhasil diperbarui!';
    } catch (PDOException $e) {
        $error = 'Gagal memperbarui data: ' . $e->getMessage();
        error_log("Error updating aspek: " . $e->getMessage());
    }
}

// Proses hapus aspek penilaian
if (isset($_GET['delete'])) {
    $id = $_GET['delete'];
    
    try {
        $stmt = $pdo->prepare("DELETE FROM aspek_penilaian_praktik WHERE id = ?");
        $stmt->execute([$id]);
        
        // Update nomor urut yang tersisa
        $stmt = $pdo->query("SET @count = 0");
        $stmt = $pdo->query("UPDATE aspek_penilaian_praktik SET nomor_urut = @count:= @count + 1 ORDER BY nomor_urut");
        
        $success_message = 'Aspek penilaian berhasil dihapus!';
        header('Location: review_aspek_penilaian.php?success=1');
        exit;
    } catch (PDOException $e) {
        $error = 'Gagal menghapus data: ' . $e->getMessage();
        error_log("Error deleting aspek: " . $e->getMessage());
    }
}

// Build query dengan filter - QUERY YANG SUDAH DIPERBAIKI
$query = "SELECT ap.*, bs.skenario_klinik, bs.department as soal_department
          FROM aspek_penilaian_praktik ap 
          LEFT JOIN bank_soal_praktik bs ON ap.nomor_registrasi = bs.nomor_registrasi 
          WHERE 1=1";
$params = [];

if (!empty($filter_department)) {
    $query .= " AND ap.department = ?";
    $params[] = $filter_department;
}

if (!empty($filter_nomor_registrasi)) {
    $query .= " AND ap.nomor_registrasi = ?";
    $params[] = $filter_nomor_registrasi;
}

if (!empty($filter_status)) {
    $query .= " AND ap.status_review = ?";
    $params[] = $filter_status;
}

$query .= " ORDER BY ap.department, ap.nomor_urut";

// Ambil data aspek penilaian dari database dengan filter
$aspek_penilaian = [];
$error = '';
try {
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $aspek_penilaian = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $error = 'Gagal mengambil data aspek penilaian: ' . $e->getMessage();
    error_log("Error fetching aspek penilaian: " . $e->getMessage());
    
    // Coba query sederhana untuk debugging
    try {
        $stmt_simple = $pdo->query("SELECT COUNT(*) as total FROM aspek_penilaian_praktik");
        $count = $stmt_simple->fetch(PDO::FETCH_ASSOC);
        error_log("Total data in aspek_penilaian_praktik: " . $count['total']);
    } catch (PDOException $e2) {
        error_log("Error counting data: " . $e2->getMessage());
    }
}

// Hitung statistik
$total_aspek = count($aspek_penilaian);
$total_departments = count(array_unique(array_column($aspek_penilaian, 'department')));
$total_soal = count(array_unique(array_column($aspek_penilaian, 'nomor_registrasi')));

// Hitung statistik status review
$total_belum_review = 0;
$total_sudah_review = 0;
foreach ($aspek_penilaian as $aspek) {
    $status = $aspek['status_review'] ?? 'belum';
    if ($status == 'sudah') {
        $total_sudah_review++;
    } else {
        $total_belum_review++;
    }
}

// Ambil nama reviewer untuk yang sudah direview (jika ada data)
$reviewer_names = [];
if ($total_sudah_review > 0) {
    try {
        $reviewer_ids = array_filter(array_column($aspek_penilaian, 'reviewer_id'));
        if (!empty($reviewer_ids)) {
            $placeholders = str_repeat('?,', count($reviewer_ids) - 1) . '?';
            $stmt_reviewers = $pdo->prepare("SELECT id, username FROM users WHERE id IN ($placeholders)");
            $stmt_reviewers->execute($reviewer_ids);
            $reviewers = $stmt_reviewers->fetchAll(PDO::FETCH_ASSOC);
            foreach ($reviewers as $reviewer) {
                $reviewer_names[$reviewer['id']] = $reviewer['username'];
            }
        }
    } catch (PDOException $e) {
        error_log("Error fetching reviewer names: " . $e->getMessage());
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Preview Aspek Penilaian - SOCA OSCE System</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="../assets/css/preview_aspek.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .status-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: bold;
            text-transform: uppercase;
            display: inline-block;
        }

        .status-sudah {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .status-belum {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .reviewer-info {
            font-size: 10px;
            color: #666;
            display: block;
            margin-top: 2px;
        }

        .review-date {
            font-size: 9px;
            color: #888;
            display: block;
        }

        .btn-status {
            padding: 4px 8px;
            font-size: 12px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="sidebar">
            <div class="sidebar-header">
                <h2>SOCA/OSCE System</h2>
                <p>Admin Panel</p>
            </div>
            <ul class="sidebar-menu">
                <li><a href="dashboard_reviewer.php"><i class="fas fa-tachometer-alt"></i> Dashboard</a></li>
                <li><a href="review_soal_teori_s1.php"><i class="fas fa-book-open"></i> Review Soal Teori S1</a></li>
                <li><a href="review_soal_teori.php"><i class="fas fa-book"></i> Review Soal Teori Profesi</a></li>
                <li><a href="review_soal_praktik.php"><i class="fas fa-clipboard-check"></i> Review Soal Praktik</a></li>
                <li><a href="review_aspek_penilaian.php" class="active"><i class="fas fa-eye"></i> Preview Aspek Penilaian</a></li>
                <li><a href="riwayat_review.php"><i class="fas fa-history"></i> Riwayat Review</a></li>
                <li><a href="panduan_review.php"><i class="fas fa-book-open"></i> Panduan Review</a></li>
                <li><a href="../logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
            </ul>
        </div>

        <div class="main-content">
            <div class="header">
                <h1>Preview Aspek Penilaian Ujian Praktik</h1>
                <div class="user-info">
                    <span><i class="fas fa-user"></i> Halo, <?php echo $_SESSION['user_name'] ?? 'Admin'; ?></span>
                    <div class="header-actions">
                        <a href="aspek_penilaian.php" class="btn btn-primary btn-sm">
                            <i class="fas fa-plus"></i> Tambah Aspek
                        </a>
                        <a href="../logout.php" class="btn btn-danger btn-sm">
                            <i class="fas fa-sign-out-alt"></i> Logout
                        </a>
                    </div>
                </div>
            </div>

            <div class="content">
                <?php if (!empty($error)): ?>
                    <div class="alert alert-danger">
                        <strong>Error:</strong> <?php echo htmlspecialchars($error); ?>
                        <?php if (strpos($error, 'bank_soal_praktik') !== false): ?>
                            <br><small>Note: Tabel bank_soal_praktik mungkin tidak ada. Sistem akan tetap berjalan tanpa informasi tambahan soal.</small>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>

                <?php if (isset($success_message)): ?>
                    <div class="alert alert-success">
                        <?php echo htmlspecialchars($success_message); ?>
                    </div>
                <?php endif; ?>

                <!-- Filter Section -->
                <div class="filter-card">
                    <div class="filter-header">
                        <h3><i class="fas fa-filter"></i> Filter Aspek Penilaian</h3>
                    </div>
                    <div class="filter-body">
                        <form method="GET" class="filter-form">
                            <div class="filter-row">
                                <div class="filter-group">
                                    <label for="filter_department"><strong>Department:</strong></label>
                                    <select id="filter_department" name="department" class="form-control">
                                        <option value="">Semua Department</option>
                                        <?php foreach ($departments as $key => $value): ?>
                                            <option value="<?php echo $key; ?>" 
                                                <?php echo $filter_department == $key ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($value); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                
                                <div class="filter-group">
                                    <label for="filter_nomor_registrasi"><strong>Nomor Registrasi:</strong></label>
                                    <select id="filter_nomor_registrasi" name="nomor_registrasi" class="form-control">
                                        <option value="">Semua Nomor Registrasi</option>
                                        <?php foreach ($nomor_registrasi_list as $nomor): ?>
                                            <option value="<?php echo $nomor; ?>" 
                                                <?php echo $filter_nomor_registrasi == $nomor ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($nomor); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                
                                <div class="filter-group">
                                    <label for="filter_status"><strong>Status Review:</strong></label>
                                    <select id="filter_status" name="status" class="form-control">
                                        <option value="">Semua Status</option>
                                        <option value="belum" <?php echo $filter_status == 'belum' ? 'selected' : ''; ?>>Belum Direview</option>
                                        <option value="sudah" <?php echo $filter_status == 'sudah' ? 'selected' : ''; ?>>Sudah Direview</option>
                                    </select>
                                </div>
                                
                                <div class="filter-actions">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-search"></i> Terapkan Filter
                                    </button>
                                    <a href="review_aspek_penilaian.php" class="btn btn-secondary">
                                        <i class="fas fa-redo"></i> Reset
                                    </a>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Filter Info -->
                <?php if (!empty($filter_department) || !empty($filter_nomor_registrasi) || !empty($filter_status)): ?>
                <div class="filter-info">
                    <strong>Filter Aktif:</strong>
                    <?php if (!empty($filter_department)): ?>
                        <span class="filter-badge">Department: <?php echo $departments[$filter_department] ?? $filter_department; ?></span>
                    <?php endif; ?>
                    <?php if (!empty($filter_nomor_registrasi)): ?>
                        <span class="filter-badge">Nomor Registrasi: <?php echo $filter_nomor_registrasi; ?></span>
                    <?php endif; ?>
                    <?php if (!empty($filter_status)): ?>
                        <span class="filter-badge">Status: <?php echo $filter_status == 'sudah' ? 'Sudah Direview' : 'Belum Direview'; ?></span>
                    <?php endif; ?>
                    <span class="filter-results">Menampilkan <?php echo $total_aspek; ?> aspek</span>
                </div>
                <?php endif; ?>

                <?php if (empty($aspek_penilaian) && empty($error)): ?>
                    <div class="empty-state">
                        <i class="fas fa-clipboard-list"></i>
                        <h3>Belum Ada Aspek Penilaian</h3>
                        <p>
                            <?php if (!empty($filter_department) || !empty($filter_nomor_registrasi) || !empty($filter_status)): ?>
                                Tidak ditemukan aspek penilaian dengan filter yang dipilih.
                            <?php else: ?>
                                Silakan tambahkan aspek penilaian terlebih dahulu
                            <?php endif; ?>
                        </p>
                        <a href="aspek_penilaian.php" class="btn btn-primary">
                            <i class="fas fa-plus"></i> Tambah Aspek Penilaian
                        </a>
                    </div>
                <?php elseif (!empty($error) && empty($aspek_penilaian)): ?>
                    <div class="empty-state">
                        <i class="fas fa-exclamation-triangle"></i>
                        <h3>Terjadi Kesalahan</h3>
                        <p><?php echo htmlspecialchars($error); ?></p>
                        <div class="action-buttons">
                            <a href="review_aspek_penilaian.php" class="btn btn-primary">
                                <i class="fas fa-redo"></i> Coba Lagi
                            </a>
                            <a href="aspek_penilaian.php" class="btn btn-secondary">
                                <i class="fas fa-plus"></i> Tambah Aspek Baru
                            </a>
                        </div>
                    </div>
                <?php else: ?>
                    <div class="preview-card">
                        <div class="preview-header">
                            <h2><i class="fas fa-table"></i> Tabel Aspek Penilaian</h2>
                            <div class="preview-actions">
                                <button onclick="window.print()" class="btn btn-outline btn-sm">
                                    <i class="fas fa-print"></i> Print
                                </button>
                                <button onclick="exportToPDF()" class="btn btn-outline btn-sm">
                                    <i class="fas fa-file-pdf"></i> Export PDF
                                </button>
                                <a href="aspek_penilaian.php" class="btn btn-primary btn-sm">
                                    <i class="fas fa-edit"></i> Edit Semua
                                </a>
                            </div>
                        </div>

                        <div class="table-responsive">
                            <table class="preview-table">
                                <thead>
                                    <tr>
                                        <th width="4%">No</th>
                                        <th width="8%">Department</th>
                                        <th width="10%">Nomor Registrasi</th>
                                        <th width="22%">Aspek yang Dinilai</th>
                                        <th width="5%">Skor 0</th>
                                        <th width="5%">Skor 1</th>
                                        <th width="5%">Skor 2</th>
                                        <th width="18%">Keterangan Skor</th>
                                        <th width="8%">Status</th>
                                        <th width="15%">Aksi</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                    $current_department = '';
                                    $current_nomor_registrasi = '';
                                    foreach ($aspek_penilaian as $aspek): 
                                        
                                        // Tampilkan header department jika berubah
                                        if ($current_department != $aspek['department'] || $current_nomor_registrasi != $aspek['nomor_registrasi']):
                                            $current_department = $aspek['department'];
                                            $current_nomor_registrasi = $aspek['nomor_registrasi'];
                                            
                                            // Ambil ID soal untuk link review
                                            $soal_id = '';
                                            try {
                                                $stmt_soal = $pdo->prepare("SELECT id FROM bank_soal_praktik WHERE nomor_registrasi = ?");
                                                $stmt_soal->execute([$aspek['nomor_registrasi']]);
                                                $soal_data = $stmt_soal->fetch(PDO::FETCH_ASSOC);
                                                $soal_id = $soal_data['id'] ?? '';
                                            } catch (PDOException $e) {
                                                $soal_id = '';
                                            }
                                    ?>
                                        <tr class="department-header-row">
                                            <td colspan="10" class="department-header-cell">
                                                <div class="department-header-content">
                                                    <div class="department-info">
                                                        <strong>
                                                            <i class="fas fa-building"></i> 
                                                            <?php echo $departments[$aspek['department']] ?? $aspek['department']; ?>
                                                            - 
                                                            <i class="fas fa-file-medical"></i>
                                                            <?php echo $aspek['nomor_registrasi']; ?>
                                                        </strong>
                                                        <?php if (!empty($aspek['skenario_klinik'])): ?>
                                                            <br><small><?php echo strip_tags(substr($aspek['skenario_klinik'], 0, 100)); ?>...</small>
                                                        <?php endif; ?>
                                                    </div>
                                                    <div class="department-actions">
                                                        <?php if (!empty($soal_id)): ?>
                                                            <a href="list_soal_praktik.php?page=1&review_id=<?php echo $soal_id; ?>" 
                                                               class="btn btn-outline btn-sm btn-view-soal"
                                                               target="_blank"
                                                               data-toggle="tooltip" title="Lihat Detail Soal">
                                                                <i class="fas fa-external-link-alt"></i> Lihat Soal
                                                            </a>
                                                        <?php endif; ?>
                                                        <button onclick="exportDepartmentToWord('<?php echo $aspek['department']; ?>', '<?php echo $aspek['nomor_registrasi']; ?>', '<?php echo addslashes($departments[$aspek['department']] ?? $aspek['department']); ?>')" 
                                                                class="btn btn-outline btn-sm btn-export-word"
                                                                data-toggle="tooltip" 
                                                                title="Export Department ke Word">
                                                            <i class="fas fa-file-word"></i> Export Word
                                                        </button>
                                                    </div>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endif; ?>

                                        <?php
                                        $skor_dinilai = explode(',', $aspek['skor_dinilai']);
                                        $has_skor_0 = in_array('0', $skor_dinilai);
                                        $has_skor_1 = in_array('1', $skor_dinilai);
                                        $has_skor_2 = in_array('2', $skor_dinilai);
                                        $status_review = $aspek['status_review'] ?? 'belum';
                                        $reviewer_name = '';
                                        if ($status_review == 'sudah' && !empty($aspek['reviewer_id'])) {
                                            $reviewer_name = $reviewer_names[$aspek['reviewer_id']] ?? 'Reviewer';
                                        }
                                        ?>
                                        <tr data-department="<?php echo $aspek['department']; ?>" data-nomor-registrasi="<?php echo $aspek['nomor_registrasi']; ?>" data-id="<?php echo $aspek['id']; ?>">
                                            <td class="text-center"><?php echo $aspek['nomor_urut']; ?></td>
                                            <td class="text-center">
                                                <span class="department-badge"><?php echo substr($aspek['department'], 0, 3); ?></span>
                                            </td>
                                            <td class="text-center">
                                                <small><?php echo $aspek['nomor_registrasi']; ?></small>
                                            </td>
                                            <td class="aspek-content">
                                                <div class="aspek-text">
                                                    <?php echo $aspek['aspek_yang_dinilai']; ?>
                                                </div>
                                            </td>
                                            <td class="text-center">
                                                <?php if ($has_skor_0): ?>
                                                    <span class="skor-check"><i class="fas fa-check"></i></span>
                                                <?php else: ?>
                                                    <span class="skor-empty">-</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-center">
                                                <?php if ($has_skor_1): ?>
                                                    <span class="skor-check"><i class="fas fa-check"></i></span>
                                                <?php else: ?>
                                                    <span class="skor-empty">-</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-center">
                                                <?php if ($has_skor_2): ?>
                                                    <span class="skor-check"><i class="fas fa-check"></i></span>
                                                <?php else: ?>
                                                    <span class="skor-empty">-</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="keterangan-content">
                                                <div class="keterangan-text">
                                                    <?php echo $aspek['keterangan_skor']; ?>
                                                </div>
                                            </td>
                                            <td class="text-center">
                                                <span class="status-badge status-<?php echo $status_review; ?>">
                                                    <?php echo $status_review == 'sudah' ? 'Sudah' : 'Belum'; ?>
                                                </span>
                                                <?php if ($status_review == 'sudah' && !empty($reviewer_name)): ?>
                                                    <br><small class="reviewer-info">Oleh: <?php echo $reviewer_name; ?></small>
                                                    <?php if (!empty($aspek['tanggal_review'])): ?>
                                                        <br><small class="review-date"><?php echo date('d/m/Y', strtotime($aspek['tanggal_review'])); ?></small>
                                                    <?php endif; ?>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-center">
                                                <div class="action-buttons">
                                                    <a href="review_aspek.php?id=<?php echo $aspek['id']; ?><?php echo !empty($filter_department) ? '&department=' . $filter_department : ''; ?><?php echo !empty($filter_nomor_registrasi) ? '&nomor_registrasi=' . $filter_nomor_registrasi : ''; ?><?php echo !empty($filter_status) ? '&status=' . $filter_status : ''; ?>" 
                                                    class="btn btn-info btn-sm btn-preview"
                                                    data-toggle="tooltip" title="Review Aspek">
                                                    <i class="fas fa-eye"></i> Review
                                                    </a>
                                                    <button onclick="toggleReviewStatus(<?php echo $aspek['id']; ?>, '<?php echo $status_review; ?>')" 
                                                            class="btn btn-<?php echo $status_review == 'sudah' ? 'warning' : 'success'; ?> btn-sm btn-status"
                                                            data-toggle="tooltip" 
                                                            title="<?php echo $status_review == 'sudah' ? 'Tandai Belum Direview' : 'Tandai Sudah Direview'; ?>">
                                                        <i class="fas fa-<?php echo $status_review == 'sudah' ? 'undo' : 'check'; ?>"></i>
                                                    </button>
                                                    <a href="review_aspek_penilaian.php?delete=<?php echo $aspek['id']; ?><?php echo !empty($filter_department) ? '&department=' . $filter_department : ''; ?><?php echo !empty($filter_nomor_registrasi) ? '&nomor_registrasi=' . $filter_nomor_registrasi : ''; ?><?php echo !empty($filter_status) ? '&status=' . $filter_status : ''; ?>" 
                                                    class="btn btn-danger btn-sm"
                                                    onclick="return confirm('Apakah Anda yakin ingin menghapus aspek ini?')"
                                                    data-toggle="tooltip" title="Hapus Aspek">
                                                    <i class="fas fa-trash"></i>
                                                    </a>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>

                        <div class="preview-footer">
                            <div class="total-aspek">
                                <strong>Total: <?php echo $total_aspek; ?> aspek</strong>
                                <?php if ($total_departments > 0): ?>
                                    <span class="stat-separator">|</span>
                                    <span><?php echo $total_departments; ?> department</span>
                                <?php endif; ?>
                                <?php if ($total_soal > 0): ?>
                                    <span class="stat-separator">|</span>
                                    <span><?php echo $total_soal; ?> soal</span>
                                <?php endif; ?>
                            </div>
                            <div class="preview-info">
                                <small>Update: <?php echo date('d/m/Y H:i'); ?></small>
                                <div class="update-time">
                                    <small>Terakhir diperbarui: <?php echo date('d/m/Y H:i'); ?></small>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Summary Cards -->
                    <div class="summary-cards">
                        <div class="summary-card">
                            <div class="summary-icon">
                                <i class="fas fa-list-ol"></i>
                            </div>
                            <div class="summary-content">
                                <h3><?php echo $total_aspek; ?></h3>
                                <p>Total Aspek</p>
                            </div>
                        </div>
                        <div class="summary-card">
                            <div class="summary-icon">
                                <i class="fas fa-building"></i>
                            </div>
                            <div class="summary-content">
                                <h3><?php echo $total_departments; ?></h3>
                                <p>Department</p>
                            </div>
                        </div>
                        <div class="summary-card">
                            <div class="summary-icon">
                                <i class="fas fa-file-medical"></i>
                            </div>
                            <div class="summary-content">
                                <h3><?php echo $total_soal; ?></h3>
                                <p>Soal Praktik</p>
                            </div>
                        </div>
                        <div class="summary-card">
                            <div class="summary-icon">
                                <i class="fas fa-check-circle"></i>
                            </div>
                            <div class="summary-content">
                                <h3><?php echo $total_sudah_review; ?></h3>
                                <p>Sudah Direview</p>
                            </div>
                        </div>
                        <div class="summary-card">
                            <div class="summary-icon">
                                <i class="fas fa-clock"></i>
                            </div>
                            <div class="summary-content">
                                <h3><?php echo $total_belum_review; ?></h3>
                                <p>Belum Direview</p>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script>
        // Fungsi untuk toggle status review
        function toggleReviewStatus(id, currentStatus) {
            const newStatus = currentStatus === 'sudah' ? 'belum' : 'sudah';
            const confirmMessage = newStatus === 'sudah' 
                ? 'Apakah Anda yakin ingin menandai aspek ini sebagai SUDAH DIREVIEW?'
                : 'Apakah Anda yakin ingin menandai aspek ini sebagai BELUM DIREVIEW?';
            
            if (!confirm(confirmMessage)) {
                return;
            }
            
            // Kirim request AJAX
            fetch('review_aspek_penilaian.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `update_status=1&id=${id}&status=${newStatus}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Reload halaman untuk update tampilan
                    location.reload();
                } else {
                    alert('Gagal mengupdate status: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Terjadi kesalahan saat mengupdate status');
            });
        }

        // Fungsi untuk export per department ke Word
        function exportDepartmentToWord(department, nomorRegistrasi, departmentName) {
            // Dapatkan semua baris yang termasuk dalam department dan nomor registrasi ini
            const rows = document.querySelectorAll(`tr[data-department="${department}"][data-nomor-registrasi="${nomorRegistrasi}"]`);
            
            if (rows.length === 0) {
                alert('Tidak ada data untuk department ini!');
                return;
            }

            // Buat tabel baru untuk department ini
            let tableHTML = `
                <table border="1" style="width: 100%; border-collapse: collapse; font-family: Arial, sans-serif; font-size: 10pt;">
                <thead>
                    <tr style="background-color: #f2f2f2;">
                        <th style="padding: 8px; border: 1px solid #000; text-align: center; width: 4%">No</th>
                        <th style="padding: 8px; border: 1px solid #000; text-align: center; width: 8%">Department</th>
                        <th style="padding: 8px; border: 1px solid #000; text-align: center; width: 12%">Nomor Registrasi</th>
                        <th style="padding: 8px; border: 1px solid #000; text-align: left; width: 26%">Aspek yang Dinilai</th>
                        <th style="padding: 8px; border: 1px solid #000; text-align: center; width: 6%">Skor 0</th>
                        <th style="padding: 8px; border: 1px solid #000; text-align: center; width: 6%">Skor 1</th>
                        <th style="padding: 8px; border: 1px solid #000; text-align: center; width: 6%">Skor 2</th>
                        <th style="padding: 8px; border: 1px solid #000; text-align: left; width: 22%">Keterangan Skor</th>
                        <th style="padding: 8px; border: 1px solid #000; text-align: center; width: 10%">Status Review</th>
                    </tr>
                </thead>
                <tbody>
            `;

            // Tambahkan setiap baris data
            rows.forEach(row => {
                const cells = row.querySelectorAll('td');
                const statusCell = cells[8]; // Kolom status
                const statusText = statusCell.querySelector('.status-badge')?.textContent.trim() || 'Belum';
                
                tableHTML += `
                    <tr>
                        <td style="padding: 6px; border: 1px solid #000; text-align: center">${cells[0].textContent}</td>
                        <td style="padding: 6px; border: 1px solid #000; text-align: center">${cells[1].textContent}</td>
                        <td style="padding: 6px; border: 1px solid #000; text-align: center">${cells[2].textContent}</td>
                        <td style="padding: 6px; border: 1px solid #000; text-align: left">${cells[3].textContent}</td>
                        <td style="padding: 6px; border: 1px solid #000; text-align: center">${cells[4].innerHTML.includes('fa-check') ? '✓' : '-'}</td>
                        <td style="padding: 6px; border: 1px solid #000; text-align: center">${cells[5].innerHTML.includes('fa-check') ? '✓' : '-'}</td>
                        <td style="padding: 6px; border: 1px solid #000; text-align: center">${cells[6].innerHTML.includes('fa-check') ? '✓' : '-'}</td>
                        <td style="padding: 6px; border: 1px solid #000; text-align: left">${cells[7].textContent}</td>
                        <td style="padding: 6px; border: 1px solid #000; text-align: center">${statusText}</td>
                    </tr>
                `;
            });

            tableHTML += '</tbody></table>';

            // Buat konten HTML lengkap
            const htmlContent = `
                <!DOCTYPE html>
                <html>
                <head>
                    <meta charset="UTF-8">
                    <title>Aspek Penilaian - ${departmentName} - ${nomorRegistrasi}</title>
                    <style>
                        body { 
                            font-family: Arial, sans-serif; 
                            font-size: 11pt; 
                            margin: 20px;
                            line-height: 1.4;
                        }
                        .header { 
                            text-align: center; 
                            margin-bottom: 20px;
                            border-bottom: 2px solid #333;
                            padding-bottom: 10px;
                        }
                        .department-title { 
                            font-size: 16pt; 
                            font-weight: bold; 
                            color: #2c3e50;
                            margin-bottom: 5px;
                        }
                        .document-info { 
                            text-align: center; 
                            margin-bottom: 15px;
                            color: #666;
                            font-size: 10pt;
                        }
                        table { 
                            width: 100%; 
                            border-collapse: collapse; 
                            margin-bottom: 20px;
                        }
                        th { 
                            background-color: #f8f9fa; 
                            font-weight: bold;
                        }
                        th, td { 
                            border: 1px solid #000; 
                            padding: 8px; 
                            text-align: left; 
                        }
                        .text-center { text-align: center; }
                        .summary {
                            margin-top: 20px;
                            padding: 10px;
                            background-color: #f8f9fa;
                            border-left: 4px solid #007bff;
                        }
                    </style>
                </head>
                <body>
                    <div class="header">
                        <div class="department-title">
                            ${departmentName} - ${nomorRegistrasi}
                        </div>
                        <div class="document-info">
                            Aspek Penilaian Praktik - SOCA OSCE System<br>
                            Total Aspek: ${rows.length} | Dibuat pada: ${new Date().toLocaleString('id-ID')}
                        </div>
                    </div>
                    
                    ${tableHTML}
                    
                    <div class="summary">
                        <strong>Summary:</strong><br>
                        - Department: ${departmentName}<br>
                        - Nomor Registrasi: ${nomorRegistrasi}<br>
                        - Total Aspek: ${rows.length}<br>
                        - Tanggal Export: ${new Date().toLocaleDateString('id-ID')}
                    </div>
                </body>
                </html>
            `;

            // Buat blob dan download
            const blob = new Blob([htmlContent], { type: 'application/msword' });
            const url = URL.createObjectURL(blob);
            
            const a = document.createElement('a');
            const timestamp = new Date().toISOString().slice(0, 19).replace(/:/g, '-');
            const fileName = `aspek-penilaian-${department}-${nomorRegistrasi}-${timestamp}.doc`
                .replace(/[^a-zA-Z0-9-]/g, '_'); // Sanitize filename
            
            a.href = url;
            a.download = fileName;
            
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }

        function exportToPDF() {
            alert('Fitur export PDF akan segera tersedia!');
        }

        // Initialize when page loads
        document.addEventListener('DOMContentLoaded', function() {
            // Auto-adjust row height
            const rows = document.querySelectorAll('.preview-table tbody tr:not(.department-header-row)');
            rows.forEach(row => {
                const aspekCell = row.querySelector('.aspek-content');
                const keteranganCell = row.querySelector('.keterangan-content');
                
                if (aspekCell && keteranganCell) {
                    const aspekHeight = aspekCell.scrollHeight;
                    const keteranganHeight = keteranganCell.scrollHeight;
                    
                    const maxHeight = Math.max(aspekHeight, keteranganHeight);
                    
                    aspekCell.style.height = maxHeight + 'px';
                    keteranganCell.style.height = maxHeight + 'px';
                }
            });
        });
    </script>
</body>
</html>