<?php
session_start();
require_once '../../config/database.php';
require_once '../../config/function.php';

// Cek login
checkLogin();

$current_user = getCurrentUser();
$id_konseling = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($id_konseling <= 0) {
    $_SESSION['modal_title'] = 'Error!';
    $_SESSION['modal_message'] = 'ID konseling tidak valid';
    $_SESSION['modal_type'] = 'danger';
    $_SESSION['modal_redirect'] = 'index.php';
    header('Location: index.php');
    exit;
}

// Ambil data konseling
$query = "SELECT k.*, s.nama as nama_siswa, s.nis, s.jenis_kelamin, s.alamat, s.no_hp, s.nama_orangtua, s.no_hp_orangtua,
          g.nama_guru, g.nip,
          j.tanggal as jadwal_tanggal, j.jam as jadwal_jam, j.status as jadwal_status,
          ta.tahun_ajaran, ta.semester
          FROM bkcare_konseling k
          LEFT JOIN bkcare_siswa s ON k.id_siswa = s.id_siswa
          LEFT JOIN bkcare_guru g ON k.id_guru_bk = g.id_guru
          LEFT JOIN bkcare_jadwal_konseling j ON k.id_jadwal = j.id_jadwal
          LEFT JOIN bkcare_tahun_ajaran ta ON k.id_tahun_ajaran = ta.id_tahun_ajaran
          WHERE k.id_konseling = $id_konseling";
$result = mysqli_query($conn, $query);
$konseling = mysqli_fetch_assoc($result);

if (!$konseling) {
    $_SESSION['modal_title'] = 'Error!';
    $_SESSION['modal_message'] = 'Data konseling tidak ditemukan';
    $_SESSION['modal_type'] = 'danger';
    $_SESSION['modal_redirect'] = 'index.php';
    header('Location: index.php');
    exit;
}

// Cek akses
if ($current_user['role'] == 'siswa' && $konseling['id_siswa'] != getSiswaIdByUserId($current_user['id_user'], $conn)) {
    $_SESSION['modal_title'] = 'Akses Ditolak!';
    $_SESSION['modal_message'] = 'Anda tidak memiliki akses ke data ini';
    $_SESSION['modal_type'] = 'danger';
    $_SESSION['modal_redirect'] = 'index.php';
    header('Location: index.php');
    exit;
}

// Ambil data sesi konseling
$query_sesi = "SELECT * FROM bkcare_sesi_konseling WHERE id_konseling = $id_konseling ORDER BY id_sesi ASC";
$result_sesi = mysqli_query($conn, $query_sesi);
$sesi_list = [];
while ($row = mysqli_fetch_assoc($result_sesi)) {
    $sesi_list[] = $row;
}

// Ambil data rencana tindakan
$query_rencana = "SELECT * FROM bkcare_rencana_tindakan WHERE id_konseling = $id_konseling";
$result_rencana = mysqli_query($conn, $query_rencana);
$rencana = mysqli_fetch_assoc($result_rencana);

// Proses update status konseling
if (isset($_POST['update_status'])) {
    $status = mysqli_real_escape_string($conn, $_POST['status']);
    
    $query_update = "UPDATE bkcare_konseling SET status = '$status' WHERE id_konseling = $id_konseling";
    
    if (mysqli_query($conn, $query_update)) {
        $_SESSION['modal_title'] = 'Berhasil!';
        $_SESSION['modal_message'] = 'Status konseling berhasil diperbarui';
        $_SESSION['modal_type'] = 'success';
        $_SESSION['modal_redirect'] = 'detail.php?id=' . $id_konseling;
    } else {
        $_SESSION['modal_title'] = 'Gagal!';
        $_SESSION['modal_message'] = 'Gagal memperbarui status: ' . mysqli_error($conn);
        $_SESSION['modal_type'] = 'danger';
        $_SESSION['modal_redirect'] = 'detail.php?id=' . $id_konseling;
    }
    
    header('Location: detail.php?id=' . $id_konseling);
    exit;
}

include '../../includes/header.php';
include '../../includes/navbar.php';
?>

