<?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_konseling = "SELECT k.*, s.nama as nama_siswa, s.nis, s.jenis_kelamin, g.nama_guru
                    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
                    WHERE k.id_konseling = $id_konseling";
$result_konseling = mysqli_query($conn, $query_konseling);
$konseling = mysqli_fetch_assoc($result_konseling);

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 = fetch_all($result_sesi);

// Proses tambah/update sesi
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $action = $_POST['action'] ?? '';
    $id_sesi = isset($_POST['id_sesi']) ? (int)$_POST['id_sesi'] : 0;
    $cerita_siswa = mysqli_real_escape_string($conn, $_POST['cerita_siswa'] ?? '');
    $analisis_emosi = mysqli_real_escape_string($conn, $_POST['analisis_emosi'] ?? '');
    $refleksi = mysqli_real_escape_string($conn, $_POST['refleksi'] ?? '');
    $konfrontasi = mysqli_real_escape_string($conn, $_POST['konfrontasi'] ?? '');
    $penguatan = mysqli_real_escape_string($conn, $_POST['penguatan'] ?? '');
    
    $errors = [];
    
    if (empty($cerita_siswa)) {
        $errors[] = 'Cerita siswa harus diisi';
    }
    
    if (empty($errors)) {
        if ($action == 'add') {
            $query = "INSERT INTO bkcare_sesi_konseling (id_konseling, cerita_siswa, analisis_emosi, refleksi, konfrontasi, penguatan) 
                      VALUES ($id_konseling, '$cerita_siswa', '$analisis_emosi', '$refleksi', '$konfrontasi', '$penguatan')";
            
            if (mysqli_query($conn, $query)) {
                $_SESSION['modal_title'] = 'Berhasil!';
                $_SESSION['modal_message'] = 'Sesi konseling berhasil ditambahkan';
                $_SESSION['modal_type'] = 'success';
            } else {
                $_SESSION['modal_title'] = 'Gagal!';
                $_SESSION['modal_message'] = 'Gagal menambahkan sesi: ' . mysqli_error($conn);
                $_SESSION['modal_type'] = 'danger';
            }
        } elseif ($action == 'edit' && $id_sesi > 0) {
            $query = "UPDATE bkcare_sesi_konseling SET 
                      cerita_siswa = '$cerita_siswa',
                      analisis_emosi = '$analisis_emosi',
                      refleksi = '$refleksi',
                      konfrontasi = '$konfrontasi',
                      penguatan = '$penguatan'
                      WHERE id_sesi = $id_sesi AND id_konseling = $id_konseling";
            
            if (mysqli_query($conn, $query)) {
                $_SESSION['modal_title'] = 'Berhasil!';
                $_SESSION['modal_message'] = 'Sesi konseling berhasil diperbarui';
                $_SESSION['modal_type'] = 'success';
            } else {
                $_SESSION['modal_title'] = 'Gagal!';
                $_SESSION['modal_message'] = 'Gagal memperbarui sesi: ' . mysqli_error($conn);
                $_SESSION['modal_type'] = 'danger';
            }
        }
        
        header('Location: sesi.php?id=' . $id_konseling);
        exit;
    } else {
        $_SESSION['modal_title'] = 'Validasi Gagal!';
        $_SESSION['modal_message'] = implode('<br>', $errors);
        $_SESSION['modal_type'] = 'warning';
    }
}

// Proses hapus sesi
if (isset($_GET['delete'])) {
    $id_sesi = (int)$_GET['delete'];
    
    $query = "DELETE FROM bkcare_sesi_konseling WHERE id_sesi = $id_sesi AND id_konseling = $id_konseling";
    
    if (mysqli_query($conn, $query)) {
        $_SESSION['modal_title'] = 'Berhasil!';
        $_SESSION['modal_message'] = 'Sesi konseling berhasil dihapus';
        $_SESSION['modal_type'] = 'success';
    } else {
        $_SESSION['modal_title'] = 'Gagal!';
        $_SESSION['modal_message'] = 'Gagal menghapus sesi: ' . mysqli_error($conn);
        $_SESSION['modal_type'] = 'danger';
    }
    
    header('Location: sesi.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);
    }
    
    .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;
    }
    
    .form-icon {
        position: absolute;
        left: 15px;
        top: 50%;
        transform: translateY(-50%);
        color: #9ca3af;
    }
    
    .form-textarea-icon {
        position: absolute;
        left: 15px;
        top: 20px;
        color: #9ca3af;
    }
    
    .form-input-icon {
        padding-left: 40px;
    }
    
    .form-textarea-icon-pad {
        padding-left: 40px;
    }
