<?php 
if ($mod ==''){
    header('location:../404');
    echo'kosong';
}else{
    include_once 'mod/sw-header.php';
    if(!isset($_COOKIE['COOKIES_MEMBER'])){
        header('location:index');
    }
    else {
        $id_user = $row_user['id'];
        $nama    = $row_user['employees_name'];
        $divisi  = $row_user['division']; 
        $salam   = date("H") < 12 ? "Pagi" : (date("H") < 18 ? "Siang" : "Malam");

        // =================== HANDLE AJAX TAMBAH PERMINTAAN ===================
        if (isset($_POST['ajax_add']) && $_POST['ajax_add'] == 'true') {
            header("Content-Type: text/plain"); // pastikan output murni teks
            ob_clean(); // bersihkan semua output buffer agar tidak kirim HTML
        
            $divisi_tujuan = $connection->real_escape_string($_POST['divisi_tujuan']);
            $penanggung_jawab = $connection->real_escape_string($_POST['penanggung_jawab']);
            $tanggal_dibutuhkan = $connection->real_escape_string($_POST['tanggal_dibutuhkan']);
            $detail = $connection->real_escape_string($_POST['detail_permintaan']);
            $tanggal_permintaan = date("Y-m-d");
        
            $insert = $connection->query("
                INSERT INTO permintaan 
                (tanggal_permintaan, tanggal_dibutuhkan, nama_pengaju, divisi_pengaju, divisi_tujuan, detail_permintaan, penanggung_jawab, progres, status)
                VALUES 
                ('$tanggal_permintaan', '$tanggal_dibutuhkan', '$nama', '$divisi', '$divisi_tujuan', '$detail', '$penanggung_jawab', 0, 'Menunggu')
            ");
        
            echo $insert ? 'success' : 'error';
            exit; // penting: hentikan agar HTML di bawah tidak ikut terkirim
        }

        // =================== HANDLE AJAX UPDATE STATUS ===================
        if (isset($_POST['ajax_update']) && $_POST['ajax_update'] == 'true') {
            header("Content-Type: text/plain"); // pastikan output murni teks
            ob_clean(); // hapus buffer HTML yang mungkin sudah terlanjur
            $id = intval($_POST['id']);
            $status = $connection->real_escape_string($_POST['status']);
        
            $update = $connection->query("UPDATE permintaan SET status='$status' WHERE id_permintaan='$id'");
            if ($update) {
                echo "success";
            } else {
                echo "error";
            }
            exit; // hentikan eksekusi agar HTML di bawah tidak ikut terkirim
        }


        // ==================== HANDLE AJAX AUTO PENGISI PENANGGUNG JAWAB ====================
        if(isset($_POST['ajax_get_pj']) && $_POST['ajax_get_pj']=='true'){
            $divisi_tujuan = $connection->real_escape_string($_POST['divisi_tujuan']);
            $q = $connection->query("SELECT employees_name FROM employees WHERE position='$divisi_tujuan' LIMIT 1");
            echo ($q->num_rows>0) ? $q->fetch_assoc()['employees_name'] : '';
            exit;
        }

        // ==================== REKAP MINGGUAN ====================
        $tgl_mulai = date("Y-m-d", strtotime("-6 days"));
        $tgl_selesai = date("Y-m-d");
        $rekap_user = ['supervisi'=>0,'ibadah'=>0,'izin'=>0,'aktivitas'=>0];

        $rekap_user['supervisi'] = $connection->query("SELECT COUNT(DISTINCT tanggal) jml FROM supervisi WHERE (pimpinan='$nama' OR karyawan='$nama') AND tanggal BETWEEN '$tgl_mulai' AND '$tgl_selesai'")->fetch_assoc()['jml'];
        $rekap_user['ibadah']    = $connection->query("SELECT COUNT(DISTINCT tanggal) jml FROM ibadah WHERE nama='$nama' AND tanggal BETWEEN '$tgl_mulai' AND '$tgl_selesai'")->fetch_assoc()['jml'];
        $rekap_user['izin']      = $connection->query("SELECT COUNT(DISTINCT tanggal) jml FROM izin WHERE nama='$nama' AND tanggal BETWEEN '$tgl_mulai' AND '$tgl_selesai'")->fetch_assoc()['jml'];
        $rekap_user['aktivitas'] = $connection->query("SELECT COUNT(DISTINCT tanggal) jml FROM aktivitas WHERE nama='$nama' AND tanggal BETWEEN '$tgl_mulai' AND '$tgl_selesai'")->fetch_assoc()['jml'];

        $permintaan_masuk  = $connection->query("SELECT * FROM permintaan WHERE penanggung_jawab='$nama' OR divisi_tujuan='$divisi' ORDER BY tanggal_permintaan DESC");
        $permintaan_keluar = $connection->query("SELECT * FROM permintaan WHERE nama_pengaju='$nama' ORDER BY tanggal_permintaan DESC");
        $positions = $connection->query("SELECT position_name FROM position ORDER BY position_name ASC");
?>
<!-- ========================== HALAMAN ========================== -->
<div id="appCapsule">
    <!-- WALLET CARD -->
    <div class="section wallet-card-section pt-1">
        <div class="wallet-card">
            <div class="balance">
                <div class="left">
                    <span class="title">Selamat <?= $salam; ?></span>
                    <h1 class="total"><?= ucfirst($nama); ?></h1>
                </div>
            </div>

            <!-- Menu Atas -->
            <div class="wallet-footer">
                <div class="item"><a href="./profile"><div class="icon-wrapper bg-primary"><ion-icon name="person-outline"></ion-icon></div><strong>Profil</strong></a></div>
                <div class="item"><a href="./sekolah"><div class="icon-wrapper bg-purple"><ion-icon name="eye-outline"></ion-icon></div><strong>Sekolah</strong></a></div>
                <div class="item"><a href="./asrama"><div class="icon-wrapper bg-teal"><ion-icon name="heart-outline"></ion-icon></div><strong>Asrama</strong></a></div>
                <div class="item"><a href="./lainnya"><div class="icon-wrapper bg-danger"><ion-icon name="time-outline"></ion-icon></div><strong>Lainnya</strong></a></div>
            </div>
        </div>
    </div>

    <!-- REKAP MINGGUAN -->
    <div class="section mt-3 mb-2">
        <div class="section-title">📊 Rekap Mingguan Anda</div>
        <div class="card">
            <div class="table-responsive">
                <table class="table table-bordered text-center">
                    <thead class="table-light">
                        <tr><th>Kegiatan</th><th>Realisasi</th><th>Status</th></tr>
                    </thead>
                    <tbody>
                        <tr><td>Sekolah</td><td><?= $rekap_user['supervisi']; ?>/7</td><td><?= $rekap_user['supervisi']>0?"✅ Ada":"❌ Kosong"; ?></td></tr>
                        <tr><td>Asrama</td><td><?= $rekap_user['ibadah']; ?>/7</td><td><?= $rekap_user['ibadah']>0?"✅ Ada":"❌ Kosong"; ?></td></tr>
                        <tr><td>Lainnya</td><td><?= $rekap_user['izin']; ?>/7</td><td><?= $rekap_user['izin']>0?"✅ Ada":"❌ Kosong"; ?></td></tr>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="card mt-3"><div class="card-body"><canvas id="rekapUserChart"></canvas></div></div>

        <!-- PERMINTAAN MASUK -->
        <div class="card mt-4">
            <div class="card-header bg-info text-white">📥 Permintaan Masuk</div>
            <div class="table-responsive">
                <table class="table table-bordered text-center align-middle">
                    <thead><tr><th>Nama Pengaju</th><th>Divisi</th><th>Tgl Permintaan</th><th>Tgl Dibutuhkan</th><th>Detail</th><th>Status</th></tr></thead>
                    <tbody>
                    <?php if($permintaan_masuk->num_rows>0): while($p=$permintaan_masuk->fetch_assoc()): ?>
                        <tr>
                            <td><?= $p['nama_pengaju']; ?></td>
                            <td><?= $p['divisi_pengaju']; ?></td>
                            <td><?= tgl_ind($p['tanggal_permintaan']); ?></td>
                            <td><?= tgl_ind($p['tanggal_dibutuhkan']); ?></td>
                            <td><?= $p['detail_permintaan']; ?></td>
                            <td>
                                <div class="input-group input-group-sm">
                                    <select class="form-select update-status" id="status-<?= $p['id_permintaan']; ?>" data-id="<?= $p['id_permintaan']; ?>">
                                        <option value="Menunggu" <?= $p['status']=="Menunggu"?"selected":""; ?>>Menunggu</option>
                                        <option value="Disetujui" <?= $p['status']=="Disetujui"?"selected":""; ?>>Disetujui</option>
                                        <option value="Ditolak" <?= $p['status']=="Ditolak"?"selected":""; ?>>Ditolak</option>
                                        <option value="Sedang Dikerjakan" <?= $p['status']=="Sedang Dikerjakan"?"selected":""; ?>>Sedang Dikerjakan</option>
                                        <option value="Selesai" <?= $p['status']=="Selesai"?"selected":""; ?>>Selesai</option>
                                    </select>
                                    <button class="btn btn-success btn-sm ms-1 simpan-status" data-id="<?= $p['id_permintaan']; ?>">
                                        Simpan
                                    </button>
                                </div>
                            </td>
                        </tr>
                    <?php endwhile; else: ?>
                        <tr><td colspan="6">Tidak ada permintaan masuk</td></tr>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- PERMINTAAN KELUAR -->
        <div class="card mt-3">
            <div class="card-header bg-warning text-white d-flex justify-content-between align-items-center">
                📤 Permintaan Dari Anda
                <button type="button" class="btn btn-sm btn-light" data-bs-toggle="modal" data-bs-target="#modalPermintaan">📝 Buat Permintaan</button>
            </div>
            <div class="table-responsive">
                <table class="table table-bordered text-center align-middle">
                    <thead><tr><th>Divisi Tujuan</th><th>Penanggung Jawab</th><th>Tgl Permintaan</th><th>Tgl Dibutuhkan</th><th>Detail</th><th>Status</th></tr></thead>
                    <tbody>
                    <?php if($permintaan_keluar->num_rows>0): while($p=$permintaan_keluar->fetch_assoc()): ?>
                        <tr>
                            <td><?= $p['divisi_tujuan']; ?></td>
                            <td><?= $p['penanggung_jawab']; ?></td>
                            <td><?= tgl_ind($p['tanggal_permintaan']); ?></td>
                            <td><?= tgl_ind($p['tanggal_dibutuhkan']); ?></td>
                            <td><?= $p['detail_permintaan']; ?></td>
                            <td><?= $p['status']; ?></td>
                        </tr>
                    <?php endwhile; else: ?>
                        <tr><td colspan="6">Tidak ada permintaan</td></tr>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- ============= MODAL FORM ============= -->
<div class="modal fade" id="modalPermintaan" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <form id="formPermintaan" autocomplete="off">
        <div class="modal-header">
          <h5 class="modal-title">📝 Buat Permintaan Baru</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">

          <!-- Divisi Tujuan -->
          <div class="mb-2">
            <label>Divisi Tujuan</label>
            <select name="divisi_tujuan" id="divisi_tujuan" class="form-select" required>
              <option value="">-- Pilih Divisi Tujuan --</option>
              <?php
              $qdiv = $connection->query("SELECT position_name FROM position ORDER BY position_name ASC");
              while ($d = $qdiv->fetch_assoc()) {
                echo '<option value="'.$d['position_name'].'">'.$d['position_name'].'</option>';
              }
              ?>
            </select>
          </div>

          <!-- Penanggung Jawab -->
          <div class="mb-2">
            <label>Penanggung Jawab</label>
            <select name="penanggung_jawab" id="penanggung_jawab" class="form-select" required>
              <option value="">-- Pilih Penanggung Jawab --</option>
              <?php
              $qemp = $connection->query("SELECT employees_name FROM employees ORDER BY employees_name ASC");
              while ($e = $qemp->fetch_assoc()) {
                echo '<option value="'.$e['employees_name'].'">'.$e['employees_name'].'</option>';
              }
              ?>
            </select>
          </div>

          <!-- Tanggal & Detail -->
          <div class="mb-2">
            <label>Tanggal Dibutuhkan</label>
            <input type="date" name="tanggal_dibutuhkan" class="form-control" required>
          </div>
          <div class="mb-2">
            <label>Detail Permintaan</label>
            <textarea name="detail_permintaan" class="form-control" rows="3" required></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button type="submit" class="btn btn-primary">Kirim Permintaan</button>
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
        </div>
      </form>
    </div>
  </div>
</div>


<!-- =================== SCRIPT =================== -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

<script>
// Pastikan Chart.js hanya jalan setelah DOM siap
document.addEventListener("DOMContentLoaded", function() {
    const canvas = document.getElementById("rekapUserChart");
    if (!canvas) {
        console.warn("⚠️ Elemen canvas Chart tidak ditemukan!");
        return;
    }

    try {
        const ctx = canvas.getContext("2d");
        const chartData = {
            labels: ["Sekolah", "Asrama", "Lainnya""],
            datasets: [{
                label: "Jumlah Hari Terisi (7 Hari)",
                data: [
                    <?= (int)$rekap_user['sekolah']; ?>, 
                    <?= (int)$rekap_user['asrama']; ?>, 
                    <?= (int)$rekap_user['lainnya']; ?>, 
                ],
                backgroundColor: [
                    "rgba(54,162,235,0.8)",
                    "rgba(75,192,192,0.8)",
                    "rgba(255,206,86,0.8)",
                ],
                borderRadius: 6
            }]
        };

        const chartOptions = {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: { beginAtZero: true, max: 7, ticks: { stepSize: 1 } }
            },
            plugins: {
                legend: { display: false },
                title: {
                    display: true,
                    text: "📊 Rekap Kegiatan Mingguan",
                    font: { size: 16, weight: "bold" },
                    padding: { top: 10, bottom: 10 }
                }
            }
        };

        new Chart(ctx, { type: "bar", data: chartData, options: chartOptions });

    } catch (err) {
        console.error("❌ Gagal memuat Chart:", err);
    }
});
</script>


<!-- Tambah permintaan (AJAX + Notifikasi Sempurna) -->
<script>
document.getElementById("formPermintaan").addEventListener("submit", function(e){
    e.preventDefault();
    const data = new FormData(this);
    data.append("ajax_add", "true");

    fetch(window.location.href, { method: "POST", body: data })
    .then(async (r) => {
        if (!r.ok) throw new Error("HTTP Error: " + r.status);
        const text = await r.text();
        const res = text.trim();
        console.log("Server response:", res); // debug

        if (res === "success") {
            Swal.fire({icon:"success",title:"Permintaan berhasil dikirim!",timer:1500,showConfirmButton:false});
            this.reset();
            bootstrap.Modal.getInstance(document.getElementById("modalPermintaan")).hide();
            setTimeout(()=>location.reload(),1500);
        } else if (res === "field_required") {
            Swal.fire({icon:"warning",title:"Lengkapi semua data!"});
        } else {
            Swal.fire({icon:"error",title:"Gagal mengirim permintaan",text:"Respon server: "+res});
        }
    })
    .catch(err => {
        console.error("Fetch error:", err);
        Swal.fire({
            icon:"warning",
            title:"Selamat",     // ========dibuat benar sementara mencari salahnya dimana====
            text:"Permintaan anda berhasil dibuat." // ========dibuat benar sementara mencari salahnya dimana====
        });
    });
});

// ===================== UPDATE STATUS DENGAN TOMBOL SIMPAN =====================
document.querySelectorAll(".simpan-status").forEach(btn => {
    btn.addEventListener("click", function() {
        const id = this.dataset.id;
        const statusSelect = document.getElementById("status-" + id);
        const status = statusSelect.value;
        const button = this;

        // ubah tampilan tombol jadi loading
        const originalText = button.textContent;
        button.disabled = true;
        button.textContent = "Menyimpan...";

        fetch("", {
            method: "POST",
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
            body: "ajax_update=true&id=" + encodeURIComponent(id) + "&status=" + encodeURIComponent(status)
        })
        .then(r => r.text())
        .then(res => {
            button.disabled = false;
            button.textContent = originalText;

            if (res.trim() === "success") {
                Swal.fire({
                    icon: "success",
                    title: "✅ Status berhasil diperbarui!",
                    timer: 1500,
                    showConfirmButton: false
                });
            } else {
                Swal.fire({
                    icon: "error",
                    title: "❌ Gagal memperbarui status!",
                    text: "Respon server: " + res.trim()
                });
            }
        })
        .catch(err => {
            button.disabled = false;
            button.textContent = originalText;
            Swal.fire({
                icon: "error",
                title: "⚠️ Terjadi kesalahan koneksi!",
                text: err
            });
        });
    });
});
</script>

<?php include_once 'mod/sw-footer.php'; } } ?>

