<?php
$page_title = 'Kelola Profil LPM';
require_once __DIR__ . '/../config/secure_bootstrap.php';
include __DIR__ . '/includes/header.php';

$alert = ''; // penampung pesan SweetAlert

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['id_profil'] ?? null;
    $judul = trim($_POST['judul']);
    $slug = $_POST['slug'] ?: strtolower(str_replace(' ', '-', $judul));
    $isi = $_POST['isi'];
    $urutan = $_POST['urutan'] ?? 0;
    $status = $_POST['status'] ?? 'inactive';

    // Upload gambar (pastikan folder ada)
    $gambar = null;
    $uploadDir = __DIR__ . '/../uploads/profile/';
    if (!is_dir($uploadDir)) mkdir($uploadDir, 0775, true);

    if (isset($_FILES['gambar']) && $_FILES['gambar']['error'] === 0) {
        $ext = pathinfo($_FILES['gambar']['name'], PATHINFO_EXTENSION);
        $namaBaru = uniqid('profil_') . '.' . strtolower($ext);
        move_uploaded_file($_FILES['gambar']['tmp_name'], $uploadDir . $namaBaru);
        $gambar = $namaBaru;
    }

    try {
        if (isset($_POST['tambah'])) {
            $stmt = $pdo->prepare("INSERT INTO profiles (judul, slug, isi, gambar, urutan, status, created_by) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$judul, $slug, $isi, $gambar, $urutan, $status, $_SESSION['user_id'] ?? null]);
            $alert = "Swal.fire('Berhasil!', 'Profil berhasil ditambahkan.', 'success')";
        }

        if (isset($_POST['edit'])) {
            if ($gambar) {
                $old = $pdo->prepare("SELECT gambar FROM profiles WHERE id_profil=?");
                $old->execute([$id]);
                $lama = $old->fetchColumn();
                if ($lama && file_exists($uploadDir . $lama)) unlink($uploadDir . $lama);

                $stmt = $pdo->prepare("UPDATE profiles SET judul=?, slug=?, isi=?, gambar=?, urutan=?, status=?, updated_by=? WHERE id_profil=?");
                $stmt->execute([$judul, $slug, $isi, $gambar, $urutan, $status, $_SESSION['user_id'] ?? null, $id]);
            } else {
                $stmt = $pdo->prepare("UPDATE profiles SET judul=?, slug=?, isi=?, urutan=?, status=?, updated_by=? WHERE id_profil=?");
                $stmt->execute([$judul, $slug, $isi, $urutan, $status, $_SESSION['user_id'] ?? null, $id]);
            }
            $alert = "Swal.fire('Berhasil!', 'Profil berhasil diperbarui.', 'success')";
        }
    } catch (Exception $e) {
        $alert = "Swal.fire('Gagal!', '".addslashes($e->getMessage())."', 'error')";
    }
}

if (isset($_GET['delete'])) {
    $id = $_GET['delete'];
    $get = $pdo->prepare("SELECT gambar FROM profiles WHERE id_profil=?");
    $get->execute([$id]);
    $gambar = $get->fetchColumn();
    $uploadDir = __DIR__ . '/../uploads/profile/';
    if ($gambar && file_exists($uploadDir . $gambar)) unlink($uploadDir . $gambar);

    $del = $pdo->prepare("DELETE FROM profiles WHERE id_profil=?");
    $del->execute([$id]);
    $alert = "Swal.fire('Dihapus!', 'Profil berhasil dihapus.', 'success')";
}

$stmt = $pdo->query("SELECT * FROM profiles ORDER BY urutan ASC");
$profile_list = $stmt->fetchAll();
?>

<style>
.tox-dialog {
    z-index: 999999 !important;
}

</style>

