<?php
session_start();
if (!isset($_SESSION['username']) || $_SESSION['role'] !== 'admin') {
    header("Location: index.php");
    exit;
}

include 'config.php';

// Filter data
$filter_tanggal = isset($_GET['tanggal']) ? $_GET['tanggal'] : '';
$filter_kelas = isset($_GET['kelas']) ? $_GET['kelas'] : '';
$filter_status = isset($_GET['status']) ? $_GET['status'] : '';

// Query data bimbingan konseling
$query = "SELECT bk.*, s.nama as siswa_nama, s.kelas, s.nis, 
                 wk.nama_wali as wali_nama
          FROM bimbingan_konseling bk 
          JOIN siswa s ON bk.siswa_id = s.id 
          LEFT JOIN wali_kelas wk ON s.kelas = wk.kelas 
          WHERE 1=1";

$params = [];
if (!empty($filter_tanggal)) {
    $query .= " AND DATE(bk.tanggal) = ?";
    $params[] = $filter_tanggal;
}
if (!empty($filter_kelas)) {
    $query .= " AND s.kelas = ?";
    $params[] = $filter_kelas;
}
if (!empty($filter_status)) {
    $query .= " AND bk.status = ?";
    $params[] = $filter_status;
}

$query .= " ORDER BY bk.tanggal DESC, bk.created_at DESC";

// Eksekusi query
$bimbingan = [];
if (!empty($params)) {
    $stmt = mysqli_prepare($conn, $query);
    if ($stmt) {
        $types = str_repeat('s', count($params));
        mysqli_stmt_bind_param($stmt, $types, ...$params);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        while ($row = mysqli_fetch_assoc($result)) {
            $bimbingan[] = $row;
        }
    }
} else {
    $result = mysqli_query($conn, $query);
    while ($row = mysqli_fetch_assoc($result)) {
        $bimbingan[] = $row;
    }
}

// Hitung statistik
$total_bimbingan = count($bimbingan);
$status_count = array_count_values(array_column($bimbingan, 'status'));

// Query untuk filter kelas
$kelas_query = mysqli_query($conn, "SELECT DISTINCT kelas FROM siswa ORDER BY kelas");

// Query untuk mendapatkan data sekolah
$sekolah_query = mysqli_query($conn, "SELECT nama_sekolah, alamat, kepala_sekolah, nip_kepala FROM profil_sekolah LIMIT 1");
$sekolah_data = mysqli_fetch_assoc($sekolah_query);