<style>
    .card-stat {
        background: white;
        border-radius: 1rem;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        transition: all 0.3s;
    }
    
    .card-stat:hover {
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    }
    
    .info-row {
        display: flex;
        padding: 12px 0;
        border-bottom: 1px solid #f0f0f0;
    }
    
    .info-label {
        width: 140px;
        font-weight: 500;
        color: #6b7280;
    }
    
    .info-value {
        flex: 1;
        color: #1f2937;
    }
    
    .badge-status {
        padding: 6px 12px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 500;
    }
    
    .badge-proses {
        background-color: #fff3cd;
        color: #856404;
    }
    
    .badge-selesai {
        background-color: #d4edda;
        color: #155724;
    }
    
    .sesi-card {
        border-left: 4px solid #8b5cf6;
        transition: all 0.3s;
    }
    
    .sesi-card:hover {
        transform: translateX(5px);
    }
    
    .badge-sesi {
        background-color: #f3e8ff;
        color: #6b21a5;
        padding: 4px 12px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 500;
    }
</style>

<div class="container mx-auto px-4 py-6">
    <div class="max-w-5xl mx-auto">
        <!-- Header -->
        <div class="flex flex-wrap justify-between items-center mb-6">
            <div class="flex items-center">
                <a href="index.php" class="text-gray-600 hover:text-purple-600 transition mr-4">
                    <i class="fas fa-arrow-left text-xl"></i>
                </a>
                <div>
                    <h1 class="text-2xl font-bold text-gray-800 flex items-center">
                        <i class="fas fa-hand-holding-heart text-purple-600 mr-3"></i>
                        Detail Konseling
                    </h1>
                    <p class="text-gray-600 text-sm mt-1">Informasi lengkap konseling siswa</p>
                </div>
            </div>
            <div class="mt-3 sm:mt-0 flex space-x-2">
                <a href="sesi.php?id=<?= $id_konseling ?>" class="bg-green-600 text-white px-4 py-2 rounded-xl hover:bg-green-700 transition flex items-center text-sm">
                    <i class="fas fa-comments mr-2"></i>
                    Sesi Konseling
                </a>
                <?php if ($konseling['status'] == 'proses'): ?>
                <button onclick="showStatusModal()" class="bg-purple-600 text-white px-4 py-2 rounded-xl hover:bg-purple-700 transition flex items-center text-sm">
                    <i class="fas fa-check-double mr-2"></i>
                    Selesaikan
                </button>
                <?php endif; ?>
            </div>
        </div>

        <!-- Informasi Konseling -->
        <div class="card-stat p-6 mb-6">
            <h2 class="text-lg font-semibold text-gray-800 mb-4 flex items-center">
                <i class="fas fa-info-circle text-purple-600 mr-2"></i>
                Informasi Konseling
            </h2>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div class="info-row">
                    <div class="info-label">ID Konseling</div>
                    <div class="info-value">#<?= $konseling['id_konseling'] ?></div>
                </div>
                <div class="info-row">
                    <div class="info-label">Status</div>
                    <div class="info-value">
                        <?php if($konseling['status'] == 'proses'): ?>
                            <span class="badge-status badge-proses">
                                <i class="fas fa-spinner fa-fw mr-1"></i>Proses
                            </span>
                        <?php else: ?>
                            <span class="badge-status badge-selesai">
                                <i class="fas fa-check-circle fa-fw mr-1"></i>Selesai
                            </span>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="info-row">
                    <div class="info-label">Tanggal Konseling</div>
                    <div class="info-value"><?= tgl_indonesia($konseling['tanggal']) ?></div>
                </div>
                <div class="info-row">
                    <div class="info-label">Jenis Konseling</div>
                    <div class="info-value"><?= htmlspecialchars($konseling['jenis_konseling']) ?></div>
                </div>
                <div class="info-row">
                    <div class="info-label">Lokasi</div>
                    <div class="info-value"><?= htmlspecialchars($konseling['lokasi']) ?></div>
                </div>
                <div class="info-row">
                    <div class="info-label">Tahun Ajaran</div>
                    <div class="info-value"><?= $konseling['tahun_ajaran'] ?> (Semester <?= ucfirst($konseling['semester']) ?>)</div>
                </div>
            </div>
        </div>

        <!-- Informasi Siswa -->
        <div class="card-stat p-6 mb-6">
            <h2 class="text-lg font-semibold text-gray-800 mb-4 flex items-center">
                <i class="fas fa-user-graduate text-purple-600 mr-2"></i>
                Informasi Siswa
            </h2>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div class="info-row">
                    <div class="info-label">Nama Siswa</div>
                    <div class="info-value"><?= htmlspecialchars($konseling['nama_siswa']) ?></div>
                </div>
                <div class="info-row">
                    <div class="info-label">NIS</div>
                    <div class="info-value"><?= $konseling['nis'] ?></div>
                </div>
                <div class="info-row">
                    <div class="info-label">Jenis Kelamin</div>
                    <div class="info-value"><?= $konseling['jenis_kelamin'] == 'L' ? 'Laki-laki' : 'Perempuan' ?></div>
                </div>
                <div class="info-row">
                    <div class="info-label">No. HP</div>
                    <div class="info-value"><?= $konseling['no_hp'] ?: '-' ?></div>
                </div>
                <div class="info-row">
                    <div class="info-label">Alamat</div>
                    <div class="info-value"><?= nl2br(htmlspecialchars($konseling['alamat'] ?: '-')) ?></div>
                </div>
                <div class="info-row">
                    <div class="info-label">Orang Tua</div>
                    <div class="info-value"><?= htmlspecialchars($konseling['nama_orangtua'] ?: '-') ?></div>
                </div>
                <div class="info-row">
                    <div class="info-label">No. HP Orang Tua</div>
                    <div class="info-value"><?= $konseling['no_hp_orangtua'] ?: '-' ?></div>
                </div>
            </div>
        </div>

        <!-- Informasi Guru BK -->
        <div class="card-stat p-6 mb-6">
            <h2 class="text-lg font-semibold text-gray-800 mb-4 flex items-center">
                <i class="fas fa-chalkboard-teacher text-purple-600 mr-2"></i>
                Informasi Guru BK
            </h2>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div class="info-row">
                    <div class="info-label">Nama Guru</div>
                    <div class="info-value"><?= htmlspecialchars($konseling['nama_guru']) ?></div>
                </div>
                <div class="info-row">
                    <div class="info-label">NIP</div>
                    <div class="info-value"><?= $konseling['nip'] ?: '-' ?></div>
                </div>
            </div>
        </div>

        <!-- Jadwal Terkait -->
        <?php if ($konseling['id_jadwal']): ?>
        <div class="card-stat p-6 mb-6">
            <h2 class="text-lg font-semibold text-gray-800 mb-4 flex items-center">
                <i class="fas fa-calendar-alt text-purple-600 mr-2"></i>
                Jadwal Terkait
            </h2>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div class="info-row">
                    <div class="info-label">Tanggal Jadwal</div>
                    <div class="info-value"><?= tgl_indonesia($konseling['jadwal_tanggal']) ?></div>
                </div>
                <div class="info-row">
                    <div class="info-label">Jam Jadwal</div>
                    <div class="info-value"><?= date('H:i', strtotime($konseling['jadwal_jam'])) ?></div>
                </div>
                <div class="info-row">
                    <div class="info-label">Status Jadwal</div>
                    <div class="info-value">
                        <?php
                        $status_class = '';
                        $status_text = '';
                        switch($konseling['jadwal_status']) {
                            case 'diajukan': $status_class = 'badge-warning'; $status_text = 'Diajukan'; break;
                            case 'disetujui': $status_class = 'badge-success'; $status_text = 'Disetujui'; break;
                            case 'ditolak': $status_class = 'badge-danger'; $status_text = 'Ditolak'; break;
                            case 'selesai': $status_class = 'badge-info'; $status_text = 'Selesai'; break;
                            case 'dibatalkan': $status_class = 'badge-secondary'; $status_text = 'Dibatalkan'; break;
                            default: $status_class = 'badge-secondary'; $status_text = $konseling['jadwal_status'];
                        }
                        ?>
                        <span class="badge-status <?= $status_class ?>"><?= $status_text ?></span>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Rencana Tindakan -->
        <?php if ($rencana): ?>
        <div class="card-stat p-6 mb-6">
            <h2 class="text-lg font-semibold text-gray-800 mb-4 flex items-center">
                <i class="fas fa-clipboard-list text-purple-600 mr-2"></i>
                Rencana Tindakan
            </h2>
            <div class="space-y-4">
                <div>
                    <p class="text-sm font-medium text-gray-700">Target Perubahan</p>
                    <p class="text-sm text-gray-600 bg-gray-50 p-3 rounded-lg mt-1"><?= nl2br(htmlspecialchars($rencana['target_perubahan'] ?: '-')) ?></p>
                </div>
                <div>
                    <p class="text-sm font-medium text-gray-700">Langkah Siswa</p>
                    <p class="text-sm text-gray-600 bg-gray-50 p-3 rounded-lg mt-1"><?= nl2br(htmlspecialchars($rencana['langkah_siswa'] ?: '-')) ?></p>
                </div>
                <div>
                    <p class="text-sm font-medium text-gray-700">Langkah Guru</p>
                    <p class="text-sm text-gray-600 bg-gray-50 p-3 rounded-lg mt-1"><?= nl2br(htmlspecialchars($rencana['langkah_guru'] ?: '-')) ?></p>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <p class="text-sm font-medium text-gray-700">Tanggal Evaluasi</p>
                        <p class="text-sm text-gray-600"><?= $rencana['tanggal_evaluasi'] ? tgl_indonesia($rencana['tanggal_evaluasi']) : '-' ?></p>
                    </div>
                    <div>
                        <p class="text-sm font-medium text-gray-700">Status</p>
                        <p class="text-sm text-gray-600">
                            <span class="badge-status <?= $rencana['status'] == 'berjalan' ? 'badge-proses' : 'badge-selesai' ?>">
                                <?= $rencana['status'] == 'berjalan' ? 'Berjalan' : 'Selesai' ?>
                            </span>
                        </p>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Daftar Sesi Konseling -->
        <div class="card-stat p-6">
            <h2 class="text-lg font-semibold text-gray-800 mb-4 flex items-center">
                <i class="fas fa-list-ul text-purple-600 mr-2"></i>
                Sesi Konseling
                <span class="ml-2 bg-purple-100 text-purple-700 px-2 py-1 rounded-full text-xs"><?= count($sesi_list) ?> Sesi</span>
            </h2>
            
            <?php if (empty($sesi_list)): ?>
                <div class="text-center py-8">
                    <i class="fas fa-comment-slash text-5xl text-gray-300 mb-3"></i>
                    <p class="text-gray-500">Belum ada sesi konseling</p>
                    <a href="sesi.php?id=<?= $id_konseling ?>" class="inline-block mt-3 text-purple-600 hover:text-purple-800">
                        <i class="fas fa-plus-circle mr-1"></i> Tambah Sesi
                    </a>
                </div>
            <?php else: ?>
                <div class="space-y-4">
                    <?php $no = 1; foreach ($sesi_list as $sesi): ?>
                    <div class="sesi-card p-4 bg-gray-50 rounded-lg">
                        <div class="flex justify-between items-start mb-3">
                            <span class="badge-sesi">
                                <i class="fas fa-calendar-alt mr-1"></i>
                                Sesi <?= $no++ ?>
                            </span>
                            <a href="sesi.php?id=<?= $id_konseling ?>" class="text-purple-600 hover:text-purple-800 text-sm">
                                <i class="fas fa-edit mr-1"></i> Edit
                            </a>
                        </div>
                        <div class="grid grid-cols-1 gap-3">
                            <div>
                                <p class="text-xs text-gray-500 mb-1">Cerita Siswa</p>
                                <p class="text-sm text-gray-700"><?= nl2br(htmlspecialchars(substr($sesi['cerita_siswa'], 0, 150) . (strlen($sesi['cerita_siswa']) > 150 ? '...' : ''))) ?></p>
                            </div>
                            <?php if ($sesi['analisis_emosi']): ?>
                            <div>
                                <p class="text-xs text-gray-500 mb-1">Analisis Emosi</p>
                                <p class="text-sm text-gray-700"><?= nl2br(htmlspecialchars(substr($sesi['analisis_emosi'], 0, 100) . (strlen($sesi['analisis_emosi']) > 100 ? '...' : ''))) ?></p>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                    <div class="text-center mt-4">
                        <a href="sesi.php?id=<?= $id_konseling ?>" class="text-purple-600 hover:text-purple-800">
                            <i class="fas fa-eye mr-1"></i> Lihat Semua Sesi
                        </a>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Modal Update Status -->