<div class="card">
  <div class="card-header d-flex justify-content-between align-items-center">
      <span><i class="fas fa-building"></i> Kelola Profil LPM</span>
      <button class="btn btn-light btn-sm" data-bs-toggle="modal" data-bs-target="#modalTambah">
          <i class="fas fa-plus"></i> Tambah Profil
      </button>
  </div>

  <div class="card-body">
      <?php if (!$profile_list): ?>
          <div class="alert alert-warning text-center">
              <i class="fas fa-exclamation-triangle"></i> Belum ada data profil.
          </div>
      <?php else: ?>
          <div class="table-responsive">
              <table class="table table-hover align-middle">
                  <thead>
                      <tr>
                          <th width="40">No</th>
                          <th>Judul</th>
                          <th>Slug</th>
                          <th>Gambar</th>
                          <th>Status</th>
                          <th>Urutan</th>
                          <th>Update</th>
                          <th width="120">Aksi</th>
                      </tr>
                  </thead>
                  <tbody>
                      <?php foreach ($profile_list as $i => $item): ?>
                      <tr>
                          <td><?= $i + 1 ?></td>
                          <td><strong><?= clean($item['judul']) ?></strong></td>
                          <td><code><?= clean($item['slug']) ?></code></td>
                          <td>
                              <?php if ($item['gambar']): ?>
                                  <img src="<?= $base_url ?>../uploads/profile/<?= $item['gambar'] ?>" width="60" height="40" style="object-fit:cover;border-radius:4px;">
                              <?php else: ?>
                                  <span class="text-muted">-</span>
                              <?php endif; ?>
                          </td>
                          <td><?= $item['status']=='active' ? '<span class="badge bg-success">Aktif</span>' : '<span class="badge bg-secondary">Nonaktif</span>' ?></td>
                          <td><span class="badge bg-info"><?= $item['urutan'] ?></span></td>
                          <td><small><?= date('d/m/Y H:i', strtotime($item['updated_at'])) ?></small></td>
                          <td>
                              <button class="btn btn-sm btn-warning" data-bs-toggle="modal" data-bs-target="#modalEdit<?= $item['id_profil'] ?>"><i class="fas fa-edit"></i></button>
                              <a href="?delete=<?= $item['id_profil'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Yakin hapus profil ini?')"><i class="fas fa-trash"></i></a>
                          </td>
                      </tr>

                      <!-- Modal Edit -->
                      <div class="modal fade" id="modalEdit<?= $item['id_profil'] ?>" tabindex="-1" aria-hidden="true">
                        <div class="modal-dialog modal-xl modal-dialog-centered">
                          <div class="modal-content border-0 shadow-lg">
                            <div class="modal-header bg-warning text-dark">
                              <h5 class="modal-title fw-bold"><i class="fas fa-edit me-2"></i>Edit Profil</h5>
                              <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>

                            <form method="POST" enctype="multipart/form-data">
                              <input type="hidden" name="id_profil" value="<?= $item['id_profil'] ?>">
                              <div class="modal-body p-4">
                                <div class="row g-4">
                                  <div class="col-md-8">
                                    <div class="mb-3">
                                      <label class="form-label">Judul</label>
                                      <input type="text" name="judul" class="form-control judul-edit" value="<?= htmlspecialchars($item['judul']) ?>" required>
                                    </div>
                                    <div class="mb-3">
                                      <label class="form-label">Slug</label>
                                      <input type="text" name="slug" class="form-control slug-edit" value="<?= htmlspecialchars($item['slug']) ?>">
                                    </div>
                                    <div class="mb-3">
                                      <label class="form-label">Konten</label>
                                      <textarea name="isi" class="form-control editorEdit" rows="8"><?= htmlspecialchars($item['isi']) ?></textarea>
                                    </div>
                                  </div>

                                  <div class="col-md-4">
                                    <div class="mb-3">
                                      <label class="form-label">Gambar</label>
                                      <?php if ($item['gambar']): ?>
                                          <img src="<?= $base_url ?>../uploads/profile/<?= $item['gambar'] ?>" class="img-fluid rounded mb-2 preview-edit">
                                      <?php endif; ?>
                                      <input type="file" name="gambar" class="form-control gambar-edit" accept="image/*">
                                    </div>
                                    <div class="mb-3">
                                      <label class="form-label">Urutan</label>
                                      <input type="number" name="urutan" class="form-control" value="<?= $item['urutan'] ?>">
                                    </div>
                                    <div class="mb-3">
                                      <label class="form-label">Status</label>
                                      <select name="status" class="form-select">
                                        <option value="active" <?= $item['status']=='active'?'selected':'' ?>>Aktif</option>
                                        <option value="inactive" <?= $item['status']=='inactive'?'selected':'' ?>>Nonaktif</option>
                                      </select>
                                    </div>
                                  </div>
                                </div>
                              </div>
                              <div class="modal-footer bg-light">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><i class="fas fa-arrow-left"></i> Kembali</button>
                                <button type="submit" name="edit" class="btn btn-warning text-dark"><i class="fas fa-save"></i> Simpan Perubahan</button>
                              </div>
                            </form>
                          </div>
                        </div>
                      </div>
                      <?php endforeach; ?>
                  </tbody>
              </table>
          </div>
      <?php endif; ?>
  </div>