// PROSES CETAK PDF
if (isset($_GET['cetak']) && $_GET['cetak'] == 'pdf') {
    require('fpdf/fpdf.php');
    
    class PDF extends FPDF {
        // Header
        function Header() {
            global $sekolah_data, $filter_tanggal, $filter_kelas, $filter_status;
            
            // Judul
            $this->SetFont('Arial','B',14);
            $this->Cell(0,6,strtoupper($sekolah_data['nama_sekolah'] ?? 'SEKOLAH'),0,1,'C');
            $this->SetFont('Arial','B',12);
            $this->Cell(0,6,'LAPORAN BIMBINGAN KONSELING SISWA',0,1,'C');
            
            // Informasi sekolah
            $this->SetFont('Arial','',9);
            $this->Cell(0,4,'Alamat: ' . ($sekolah_data['alamat'] ?? '-'),0,1,'C');
            
            // Filter info
            $this->SetFont('Arial','I',8);
            $filter_info = 'Periode: ';
            if ($filter_tanggal) {
                $filter_info .= date('d/m/Y', strtotime($filter_tanggal));
            } else {
                $filter_info .= 'Semua Tanggal';
            }
            
            if ($filter_kelas) {
                $filter_info .= ' | Kelas: ' . $filter_kelas;
            }
            if ($filter_status) {
                $filter_info .= ' | Status: ' . ucfirst($filter_status);
            }
            
            $this->Cell(0,4,$filter_info,0,1,'C');
            $this->Ln(5);
        }
        
        // Footer
        function Footer() {
            $this->SetY(-15);
            $this->SetFont('Arial','I',8);
            $this->Cell(0,10,'Halaman ' . $this->PageNo() . ' dari {nb}',0,0,'C');
        }
        
        // Function untuk membuat tabel dengan border yang rapi
        function ImprovedTable($header, $data) {
            // Lebar kolom disesuaikan untuk data BK
            $w = array(10, 25, 45, 15, 40, 50, 35, 25);
            
            // Header
            $this->SetFillColor(200, 220, 255); // Biru muda
            $this->SetTextColor(0);
            $this->SetDrawColor(150, 150, 150);
            $this->SetLineWidth(.3);
            $this->SetFont('Arial','B',8);
            
            for($i=0;$i<count($header);$i++)
                $this->Cell($w[$i],7,$header[$i],1,0,'C',true);
            $this->Ln();
            
            // Data
            $this->SetFillColor(255, 255, 255);
            $this->SetTextColor(0);
            $this->SetFont('Arial','',8);
            
            $fill = false;
            $row_height = 6;
            
            foreach($data as $row) {
                // Cek jika halaman penuh
                if($this->GetY() > 180) {
                    $this->AddPage();
                    // Header tabel baru
                    $this->SetFillColor(200, 220, 255);
                    $this->SetFont('Arial','B',8);
                    for($i=0;$i<count($header);$i++)
                        $this->Cell($w[$i],7,$header[$i],1,0,'C',true);
                    $this->Ln();
                    $this->SetFont('Arial','',8);
                }
                
                // Hitung tinggi baris berdasarkan konten terpanjang
                $nb = 0;
                for($i=0;$i<count($row);$i++) {
                    if($i == 4 || $i == 5) { // Kolom topik dan keterangan
                        $nb = max($nb, $this->NbLines($w[$i], $row[$i]));
                    }
                }
                $h = $row_height * max($nb, 1);
                
                // Baris pertama
                $x = $this->GetX();
                $y = $this->GetY();
                
                // Cell 1: No
                $this->MultiCell($w[0], $h, $row[0], 1, 'C', $fill);
                $this->SetXY($x + $w[0], $y);
                
                // Cell 2: Tanggal
                $this->MultiCell($w[1], $h, $row[1], 1, 'C', $fill);
                $this->SetXY($x + $w[0] + $w[1], $y);
                
                // Cell 3: Siswa
                $this->MultiCell($w[2], $h, $row[2], 1, 'L', $fill);
                $this->SetXY($x + $w[0] + $w[1] + $w[2], $y);
                
                // Cell 4: Kelas
                $this->MultiCell($w[3], $h, $row[3], 1, 'C', $fill);
                $this->SetXY($x + $w[0] + $w[1] + $w[2] + $w[3], $y);
                
                // Cell 5: Topik
                $this->MultiCell($w[4], $h, $row[4], 1, 'L', $fill);
                $this->SetXY($x + $w[0] + $w[1] + $w[2] + $w[3] + $w[4], $y);
                
                // Cell 6: Keterangan
                $this->MultiCell($w[5], $h, $row[5], 1, 'L', $fill);
                $this->SetXY($x + $w[0] + $w[1] + $w[2] + $w[3] + $w[4] + $w[5], $y);
                
                // Cell 7: Wali Kelas
                $this->MultiCell($w[6], $h, $row[6], 1, 'L', $fill);
                $this->SetXY($x + $w[0] + $w[1] + $w[2] + $w[3] + $w[4] + $w[5] + $w[6], $y);
                
                // Cell 8: Status dengan warna
                $status = $row[7];
                $status_color = $this->getStatusColor($status);
                $this->SetFillColor($status_color[0], $status_color[1], $status_color[2]);
                $this->MultiCell($w[7], $h, ucfirst($status), 1, 'C', true);
                $this->SetFillColor(255, 255, 255);
                
                $this->SetXY($x, $y + $h);
                $fill = !$fill;
            }
        }
        
        // Function untuk mendapatkan warna berdasarkan status
        function getStatusColor($status) {
            switch($status) {
                case 'pending':
                    return array(255, 193, 7); // Kuning
                case 'approved':
                    return array(23, 162, 184); // Biru
                case 'completed':
                    return array(40, 167, 69); // Hijau
                case 'rejected':
                    return array(220, 53, 69); // Merah
                default:
                    return array(200, 200, 200); // Abu-abu
            }
        }
        
        // Function untuk menghitung jumlah baris dalam MultiCell
        function NbLines($w, $txt) {
            $cw = &$this->CurrentFont['cw'];
            if($w==0)
                $w=$this->w-$this->rMargin-$this->x;
            $wmax = ($w-2*$this->cMargin)*1000/$this->FontSize;
            $s = str_replace("\r",'', $txt);
            $nb = strlen($s);
            if($nb>0 && $s[$nb-1]=="\n")
                $nb--;
            $sep = -1;
            $i = 0;
            $j = 0;
            $l = 0;
            $nl = 1;
            while($i<$nb) {
                $c = $s[$i];
                if($c=="\n") {
                    $i++;
                    $sep = -1;
                    $j = $i;
                    $l = 0;
                    $nl++;
                    continue;
                }
                if($c==' ')
                    $sep=$i;
                $l += $cw[$c];
                if($l>$wmax) {
                    if($sep==-1) {
                        if($i==$j)
                            $i++;
                    } else
                        $i = $sep+1;
                    $sep = -1;
                    $j = $i;
                    $l = 0;
                    $nl++;
                } else
                    $i++;
            }
            return $nl;
        }
    }
    
    // Buat PDF dengan orientasi landscape
    $pdf = new PDF('L','mm','A4');
    $pdf->AliasNbPages();
    $pdf->AddPage();
    
    // Header informasi
    $pdf->SetFont('Arial','B',10);
    $pdf->Cell(0,8,'STATISTIK: Total Sesi: ' . $total_bimbingan,0,1,'L');
    
    // Tampilkan statistik status
    $status_stats = '';
    if(isset($status_count['pending'])) $status_stats .= 'Pending: ' . $status_count['pending'] . ' | ';
    if(isset($status_count['approved'])) $status_stats .= 'Approved: ' . $status_count['approved'] . ' | ';
    if(isset($status_count['completed'])) $status_stats .= 'Completed: ' . $status_count['completed'] . ' | ';
    if(isset($status_count['rejected'])) $status_stats .= 'Rejected: ' . $status_count['rejected'];
    $status_stats = rtrim($status_stats, ' | ');
    
    $pdf->SetFont('Arial','',9);
    $pdf->Cell(0,6,'Status: ' . $status_stats,0,1,'L');
    $pdf->Cell(0,6,'Dicetak pada: ' . date('d/m/Y H:i:s') . ' oleh ' . $_SESSION['username'],0,1,'L');
    $pdf->Ln(5);
    
    // Header tabel
    $header = array('No', 'Tanggal', 'Siswa (NIS)', 'Kelas', 'Topik', 'Keterangan', 'Wali Kelas', 'Status');
    
    // Siapkan data untuk tabel
    $data = array();
    $no = 1;
    
    foreach ($bimbingan as $row) {
        $siswa_info = $row['siswa_nama'] . "\nNIS: " . $row['nis'];
        $tanggal_info = date('d/m/Y', strtotime($row['tanggal'])) . "\n" . date('H:i', strtotime($row['created_at']));
        
        // Batasi panjang teks untuk menjaga kerapian
        $topik = (strlen($row['topik']) > 40) ? substr($row['topik'], 0, 37) . '...' : $row['topik'];
        $keterangan = (strlen($row['keterangan']) > 70) ? substr($row['keterangan'], 0, 67) . '...' : $row['keterangan'];
        $catatan_guru = (isset($row['catatan_guru']) && strlen($row['catatan_guru']) > 40) ? 
            substr($row['catatan_guru'], 0, 37) . '...' : ($row['catatan_guru'] ?? '-');
        
        $wali_info = $row['wali_nama'] ?: '-';
        
        $data[] = array(
            $no++,
            $tanggal_info,
            $siswa_info,
            $row['kelas'],
            $topik,
            $keterangan,
            $wali_info,
            $row['status']
        );
    }
    
    // Buat tabel
    if (!empty($data)) {
        $pdf->ImprovedTable($header, $data);
    } else {
        $pdf->SetFont('Arial','I',10);
        $pdf->Cell(0,10,'Tidak ada data bimbingan konseling',1,1,'C');
    }
    
    // Tanda tangan
    $pdf->Ln(10);
    $pdf->SetFont('Arial','',9);
    $pdf->Cell(0,5,'Mengetahui,',0,1,'R');
    $pdf->Ln(15);
    $pdf->SetFont('Arial','B',10);
    $pdf->Cell(0,5,'(' . ($sekolah_data['kepala_sekolah'] ?? 'Kepala Sekolah') . ')',0,1,'R');
    
    // Output PDF
    $pdf->Output('Laporan_Bimbingan_Konseling_' . date('Ymd_His') . '.pdf', 'D');
    exit;
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Riwayat Bimbingan Konseling - Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
    <style>
        .table-responsive {
            max-height: 600px;
            overflow-y: auto;
        }
        .badge-pending {
            background: #ffc107;
            color: #000;
        }
        .badge-approved {
            background: #17a2b8;
            color: #fff;
        }
        .badge-completed {
            background: #28a745;
            color: #fff;
        }
        .badge-rejected {
            background: #dc3545;
            color: #fff;
        }
        .stat-card {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
            text-align: center;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            transition: transform 0.3s;
        }
        .stat-card:hover {
            transform: translateY(-5px);
        }
        .btn-pdf {
            background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
            border: none;
            color: white;
        }
        .btn-pdf:hover {
            background: linear-gradient(135deg, #c82333 0%, #bd2130 100%);
            color: white;
        }
        .table-hover tbody tr:hover {
            background-color: rgba(0,123,255,.05);
        }
        .print-header {
            display: none;
        }
        @media print {
            .no-print {
                display: none !important;
            }
            .print-header {
                display: block;
                text-align: center;
                margin-bottom: 20px;
                border-bottom: 2px solid #000;
                padding-bottom: 10px;
            }
        }
    </style>
</head>
<body class="container py-4">
    <div class="print-header">
        <h2><?php echo $sekolah_data['nama_sekolah'] ?? 'Sekolah'; ?></h2>
        <h4>Laporan Bimbingan Konseling Siswa</h4>
        <p>Alamat: <?php echo $sekolah_data['alamat'] ?? '-'; ?></p>
        <p>Periode: <?php 
            if($filter_tanggal) {
                echo date('d/m/Y', strtotime($filter_tanggal));
            } elseif($filter_kelas || $filter_status) {
                echo 'Filter: ';
                if($filter_kelas) echo "Kelas $filter_kelas ";
                if($filter_status) echo "Status " . ucfirst($filter_status);
            } else {
                echo 'Semua Data';
            }
        ?></p>
        <p>Dicetak: <?php echo date('d/m/Y H:i:s'); ?></p>
    </div>

    <h2 class="text-center mb-4"><i class="fas fa-hands-helping"></i> Riwayat Bimbingan Konseling</h2>

    <div class="no-print">
        <a href="dashboard.php" class="btn btn-secondary mb-3"><i class="fas fa-arrow-left"></i> Kembali ke Dashboard</a>
        
        <!-- Tombol Cetak -->
        <div class="mb-3">
            <button onclick="window.print()" class="btn btn-primary">
                <i class="fas fa-print"></i> Cetak Halaman
            </button>
            <a href="?cetak=pdf&tanggal=<?php echo $filter_tanggal; ?>&kelas=<?php echo $filter_kelas; ?>&status=<?php echo $filter_status; ?>" 
               class="btn btn-pdf">
                <i class="fas fa-file-pdf"></i> Cetak PDF
            </a>
            <span class="ms-3 text-muted">
                <i class="fas fa-info-circle"></i> Total: <?php echo $total_bimbingan; ?> sesi bimbingan
            </span>
        </div>
    </div>

    <!-- Statistik -->
    <div class="row mb-4">
        <div class="col-md-2">
            <div class="stat-card">
                <h4><?php echo $total_bimbingan; ?></h4>
                <small>Total Sesi</small>
            </div>
        </div>
        <div class="col-md-2">
            <div class="stat-card" style="background: linear-gradient(135deg, #ffc107 0%, #ff9800 100%);">
                <h4><?php echo $status_count['pending'] ?? 0; ?></h4>
                <small>Pending</small>
            </div>
        </div>
        <div class="col-md-2">
            <div class="stat-card" style="background: linear-gradient(135deg, #17a2b8 0%, #138496 100%);">
                <h4><?php echo $status_count['approved'] ?? 0; ?></h4>
                <small>Approved</small>
            </div>
        </div>
        <div class="col-md-2">
            <div class="stat-card" style="background: linear-gradient(135deg, #28a745 0%, #1e7e34 100%);">
                <h4><?php echo $status_count['completed'] ?? 0; ?></h4>
                <small>Completed</small>
            </div>
        </div>
        <div class="col-md-2">
            <div class="stat-card" style="background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);">
                <h4><?php echo $status_count['rejected'] ?? 0; ?></h4>
                <small>Rejected</small>
            </div>
        </div>
        <div class="col-md-2">
            <div class="stat-card" style="background: linear-gradient(135deg, #6c757d 0%, #5a6268 100%);">
                <h4><?php echo date('d/m/Y'); ?></h4>
                <small>Hari Ini</small>
            </div>
        </div>
    </div>

    <!-- Filter Form -->
    <div class="card mb-4 no-print">
        <div class="card-header bg-light">
            <h5 class="mb-0"><i class="fas fa-filter"></i> Filter Data</h5>
        </div>
        <div class="card-body">
            <form method="GET" class="row g-3">
                <div class="col-md-3">
                    <label for="tanggal" class="form-label">Tanggal</label>
                    <input type="date" class="form-control" id="tanggal" name="tanggal" 
                           value="<?php echo $filter_tanggal; ?>">
                </div>
                <div class="col-md-3">
                    <label for="kelas" class="form-label">Kelas</label>
                    <select class="form-select" id="kelas" name="kelas">
                        <option value="">Semua Kelas</option>
                        <?php 
                        // Reset pointer query
                        mysqli_data_seek($kelas_query, 0);
                        while($kelas = mysqli_fetch_assoc($kelas_query)): ?>
                            <option value="<?php echo $kelas['kelas']; ?>" 
                                    <?php echo $filter_kelas == $kelas['kelas'] ? 'selected' : ''; ?>>
                                <?php echo $kelas['kelas']; ?>
                            </option>
                        <?php endwhile; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label for="status" class="form-label">Status</label>
                    <select class="form-select" id="status" name="status">
                        <option value="">Semua Status</option>
                        <option value="pending" <?php echo $filter_status == 'pending' ? 'selected' : ''; ?>>Pending</option>
                        <option value="approved" <?php echo $filter_status == 'approved' ? 'selected' : ''; ?>>Approved</option>
                        <option value="completed" <?php echo $filter_status == 'completed' ? 'selected' : ''; ?>>Completed</option>
                        <option value="rejected" <?php echo $filter_status == 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                    </select>
                </div>
                <div class="col-md-3 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-search"></i> Filter Data
                    </button>
                </div>
            </form>
            <?php if($filter_tanggal || $filter_kelas || $filter_status): ?>
            <div class="mt-3">
                <a href="riwayat_bimbingan.php" class="btn btn-sm btn-outline-secondary">
                    <i class="fas fa-times"></i> Hapus Filter
                </a>
                <small class="text-muted ms-2">
                    Filter aktif: 
                    <?php if($filter_tanggal) echo "Tanggal: " . date('d/m/Y', strtotime($filter_tanggal)) . " "; ?>
                    <?php if($filter_kelas) echo "Kelas: $filter_kelas "; ?>
                    <?php if($filter_status) echo "Status: " . ucfirst($filter_status); ?>
                </small>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Tabel Riwayat BK -->
    <div class="card">
        <div class="card-header bg-info text-white d-flex justify-content-between align-items-center">
            <div>
                <i class="fas fa-history"></i> <strong>Data Bimbingan Konseling</strong>
                <span class="badge bg-light text-dark ms-2"><?php echo $total_bimbingan; ?> Sesi</span>
            </div>
            <div class="text-white small">
                <i class="fas fa-clock"></i> <?php echo date('d/m/Y H:i:s'); ?>
            </div>
        </div>
        <div class="card-body p-0">
            <?php if (empty($bimbingan)): ?>
                <div class="text-center text-muted py-4">
                    <i class="fas fa-comments fa-2x mb-2"></i><br>
                    <strong>Belum ada data bimbingan konseling</strong>
                    <p class="text-muted mt-2">Coba gunakan filter yang berbeda</p>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-bordered table-striped table-hover table-sm mb-0">
                        <thead class="table-light">
                            <tr>
                                <th width="5%" class="text-center">No</th>
                                <th width="10%">Tanggal</th>
                                <th width="15%">Siswa</th>
                                <th width="10%">Kelas</th>
                                <th width="15%">Topik</th>
                                <th width="20%">Keterangan</th>
                                <th width="15%">Wali Kelas</th>
                                <th width="10%" class="text-center">Status</th>
                                <th width="10%" class="text-center no-print">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($bimbingan as $index => $data): ?>
                                <tr>
                                    <td class="text-center"><?php echo $index + 1; ?></td>
                                    <td>
                                        <strong><?php echo date('d/m/Y', strtotime($data['tanggal'])); ?></strong>
                                        <br><small class="text-muted"><?php echo date('H:i', strtotime($data['created_at'])); ?></small>
                                    </td>
                                    <td>
                                        <strong><?php echo $data['siswa_nama']; ?></strong>
                                        <br><small class="text-muted">NIS: <?php echo $data['nis']; ?></small>
                                    </td>
                                    <td><span class="badge bg-info"><?php echo $data['kelas']; ?></span></td>
                                    <td><?php echo htmlspecialchars($data['topik']); ?></td>
                                    <td>
                                        <small><?php echo htmlspecialchars($data['keterangan']); ?></small>
                                        <?php if (!empty($data['catatan_guru'])): ?>
                                            <br><small class="text-success"><i class="fas fa-sticky-note"></i> Catatan: <?php echo htmlspecialchars($data['catatan_guru']); ?></small>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if($data['wali_nama']): ?>
                                            <i class="fas fa-user-tie text-primary"></i> <?php echo $data['wali_nama']; ?>
                                        <?php else: ?>
                                            <span class="text-muted">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-center">
                                        <span class="badge badge-<?php echo $data['status']; ?> p-2">
                                            <i class="fas fa-<?php 
                                                switch($data['status']) {
                                                    case 'pending': echo 'clock'; break;
                                                    case 'approved': echo 'check-circle'; break;
                                                    case 'completed': echo 'check-double'; break;
                                                    case 'rejected': echo 'times-circle'; break;
                                                    default: echo 'question-circle';
                                                }
                                            ?>"></i>
                                            <?php echo ucfirst($data['status']); ?>
                                        </span>
                                    </td>
                                    <td class="text-center no-print">
                                        <div class="btn-group btn-group-sm" role="group">
                                            <button type="button" class="btn btn-info" 
                                                    onclick="viewBKDetails(<?php echo $data['id']; ?>)"
                                                    title="Lihat Detail">
                                                <i class="fas fa-eye"></i>
                                            </button>
                                            <?php if ($data['status'] == 'pending'): ?>
                                                <button type="button" class="btn btn-success"
                                                        onclick="updateStatus(<?php echo $data['id']; ?>, 'approved')"
                                                        title="Setujui">
                                                    <i class="fas fa-check"></i>
                                                </button>
                                                <button type="button" class="btn btn-danger"
                                                        onclick="updateStatus(<?php echo $data['id']; ?>, 'rejected')"
                                                        title="Tolak">
                                                    <i class="fas fa-times"></i>
                                                </button>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
        <div class="card-footer text-muted no-print">
            <small><i class="fas fa-info-circle"></i> Menampilkan <?php echo count($bimbingan); ?> dari <?php echo $total_bimbingan; ?> data bimbingan konseling</small>
        </div>
    </div>

    <div class="mt-4 no-print">
        <div class="alert alert-info">
            <h5><i class="fas fa-file-pdf"></i> Catatan Cetak PDF:</h5>
            <ul class="mb-0">
                <li>PDF akan dibuat dalam format landscape untuk tabel yang lebih lebar</li>
                <li>File PDF akan otomatis terdownload dengan format: <code>Laporan_Bimbingan_Konseling_TGL_JAM.pdf</code></li>
                <li>Tabel dalam PDF memiliki warna status yang sesuai:
                    <span class="badge badge-pending ms-2">Pending</span>
                    <span class="badge badge-approved ms-1">Approved</span>
                    <span class="badge badge-completed ms-1">Completed</span>
                    <span class="badge badge-rejected ms-1">Rejected</span>
                </li>
                <li>Baris tabel akan berganti warna untuk kemudahan membaca</li>
                <li>Header tabel berwarna biru muda dengan teks tebal</li>
            </ul>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function viewBKDetails(id) {
            // Implementasi view detail BK
            alert('Detail BK ID: ' + id + '\nFitur ini dalam pengembangan.');
        }

        function updateStatus(id, status) {
            const statusText = {
                'approved': 'Setujui',
                'rejected': 'Tolak',
                'completed': 'Selesaikan'
            }[status] || status;
            
            if (confirm('Yakin ingin ' + statusText.toLowerCase() + ' bimbingan konseling ini?')) {
                // Kirim request AJAX untuk update status
                fetch('update_bk_status.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: 'id=' + id + '&status=' + status
                })
                .then(response => response.text())
                .then(data => {
                    alert(data);
                    location.reload();
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Terjadi kesalahan saat memperbarui status');
                });
            }
        }
        
        // Alert sebelum cetak PDF
        document.querySelector('a[href*="cetak=pdf"]').addEventListener('click', function(e) {
            if(!confirm('PDF akan segera dibuat. Proses ini mungkin membutuhkan beberapa saat untuk data yang banyak.\n\nLanjutkan?')) {
                e.preventDefault();
            }
        });
    </script>
</body>
</html>