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

// Cek login
checkLogin();

$current_user = getCurrentUser();
$tahun_ajaran_aktif = getTahunAjaranAktif();

// Ambil parameter filter
$tahun_ajaran_id = isset($_GET['tahun_ajaran']) ? (int)$_GET['tahun_ajaran'] : ($tahun_ajaran_aktif ? $tahun_ajaran_aktif['id_tahun_ajaran'] : 0);
$status = isset($_GET['status']) ? mysqli_real_escape_string($conn, $_GET['status']) : '';
$search = isset($_GET['search']) ? mysqli_real_escape_string($conn, $_GET['search']) : '';

// Query ambil data laporan
$query = "SELECT l.*, 
          s.nis, s.nama as nama_siswa,
          u.nama as nama_pelapor,
          ta.tahun_ajaran, ta.semester
          FROM bkcare_laporan_masalah l
          LEFT JOIN bkcare_siswa s ON l.id_siswa = s.id_siswa
          LEFT JOIN bkcare_users u ON l.id_pelapor = u.id_user
          LEFT JOIN bkcare_tahun_ajaran ta ON l.id_tahun_ajaran = ta.id_tahun_ajaran
          WHERE 1=1";

if ($tahun_ajaran_id > 0) {
    $query .= " AND l.id_tahun_ajaran = $tahun_ajaran_id";
}

if (!empty($status)) {
    $query .= " AND l.status = '$status'";
}

if (!empty($search)) {
    $query .= " AND (s.nama LIKE '%$search%' OR s.nis LIKE '%$search%' OR l.jenis_masalah LIKE '%$search%' OR l.deskripsi LIKE '%$search%')";
}

$query .= " ORDER BY l.tanggal DESC, l.id_laporan DESC";
$result = mysqli_query($conn, $query);

// Ambil data untuk filter
$tahun_ajaran_list = mysqli_query($conn, "SELECT * FROM bkcare_tahun_ajaran ORDER BY tahun_ajaran DESC, semester");

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