</div>

<!-- Modal Tambah Profil -->
<div class="modal fade" id="modalTambah" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-xl modal-dialog-centered">
    <div class="modal-content border-0 shadow-lg">
      <div class="modal-header bg-success text-white">
        <h5 class="modal-title fw-bold"><i class="fas fa-plus-circle me-2"></i>Tambah Profil Baru</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>

      <form method="POST" enctype="multipart/form-data" id="formTambahProfil">
        <div class="modal-body p-4">
          <div class="row g-4">
            <div class="col-md-8">
              <div class="mb-3">
                <label class="form-label fw-semibold">Judul</label>
                <input type="text" name="judul" id="judulInput" class="form-control" required placeholder="Contoh: Sambutan Ketua, Visi & Misi, dst">
              </div>
              <div class="mb-3">
                <label class="form-label fw-semibold">Slug</label>
                <input type="text" name="slug" id="slugInput" class="form-control" placeholder="Slug otomatis dari judul">
              </div>
              <div class="mb-3">
                <label class="form-label fw-semibold">Konten</label>
                <textarea name="isi" id="editorKonten" rows="8" class="form-control"></textarea>
              </div>
            </div>

            <div class="col-md-4">
              <div class="mb-3">
                <label class="form-label fw-semibold">Gambar</label>
                <input type="file" name="gambar" class="form-control" accept="image/*" id="gambarInput">
                <img id="previewGambar" src="" class="img-fluid rounded mt-2 d-none">
              </div>
              <div class="mb-3">
                <label class="form-label fw-semibold">Urutan</label>
                <input type="number" name="urutan" class="form-control" value="0">
              </div>
              <div class="mb-3">
                <label class="form-label fw-semibold">Status</label>
                <select name="status" class="form-select">
                  <option value="active" selected>Aktif</option>
                  <option value="inactive">Nonaktif</option>
                </select>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer bg-light">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><i class="fas fa-arrow-left"></i> Kembali</button>
          <button type="submit" name="tambah" class="btn btn-success"><i class="fas fa-save"></i> Simpan Profil</button>
        </div>
      </form>
    </div>
  </div>
</div>

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

<!-- TinyMCE -->
<script src="https://cdn.jsdelivr.net/npm/tinymce@6.8.3/tinymce.min.js"></script>

<script>
/* ----------------------------------------------------
   Slug otomatis (Tambah)
---------------------------------------------------- */
document.getElementById('judulInput').addEventListener('input', function () {
    const slug = this.value
        .toLowerCase()
        .replace(/[^\w\s-]/g, '')
        .trim()
        .replace(/\s+/g, '-');

    document.getElementById('slugInput').value = slug;
});

/* ----------------------------------------------------
   Preview gambar (Tambah)
---------------------------------------------------- */
document.getElementById('gambarInput').addEventListener('change', e => {
    const file = e.target.files[0];
    if (!file) return;

    const r = new FileReader();
    r.onload = ev => {
        const img = document.getElementById('previewGambar');
        img.src = ev.target.result;
        img.classList.remove('d-none');
    };
    r.readAsDataURL(file);
});

/* ----------------------------------------------------
   Slug otomatis (Edit)
---------------------------------------------------- */
document.querySelectorAll('.judul-edit').forEach((input, idx) => {
    input.addEventListener('input', () => {
        const field = document.querySelectorAll('.slug-edit')[idx];
        field.value = input.value
            .toLowerCase()
            .replace(/[^\w\s-]/g, '')
            .trim()
            .replace(/\s+/g, '-');
    });
});