</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="detail.php?id=<?= $id_konseling ?>" 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-comments text-purple-600 mr-3"></i>
                        Sesi Konseling
                    </h1>
                    <p class="text-gray-600 text-sm mt-1">Kelola sesi konseling untuk <?= htmlspecialchars($konseling['nama_siswa']) ?></p>
                </div>
            </div>
            <button type="button" onclick="showAddModal()" class="mt-3 sm:mt-0 bg-purple-600 text-white px-5 py-2.5 rounded-xl hover:bg-purple-700 transition flex items-center shadow-sm">
                <i class="fas fa-plus-circle mr-2"></i>
                Tambah Sesi
            </button>
        </div>

        <!-- Info Konseling -->
        <div class="card-stat p-6 mb-6">
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                    <p class="text-sm text-gray-500">Siswa</p>
                    <p class="font-semibold text-gray-800">
                        <i class="fas fa-user-graduate text-purple-600 mr-2"></i>
                        <?= htmlspecialchars($konseling['nama_siswa']) ?>
                    </p>
                    <p class="text-xs text-gray-500">NIS: <?= $konseling['nis'] ?></p>
                </div>
                <div>
                    <p class="text-sm text-gray-500">Guru BK</p>
                    <p class="font-semibold text-gray-800">
                        <i class="fas fa-chalkboard-teacher text-purple-600 mr-2"></i>
                        <?= htmlspecialchars($konseling['nama_guru']) ?>
                    </p>
                </div>
                <div>
                    <p class="text-sm text-gray-500">Jenis Konseling</p>
                    <p class="font-semibold text-gray-800">
                        <i class="fas fa-tag text-purple-600 mr-2"></i>
                        <?= htmlspecialchars($konseling['jenis_konseling']) ?>
                    </p>
                    <p class="text-xs text-gray-500">Tanggal: <?= tgl_indonesia($konseling['tanggal']) ?></p>
                </div>
            </div>
        </div>

        <!-- Daftar Sesi Konseling -->
        <div class="mb-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>
                Daftar 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="card-stat p-8 text-center">
                    <i class="fas fa-comment-slash text-5xl text-gray-300 mb-3"></i>
                    <p class="text-gray-500">Belum ada sesi konseling</p>
                    <p class="text-sm text-gray-400">Klik tombol "Tambah Sesi" untuk memulai</p>
                </div>
            <?php else: ?>
                <div class="space-y-4">
                    <?php $no = 1; foreach ($sesi_list as $sesi): ?>
                    <div class="card-stat sesi-card p-5">
                        <div class="flex flex-wrap justify-between items-start mb-3">
                            <div>
                                <span class="badge-sesi">
                                    <i class="fas fa-calendar-alt mr-1"></i>
                                    Sesi <?= $no++ ?>
                                </span>
                            </div>
                            <div class="flex space-x-2">
                                <button onclick="editSesi(<?= $sesi['id_sesi'] ?>)" 
                                        class="text-blue-600 hover:text-blue-800 transition"
                                        title="Edit Sesi">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button onclick="confirmDelete(<?= $sesi['id_sesi'] ?>)" 
                                        class="text-red-600 hover:text-red-800 transition"
                                        title="Hapus Sesi">
                                    <i class="fas fa-trash-alt"></i>
                                </button>
                            </div>
                        </div>
                        
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <p class="text-xs text-gray-500 mb-1">
                                    <i class="fas fa-book-open mr-1"></i>Cerita Siswa
                                </p>
                                <p class="text-sm text-gray-700 bg-gray-50 p-3 rounded-lg">
                                    <?= nl2br(htmlspecialchars($sesi['cerita_siswa'])) ?>
                                </p>
                            </div>
                            <div>
                                <p class="text-xs text-gray-500 mb-1">
                                    <i class="fas fa-brain mr-1"></i>Analisis Emosi
                                </p>
                                <p class="text-sm text-gray-700 bg-gray-50 p-3 rounded-lg">
                                    <?= nl2br(htmlspecialchars($sesi['analisis_emosi'] ?: '-')) ?>
                                </p>
                            </div>
                            <div>
                                <p class="text-xs text-gray-500 mb-1">
                                    <i class="fas fa-comment-dots mr-1"></i>Refleksi
                                </p>
                                <p class="text-sm text-gray-700 bg-gray-50 p-3 rounded-lg">
                                    <?= nl2br(htmlspecialchars($sesi['refleksi'] ?: '-')) ?>
                                </p>
                            </div>
                            <div>
                                <p class="text-xs text-gray-500 mb-1">
                                    <i class="fas fa-hand-fist mr-1"></i>Konfrontasi
                                </p>
                                <p class="text-sm text-gray-700 bg-gray-50 p-3 rounded-lg">
                                    <?= nl2br(htmlspecialchars($sesi['konfrontasi'] ?: '-')) ?>
                                </p>
                            </div>
                            <div class="md:col-span-2">
                                <p class="text-xs text-gray-500 mb-1">
                                    <i class="fas fa-thumbs-up mr-1"></i>Penguatan
                                </p>
                                <p class="text-sm text-gray-700 bg-gray-50 p-3 rounded-lg">
                                    <?= nl2br(htmlspecialchars($sesi['penguatan'] ?: '-')) ?>
                                </p>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Modal Tambah/Edit Sesi -->