<div class="modal fade" id="statusModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title">
                    <i class="fas fa-check-double me-2"></i>
                    Selesaikan Konseling
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" action="">
                <div class="modal-body text-center py-4">
                    <input type="hidden" name="update_status" value="1">
                    <input type="hidden" name="status" value="selesai">
                    <div class="modal-icon mb-3">
                        <i class="fas fa-question-circle fa-3x text-warning"></i>
                    </div>
                    <p class="mb-0">Apakah Anda yakin ingin menyelesaikan konseling ini?</p>
                    <small class="text-muted">Konseling yang telah selesai tidak dapat diubah kembali</small>
                </div>
                <div class="modal-footer justify-content-center">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times me-2"></i>Batal
                    </button>
                    <button type="submit" class="btn btn-success">
                        <i class="fas fa-check me-2"></i>Ya, Selesaikan
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
function showStatusModal() {
    $('#statusModal').modal('show');
}

<?php if (isset($_SESSION['modal_title'])): ?>
    $(document).ready(function() {
        let modalType = '<?= $_SESSION['modal_type'] ?>';
        let modalTitle = '<?= $_SESSION['modal_title'] ?>';
        let modalMessage = '<?= addslashes($_SESSION['modal_message']) ?>';
        let modalRedirect = '<?= $_SESSION['modal_redirect'] ?? '' ?>';
        
        let bgColor = modalType == 'success' ? 'bg-success' : (modalType == 'danger' ? 'bg-danger' : 'bg-warning');
        let icon = modalType == 'success' ? 'check-circle' : (modalType == 'danger' ? 'exclamation-circle' : 'info-circle');
        let iconModal = modalType == 'success' ? 'check-circle' : (modalType == 'danger' ? 'times-circle' : 'exclamation-triangle');
        
        let modalHtml = `
            <div class="modal fade" id="notificationModal" tabindex="-1" aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content rounded-2xl">
                        <div class="modal-header ${bgColor} text-white rounded-t-2xl">
                            <h5 class="modal-title">
                                <i class="fas fa-${icon} me-2"></i>
                                ${modalTitle}
                            </h5>
                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body text-center py-5">
                            <div class="modal-icon mb-3">
                                <i class="fas fa-${iconModal} fa-3x text-${modalType}"></i>
                            </div>
                            <p class="mb-0 text-gray-700">${modalMessage}</p>
                        </div>
                        <div class="modal-footer justify-content-center border-t border-gray-100 pt-4">
                            <button type="button" class="btn btn-${modalType == 'success' ? 'success' : (modalType == 'danger' ? 'danger' : 'warning')}" data-bs-dismiss="modal">
                                <i class="fas fa-check me-2"></i>OK
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        if ($('#notificationModal').length === 0) {
            $('body').append(modalHtml);
        }
        
        $('#notificationModal').modal('show');
        
        $('#notificationModal').on('hidden.bs.modal', function() {
            $(this).remove();
            if (modalRedirect && modalRedirect !== window.location.pathname.split('/').pop() + '?id=<?= $id_konseling ?>') {
                window.location.href = modalRedirect;
            }
        });
    });
    <?php unset($_SESSION['modal_title'], $_SESSION['modal_message'], $_SESSION['modal_type'], $_SESSION['modal_redirect']); ?>
<?php endif; ?>
</script>

<?php include '../../includes/footer.php'; ?>