/* ----------------------------------------------------
   Preview gambar (Edit)
---------------------------------------------------- */
document.querySelectorAll('.gambar-edit').forEach((input, idx) => {
    input.addEventListener('change', e => {
        const file = e.target.files[0];
        if (!file) return;

        const r = new FileReader();
        r.onload = ev => {
            document.querySelectorAll('.preview-edit')[idx].src = ev.target.result;
        };
        r.readAsDataURL(file);
    });
});

/* ----------------------------------------------------
   INIT TINYMCE
---------------------------------------------------- */
tinymce.init({
    selector: 'textarea.editorEdit, #editorKonten',
    menubar: false,
    height: 350,
    plugins: 'link image lists table code',
    toolbar: 'undo redo | bold italic underline | bullist numlist | table | link image | alignleft aligncenter alignright | code',
    branding: false
});

/* ----------------------------------------------------
   FIX: Modal Bootstrap suka ambil fokus TinyMCE
---------------------------------------------------- */
document.addEventListener('focusin', function (e) {
    if (e.target.closest('.tox-dialog')) {
        e.stopPropagation();
    }
});
</script>


<!-- ====================================================
   FIX OVERLAY KHUSUS (yang kamu pakai & terbukti jalan)
==================================================== -->
<script>
(function(){

    if (window.__tinymce_modal_fix_installed) return;
    window.__tinymce_modal_fix_installed = true;

    /* ------------------------------
       Cari elemen yang menutupi dialog
    ------------------------------ */
    function getCoveringElementsForDialog(dialog) {
        if (!dialog) return [];

        const rect = dialog.getBoundingClientRect();
        const pts = [];
        const sx = Math.max(16, Math.floor(rect.width / 4));
        const sy = Math.max(16, Math.floor(rect.height / 4));

        for (let x = rect.left + 8; x < rect.right; x += sx) {
            for (let y = rect.top + 8; y < rect.bottom; y += sy) {
                pts.push([Math.round(x), Math.round(y)]);
            }
        }

        const result = new Set();

        pts.forEach(([x, y]) => {
            if (x < 0 || y < 0 || x > innerWidth || y > innerHeight) return;
            const el = document.elementFromPoint(x, y);
            if (!el) return;
            if (el.closest('.tox-dialog')) return;
            result.add(el);
        });

        return Array.from(result);
    }

    /* ------------------------------
       Disable pointer-events elemen penutup
    ------------------------------ */
    function disableCoveringElems(dialog) {
        const list = getCoveringElementsForDialog(dialog);

        list.forEach(el => {
            if (!el) return;

            if (el.dataset.__tinymce_orig_pe === undefined) {
                el.dataset.__tinymce_orig_pe = getComputedStyle(el).pointerEvents || 'auto';
            }

            el.style.pointerEvents = 'none';
        });

        return list;
    }

    /* ------------------------------
       Restore pointer-events
    ------------------------------ */
    function restoreCoveringElems(list) {
        if (!Array.isArray(list)) return;

        list.forEach(el => {
            if (!el) return;

            if (el.dataset.__tinymce_orig_pe !== undefined) {
                el.style.pointerEvents = el.dataset.__tinymce_orig_pe;
                delete el.dataset.__tinymce_orig_pe;
            }
        });
    }

    let lastDisabled = [];

    /* ------------------------------
       Observer — saat dialog muncul / hilang
    ------------------------------ */
    const mo = new MutationObserver(() => {
        const dialog = document.querySelector('.tox-dialog');

        if (dialog) {
            lastDisabled = disableCoveringElems(dialog);
        } else if (lastDisabled.length) {
            restoreCoveringElems(lastDisabled);
            lastDisabled = [];
        }
    });

    mo.observe(document.documentElement, { childList: true, subtree: true });

    /* cek awal */
    setTimeout(() => {
        const dlg = document.querySelector('.tox-dialog');
        if (dlg) lastDisabled = disableCoveringElems(dlg);
    }, 500);

    /* Extra guard fokus */
    document.addEventListener('focusin', function (e) {
        if (e.target.closest('.tox-dialog')) e.stopPropagation();
    }, true);

})();
</script>


<!-- SweetAlert -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<?php if (!empty($alert)): ?>
<script>
<?= $alert ?>;
setTimeout(() => { window.location.href = 'profil.php'; }, 1500);
</script>
<?php endif; ?>

