<!-- ✅ CORE LIBRARIES -->
<script src="<?= base_url('assets/vendor/jquery/jquery.min.js'); ?>"></script>
<script src="<?= base_url('assets/vendor/bootstrap/js/bootstrap.bundle.min.js'); ?>"></script>
<script src="<?= base_url('assets/vendor/jquery-easing/jquery.easing.min.js'); ?>"></script>
<script src="<?= base_url('assets/js/sb-admin-2.min.js'); ?>"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<!-- SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>


<script>
$(function() {
  // =========================================
  // SIDEBAR CUSTOM TOGGLE (fix mobile & desktop)
  // =========================================
  const wrapper = $('#wrapper');
  const sidebar = $('#accordionSidebar');
  const toggleBtn = $('#sidebarToggle');
  const contentWrapper = $('#content-wrapper');

  if (!wrapper.length || !sidebar.length || !toggleBtn.length) return;

  // Matikan event toggle bawaan
  $('#sidebarToggle, #sidebarToggleTop').off('click');

  // Setup awal (sidebar tertutup)
  wrapper.addClass('toggled');
  sidebar.css({ transform: 'translateX(-100%)', transition: 'all 0.3s ease-in-out' });
  contentWrapper.css({ transform: 'translateX(0)', transition: 'all 0.3s ease-in-out' });

  // Tombol toggle
  toggleBtn.on('click', function(e) {
    e.preventDefault();
    const isMobile = window.innerWidth <= 768;
    wrapper.toggleClass('toggled');

    if (isMobile) {
      if (wrapper.hasClass('toggled')) {
        sidebar.css('transform', 'translateX(-100%)');
        contentWrapper.css('transform', 'translateX(0)');
      } else {
        sidebar.css('transform', 'translateX(0)');
        contentWrapper.css('transform', 'translateX(6.5rem)');
      }
    } else {
      sidebar.css('transform', '');
      contentWrapper.css('transform', '');
    }
  });

  // Reset transform saat resize
  $(window).on('resize', function() {
    if (window.innerWidth > 768) {
      sidebar.css('transform', '');
      contentWrapper.css('transform', '');
    } else if (wrapper.hasClass('toggled')) {
      sidebar.css('transform', 'translateX(-100%)');
      contentWrapper.css('transform', 'translateX(0)');
    }
  });
});
</script>

<!-- =====================
     📸 HANDLE IMAGE UPLOAD + PREVIEW (Refactored)
===================== -->
<script>
async function handleImageUpload(input, previewId) {
  try {
    const file = input.files[0];
    if (!file) return;

    // 🔹 Validasi tipe file
    if (!file.type.startsWith('image/')) {
      alertSwal('Oops!', 'File yang diunggah harus berupa gambar.', 'warning');
      input.value = '';
      return;
    }

    // 🔹 Validasi ukuran awal (max 10MB)
    if (file.size > 10 * 1024 * 1024) {
      alertSwal('Ukuran Terlalu Besar!', 'Maksimum 10MB per gambar sebelum kompresi.', 'error');
      input.value = '';
      return;
    }

    // 🔹 Baca gambar sebagai dataURL
    const reader = new FileReader();
    reader.readAsDataURL(file);

    reader.onload = async function (e) {
      const img = new Image();
      img.src = e.target.result;

      img.onload = async function () {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');

        let width = img.width;
        let height = img.height;

        // 🔁 Rotasi otomatis (landscape default)
        if (height > width) {
          canvas.width = height;
          canvas.height = width;
          ctx.translate(height, 0);
          ctx.rotate(90 * Math.PI / 180);
        } else {
          canvas.width = width;
          canvas.height = height;
        }

        ctx.drawImage(img, 0, 0);

        // 💾 Kompres sesuai besar gambar
        let targetSize = 2 * 1024 * 1024; // target 2MB
        let quality = 0.85;
        let blob = await getCompressedBlob(canvas, quality);

        // adaptif: jika gambar > 4MB, turunin kualitas; jika kecil, jangan overcompress
        while (blob.size > targetSize && quality > 0.4) {
          quality -= 0.1;
          blob = await getCompressedBlob(canvas, quality);
        }

        // 🔍 Tampilkan Preview
        const preview = document.getElementById(previewId);
        if (!preview) {
          console.warn(`Preview element #${previewId} not found.`);
          return;
        }

        // hapus URL lama kalau ada
        if (preview.dataset.url) URL.revokeObjectURL(preview.dataset.url);

        const blobUrl = URL.createObjectURL(blob);
        preview.src = blobUrl;
        preview.dataset.url = blobUrl;
        preview.classList.remove('d-none');
        preview.style.display = 'block';
        preview.style.maxWidth = '100%';
        preview.style.border = '2px solid #e9ecef';
        preview.style.borderRadius = '10px';
        preview.style.marginTop = '8px';

        // ✏️ Ganti file di input jadi hasil kompres
        const compressedFile = new File([blob], renameFile(file.name), { type: 'image/jpeg' });
        const dt = new DataTransfer();
        dt.items.add(compressedFile);
        input.files = dt.files;
      };
    };

  } catch (err) {
    console.error(err);
    alertSwal('Error!', 'Terjadi kesalahan saat memproses gambar.', 'error');
  }
}