<div class="modal fade" id="sesiModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-purple-600 text-white">
                <h5 class="modal-title" id="modalTitle">
                    <i class="fas fa-plus-circle me-2"></i>
                    Tambah Sesi Konseling
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" action="sesi.php?id=<?= $id_konseling ?>" id="sesiForm">
                <div class="modal-body p-5">
                    <input type="hidden" name="action" id="formAction" value="add">
                    <input type="hidden" name="id_sesi" id="id_sesi" value="0">
                    
                    <!-- Cerita Siswa -->
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-book-open text-purple-600 mr-1"></i>
                            Cerita Siswa <span class="text-red-500">*</span>
                        </label>
                        <div class="relative">
                            <div class="absolute left-3 top-3 text-gray-400">
                                <i class="fas fa-quote-left"></i>
                            </div>
                            <textarea name="cerita_siswa" id="cerita_siswa" rows="4"
                                      class="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-600 focus:border-transparent outline-none transition"
                                      placeholder="Ceritakan apa yang dialami/dirasakan siswa..."></textarea>
                        </div>
                    </div>
                    
                    <!-- Analisis Emosi -->
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-brain text-purple-600 mr-1"></i>
                            Analisis Emosi
                        </label>
                        <div class="relative">
                            <div class="absolute left-3 top-3 text-gray-400">
                                <i class="fas fa-chart-line"></i>
                            </div>
                            <textarea name="analisis_emosi" id="analisis_emosi" rows="3"
                                      class="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-600 focus:border-transparent outline-none transition"
                                      placeholder="Analisis kondisi emosi siswa..."></textarea>
                        </div>
                    </div>
                    
                    <!-- Refleksi -->
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-comment-dots text-purple-600 mr-1"></i>
                            Refleksi
                        </label>
                        <div class="relative">
                            <div class="absolute left-3 top-3 text-gray-400">
                                <i class="fas fa-retweet"></i>
                            </div>
                            <textarea name="refleksi" id="refleksi" rows="3"
                                      class="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-600 focus:border-transparent outline-none transition"
                                      placeholder="Refleksi dari konselor..."></textarea>
                        </div>
                    </div>
                    
                    <!-- Konfrontasi -->
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-hand-fist text-purple-600 mr-1"></i>
                            Konfrontasi
                        </label>
                        <div class="relative">
                            <div class="absolute left-3 top-3 text-gray-400">
                                <i class="fas fa-exclamation-triangle"></i>
                            </div>
                            <textarea name="konfrontasi" id="konfrontasi" rows="3"
                                      class="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-600 focus:border-transparent outline-none transition"
                                      placeholder="Konfrontasi terhadap perilaku siswa..."></textarea>
                        </div>
                    </div>
                    
                    <!-- Penguatan -->
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-thumbs-up text-purple-600 mr-1"></i>
                            Penguatan
                        </label>
                        <div class="relative">
                            <div class="absolute left-3 top-3 text-gray-400">
                                <i class="fas fa-star"></i>
                            </div>
                            <textarea name="penguatan" id="penguatan" rows="3"
                                      class="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-600 focus:border-transparent outline-none transition"
                                      placeholder="Penguatan positif yang diberikan..."></textarea>
                        </div>
                    </div>
                </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-primary bg-purple-600 text-white">
                        <i class="fas fa-save me-2"></i>Simpan Sesi
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal Konfirmasi Hapus -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">
                    <i class="fas fa-trash-alt me-2"></i>
                    Konfirmasi Hapus
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body text-center py-4">
                <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 menghapus sesi konseling ini?</p>
                <small class="text-muted">Data yang dihapus tidak dapat dikembalikan</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>
                <a href="#" id="deleteLink" class="btn btn-danger">
                    <i class="fas fa-trash-alt me-2"></i>Ya, Hapus
                </a>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
let sesiData = {};