<!-- Main Content -->
<main class="container mx-auto px-4 py-6">
    <!-- Header -->
    <div class="flex justify-between items-center mb-6">
        <div>
            <h1 class="text-2xl font-bold text-gray-800 flex items-center">
                <i class="fas fa-exclamation-triangle text-red-500 mr-3"></i>
                Data Laporan Masalah
            </h1>
            <p class="text-gray-600 text-sm mt-1">Kelola laporan masalah siswa</p>
        </div>
        <a href="tambah.php" class="btn-primary">
            <i class="fas fa-plus mr-2"></i>Buat Laporan Baru
        </a>
    </div>

    <!-- Filter Section -->
    <div class="card-stat p-4 mb-6">
        <form method="GET" class="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div>
                <label class="block text-xs font-medium text-gray-500 mb-1">
                    <i class="fas fa-calendar-alt mr-1 text-purple-600"></i>Tahun Ajaran
                </label>
                <select name="tahun_ajaran" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-600 focus:border-transparent">
                    <option value="">Semua Tahun Ajaran</option>
                    <?php while($ta = mysqli_fetch_assoc($tahun_ajaran_list)): ?>
                        <option value="<?= $ta['id_tahun_ajaran'] ?>" <?= $tahun_ajaran_id == $ta['id_tahun_ajaran'] ? 'selected' : '' ?>>
                            <?= $ta['tahun_ajaran'] ?> - <?= ucfirst($ta['semester']) ?>
                            <?= $ta['status'] == 'aktif' ? '(Aktif)' : '' ?>
                        </option>
                    <?php endwhile; ?>
                </select>
            </div>
            <div>
                <label class="block text-xs font-medium text-gray-500 mb-1">
                    <i class="fas fa-tag mr-1 text-purple-600"></i>Status
                </label>
                <select name="status" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-600 focus:border-transparent">
                    <option value="">Semua Status</option>
                    <option value="baru" <?= $status == 'baru' ? 'selected' : '' ?>>Baru</option>
                    <option value="diproses" <?= $status == 'diproses' ? 'selected' : '' ?>>Diproses</option>
                    <option value="selesai" <?= $status == 'selesai' ? 'selected' : '' ?>>Selesai</option>
                </select>
            </div>
            <div class="md:col-span-2">
                <label class="block text-xs font-medium text-gray-500 mb-1">
                    <i class="fas fa-search mr-1 text-purple-600"></i>Pencarian
                </label>
                <div class="flex">
                    <input type="text" 
                           name="search" 
                           value="<?= htmlspecialchars($search) ?>"
                           class="flex-1 px-3 py-2 border border-gray-300 rounded-l-lg focus:ring-2 focus:ring-purple-600 focus:border-transparent"
                           placeholder="Cari siswa, NIS, jenis masalah, atau deskripsi...">
                    <button type="submit" class="bg-purple-600 text-white px-4 py-2 rounded-r-lg hover:bg-purple-700 transition">
                        <i class="fas fa-search"></i>
                    </button>
                </div>
            </div>
        </form>
    </div>

    <!-- Table -->
    <div class="card-stat p-6">
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">No</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Tanggal</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Siswa</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Jenis Masalah</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Pelapor</th>
                        <th class="min-w-[150px] text-left text-xs font-medium text-gray-500 uppercase">Status</th>
                        <th class="min-w-[150px] text-right text-xs font-medium text-gray-500 uppercase">Aksi</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    <?php if (mysqli_num_rows($result) > 0): ?>
                        <?php $no = 1; ?>
                        <?php while($row = mysqli_fetch_assoc($result)): ?>
                            <tr class="hover:bg-red-50 transition">
                                <td class="px-6 py-4 text-sm text-gray-600"><?= $no++ ?></td>
                                <td class="px-6 py-4 text-sm">
                                    <span class="font-medium"><?= tgl_indonesia($row['tanggal']) ?></span>
                                    <span class="text-xs text-gray-500 block"><?= $row['tahun_ajaran'] ?></span>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="font-medium text-gray-800"><?= htmlspecialchars($row['nama_siswa']) ?></div>
                                    <div class="text-xs text-gray-500">NIS: <?= $row['nis'] ?></div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="font-medium text-gray-800"><?= htmlspecialchars($row['jenis_masalah']) ?></div>
                                    <div class="text-xs text-gray-500 max-w-xs truncate" title="<?= htmlspecialchars($row['deskripsi']) ?>">
                                        <i class="fas fa-align-left mr-1 text-gray-400"></i>
                                        <?= substr(htmlspecialchars($row['deskripsi']), 0, 50) ?>...
                                    </div>
                                </td>
                                <td class="px-6 py-4 text-sm text-gray-600">
                                    <?= htmlspecialchars($row['nama_pelapor']) ?>
                                </td>
                                <td class="px-6 py-4">
                                    <?php 
                                    $status_class = [
                                        'baru' => 'badge-warning',
                                        'diproses' => 'badge-info',
                                        'selesai' => 'badge-success'
                                    ];
                                    $status_icon = [
                                        'baru' => 'exclamation-circle',
                                        'diproses' => 'spinner',
                                        'selesai' => 'check-circle'
                                    ];
                                    $status_text = [
                                        'baru' => 'Baru',
                                        'diproses' => 'Diproses',
                                        'selesai' => 'Selesai'
                                    ];
                                    ?>
                                    <span class="<?= $status_class[$row['status']] ?> px-3 py-1 rounded-full text-xs">
                                        <i class="fas fa-<?= $status_icon[$row['status']] ?> mr-1"></i>
                                        <?= $status_text[$row['status']] ?>
                                    </span>
                                </td>
                                <td class="px-6 py-4 text-sm text-right">
                                    <a href="detail.php?id=<?= $row['id_laporan'] ?>" 
                                       class="text-green-600 hover:text-green-800 mx-2"
                                       data-bs-toggle="tooltip" 
                                       title="Detail Laporan">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                    <a href="edit.php?id=<?= $row['id_laporan'] ?>" 
                                       class="text-blue-600 hover:text-blue-800 mx-2"
                                       data-bs-toggle="tooltip" 
                                       title="Edit Data">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <?php if ($row['status'] == 'selesai'): ?>
                                        <span class="text-gray-400 mx-2 cursor-not-allowed" 
                                              data-bs-toggle="tooltip" 
                                              title="Laporan selesai tidak dapat dihapus">
                                            <i class="fas fa-trash"></i>
                                        </span>
                                    <?php else: ?>
                                        <a href="#" 
                                           onclick="confirmDelete(<?= $row['id_laporan'] ?>, 'Laporan: <?= htmlspecialchars($row['jenis_masalah']) ?> - <?= htmlspecialchars($row['nama_siswa']) ?>')"
                                           class="text-red-600 hover:text-red-800 mx-2"
                                           data-bs-toggle="tooltip" 
                                           title="Hapus Data">
                                            <i class="fas fa-trash"></i>
                                        </a>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="7" class="px-6 py-12 text-center text-gray-500">
                                <i class="fas fa-flag fa-3x mb-3 text-gray-300"></i>
                                <p class="text-lg font-medium">Belum ada laporan masalah</p>
                                <p class="text-sm mt-1">Klik tombol "Buat Laporan Baru" untuk membuat laporan</p>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</main>

<!-- Modal Konfirmasi Hapus -->
<div class="modal fade" id="deleteModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content rounded-2xl">
            <div class="modal-header bg-red-500 text-white rounded-t-2xl">
                <h5 class="modal-title">
                    <i class="fas fa-exclamation-triangle mr-2"></i>Konfirmasi Hapus
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-6">
                <p class="text-gray-600 mb-2">Apakah Anda yakin ingin menghapus:</p>
                <p class="font-semibold text-gray-800" id="deleteItemInfo"></p>
                <p class="text-sm text-red-600 mt-3">
                    <i class="fas fa-info-circle mr-1"></i>
                    Data yang sudah dihapus tidak dapat dikembalikan!
                </p>
            </div>
            <div class="modal-footer border-t border-gray-100 p-4">
                <button type="button" class="btn-outline-primary text-sm" data-bs-dismiss="modal">
                    <i class="fas fa-times mr-1"></i>Batal
                </button>
                <a href="#" id="confirmDeleteBtn" class="bg-red-500 text-white px-6 py-2 rounded-full hover:bg-red-600 transition text-sm">
                    <i class="fas fa-trash mr-1"></i>Ya, Hapus
                </a>
            </div>
        </div>
    </div>
</div>

<script>
function confirmDelete(id, info) {
    if (typeof window.confirmDelete === 'function') {
        window.confirmDelete(id, info, 'hapus.php');
    } else {
        document.getElementById('deleteItemInfo').textContent = info;
        document.getElementById('confirmDeleteBtn').href = 'hapus.php?id=' + id;
        
        var deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));
        deleteModal.show();
    }
}

$(document).ready(function() {
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    var tooltipList = tooltipTriggerList.map(function(tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
});
</script>

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