/* Helper: convert canvas → Blob async */
function getCompressedBlob(canvas, quality) {
  return new Promise(resolve => {
    canvas.toBlob(blob => resolve(blob), 'image/jpeg', quality);
  });
}

/* Helper: dataURL → Blob (fallback) */
function dataURLtoBlob(dataURL) {
  const arr = dataURL.split(',');
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) u8arr[n] = bstr.charCodeAt(n);
  return new Blob([u8arr], { type: mime });
}

/* Helper: rename file biar unik (timestamp suffix) */
function renameFile(name) {
  const ext = name.split('.').pop().toLowerCase();
  const base = name.substring(0, name.lastIndexOf('.')) || 'IMG';
  return `${base}_${Date.now()}.${ext}`;
}

/* SweetAlert fallback-safe */
function alertSwal(title, text, icon) {
  if (typeof Swal !== 'undefined') {
    Swal.fire(title, text, icon);
  } else {
    alert(`${title}\n${text}`);
  }
}
</script>


<script>
/**
 * Buka picker file dengan mode:
 * - 'camera'  -> set capture="environment" (kamera belakang)
 * - 'gallery' -> hapus capture agar buka galeri/file manager
 */
function openPicker(inputId, mode) {
  const input = document.getElementById(inputId);
  if (!input) return;

  // pastikan accept sudah benar
  input.setAttribute('accept', 'image/*');

  if (mode === 'camera') {
    // environment = kamera belakang; untuk selfie bisa 'user'
    input.setAttribute('capture', 'environment');
  } else {
    // galeri: hapus attribute capture
    input.removeAttribute('capture');
  }

  // trigger pemilihan file
  input.click();
}
</script>


<script>
<?php if ($this->session->flashdata('success')): ?>
Swal.fire({
  icon: 'success',
  title: 'Berhasil!',
  text: '<?= $this->session->flashdata('success'); ?>',
  timer: 2500,
  showConfirmButton: false
});
<?php endif; ?>

<?php if ($this->session->flashdata('error')): ?>
Swal.fire({
  icon: 'error',
  title: 'Oops!',
  text: '<?= $this->session->flashdata('error'); ?>',
  timer: 3000,
  showConfirmButton: false
});
<?php endif; ?>
</script>

<script>
document.querySelectorAll('.btn-delete').forEach(btn => {
  btn.addEventListener('click', function(e) {
    e.preventDefault();
    const url = this.getAttribute('data-url');
    Swal.fire({
      title: 'Yakin hapus data ini?',
      text: "Data yang dihapus tidak dapat dikembalikan!",
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#d33',
      cancelButtonColor: '#6c757d',
      confirmButtonText: 'Ya, hapus!',
      cancelButtonText: 'Batal'
    }).then((result) => {
      if (result.isConfirmed) {
        window.location.href = url;
      }
    });
  });
});
</script>

<script>
function validateForm() {
  const name = document.querySelector('[name="name"]').value.trim();
  const email = document.querySelector('[name="email"]').value.trim();
  const pass = document.querySelector('[name="password"]').value.trim();
  const role = document.querySelector('[name="role"]').value.trim();
  if (!name || !email || !pass || !role) {
    Swal.fire('Oops!', 'Semua field wajib diisi!', 'warning');
    return false;
  }
  return true;
}
</script>



<style>
/* ======================
   SIDEBAR FIX FINAL
====================== */

/* Sidebar utama */
#accordionSidebar {
    width: 7rem;
    position: fixed;
    top: 0;
    left: 0;
    height: 100vh;
    z-index: 1030;
    transition: all 0.3s ease-in-out;
}

/* Sidebar tertutup (desktop) */
#wrapper.toggled #accordionSidebar {
    margin-left: -14rem;
}

/* Konten utama */
#content-wrapper {
    transition: all 0.3s ease-in-out;
    margin-left: 0;
}

/* Saat sidebar terbuka di desktop */
@media (min-width: 769px) {
    #wrapper:not(.toggled) #content-wrapper {
        margin-left: 14rem;
    }
}

/* ======================
   MOBILE BEHAVIOR
====================== */
@media (max-width: 500px) {
    #accordionSidebar {
        width: 7rem; /* << kecilin di sini */
        transform: translateX(0rem);
        position: fixed;
        top: 0;
        left: 0;
        background-color: #4e73df;
        z-index: 1030;
    }

    #wrapper:not(.toggled) #accordionSidebar {
        transform: translateX(0);

    }

    /* Konten geser dikit pas sidebar muncul */
    #content-wrapper {
        transform: translateX(0);
    }

    #wrapper:not(.toggled) #content-wrapper {
        transform: translateX(0rem); /* << sesuaikan juga sama width sidebar */
    }

    select.form-control {
        text-transform: uppercase;
        font-weight: 500;
        }

}

</style>