function showAddModal() {
    $('#modalTitle').html('<i class="fas fa-plus-circle me-2"></i>Tambah Sesi Konseling');
    $('#formAction').val('add');
    $('#id_sesi').val(0);
    $('#cerita_siswa').val('');
    $('#analisis_emosi').val('');
    $('#refleksi').val('');
    $('#konfrontasi').val('');
    $('#penguatan').val('');
    $('#sesiModal').modal('show');
}

function editSesi(id) {
    // Ambil data sesi dari PHP yang sudah ada
    <?php foreach ($sesi_list as $sesi): ?>
    if (id == <?= $sesi['id_sesi'] ?>) {
        sesiData = {
            id: <?= $sesi['id_sesi'] ?>,
            cerita_siswa: <?= json_encode($sesi['cerita_siswa']) ?>,
            analisis_emosi: <?= json_encode($sesi['analisis_emosi']) ?>,
            refleksi: <?= json_encode($sesi['refleksi']) ?>,
            konfrontasi: <?= json_encode($sesi['konfrontasi']) ?>,
            penguatan: <?= json_encode($sesi['penguatan']) ?>
        };
    }
    <?php endforeach; ?>
    
    $('#modalTitle').html('<i class="fas fa-edit me-2"></i>Edit Sesi Konseling');
    $('#formAction').val('edit');
    $('#id_sesi').val(sesiData.id);
    $('#cerita_siswa').val(sesiData.cerita_siswa);
    $('#analisis_emosi').val(sesiData.analisis_emosi);
    $('#refleksi').val(sesiData.refleksi);
    $('#konfrontasi').val(sesiData.konfrontasi);
    $('#penguatan').val(sesiData.penguatan);
    $('#sesiModal').modal('show');
}

function confirmDelete(id) {
    $('#deleteLink').attr('href', 'sesi.php?id=<?= $id_konseling ?>&delete=' + id);
    $('#deleteModal').modal('show');
}

// Validasi form
$('#sesiForm').on('submit', function(e) {
    let cerita_siswa = $('#cerita_siswa').val();
    let errors = [];
    
    if (!cerita_siswa) {
        errors.push('Cerita siswa harus diisi');
        $('#cerita_siswa').addClass('border-red-500');
    } else {
        $('#cerita_siswa').removeClass('border-red-500');
    }
    
    if (errors.length > 0) {
        e.preventDefault();
        alert('Validasi Gagal:\n- ' + errors.join('\n- '));
    }
});

// Hapus border merah saat input berubah
$('#cerita_siswa, #analisis_emosi, #refleksi, #konfrontasi, #penguatan').on('change input', function() {
    if ($(this).val()) {
        $(this).removeClass('border-red-500');
    }
});

// Tampilkan modal notifikasi jika ada
<?php if (isset($_SESSION['modal_title'])): ?>
    $(document).ready(function() {
        let modalHtml = `
            <div class="modal fade" id="notificationModal" tabindex="-1" aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content">
                        <div class="modal-header bg-<?= $_SESSION['modal_type'] == 'success' ? 'success' : ($_SESSION['modal_type'] == 'danger' ? 'danger' : 'warning') ?> text-white">
                            <h5 class="modal-title">
                                <i class="fas fa-<?= $_SESSION['modal_type'] == 'success' ? 'check-circle' : ($_SESSION['modal_type'] == 'danger' ? 'exclamation-circle' : 'info-circle') ?> me-2"></i>
                                <?= $_SESSION['modal_title'] ?>
                            </h5>
                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body text-center py-4">
                            <div class="modal-icon mb-3">
                                <i class="fas fa-<?= $_SESSION['modal_type'] == 'success' ? 'check-circle' : ($_SESSION['modal_type'] == 'danger' ? 'times-circle' : 'exclamation-triangle') ?> fa-3x text-<?= $_SESSION['modal_type'] ?>"></i>
                            </div>
                            <p class="mb-0"><?= $_SESSION['modal_message'] ?></p>
                        </div>
                        <div class="modal-footer justify-content-center">
                            <button type="button" class="btn btn-<?= $_SESSION['modal_type'] == 'success' ? 'success' : ($_SESSION['modal_type'] == 'danger' ? 'danger' : 'warning') ?>" data-bs-dismiss="modal">
                                <i class="fas fa-check me-2"></i>OK
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        $('body').append(modalHtml);
        $('#notificationModal').modal('show');
        
        $('#notificationModal').on('hidden.bs.modal', function() {
            $(this).remove();
        });
    });
    <?php unset($_SESSION['modal_title'], $_SESSION['modal_message'], $_SESSION['modal_type']); ?>
<?php endif; ?>
</script>

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