/* ============================================================
   نظام إدارة القضايا — main.js
   ============================================================ */

'use strict';

// ── Sidebar toggle ───────────────────────────────────────────
const sidebar  = document.getElementById('sidebar');
const overlay  = document.getElementById('sidebarOverlay');
const toggler  = document.getElementById('sidebarToggle');

if (toggler) {
  toggler.addEventListener('click', () => {
    sidebar.classList.toggle('open');
    overlay.classList.toggle('open');
  });
}
if (overlay) {
  overlay.addEventListener('click', () => {
    sidebar.classList.remove('open');
    overlay.classList.remove('open');
  });
}

// ── Notifications ────────────────────────────────────────────
const notifBtn      = document.getElementById('notifBtn');
const notifDropdown = document.getElementById('notifDropdown');
const notifList     = document.getElementById('notifList');
const markAllBtn    = document.getElementById('markAllRead');

if (notifBtn) {
  notifBtn.addEventListener('click', (e) => {
    e.stopPropagation();
    const isOpen = notifDropdown.classList.toggle('open');
    if (isOpen) loadNotifications();
  });
  document.addEventListener('click', (e) => {
    if (!notifBtn.contains(e.target) && !notifDropdown.contains(e.target)) {
      notifDropdown.classList.remove('open');
    }
  });
}

function loadNotifications() {
  if (!notifList) return;
  notifList.innerHTML = '<div class="notif-loading"><i class="bi bi-hourglass-split"></i> جاري التحميل...</div>';
  fetch(window.APP_BASE + '/api/notifications.php?action=list')
    .then(r => r.json())
    .then(data => {
      if (!data.length) {
        notifList.innerHTML = '<div class="notif-loading">لا توجد إشعارات</div>';
        return;
      }
      notifList.innerHTML = data.map(n => `
        <div class="notif-item ${n.is_read == 0 ? 'unread' : ''}" data-id="${n.id}" data-link="${n.link || ''}">
          <div class="notif-icon"><i class="bi bi-bell"></i></div>
          <div class="notif-body">
            <div class="notif-title">${n.title}</div>
            <div class="notif-msg">${n.message}</div>
            <div class="notif-time">${timeAgo(n.created_at)}</div>
          </div>
        </div>`).join('');

      notifList.querySelectorAll('.notif-item').forEach(item => {
        item.addEventListener('click', () => {
          const id   = item.dataset.id;
          const link = item.dataset.link;
          fetch(window.APP_BASE + `/api/notifications.php?action=read&id=${id}`);
          item.classList.remove('unread');
          if (link) window.location.href = link;
        });
      });
    })
    .catch(() => { notifList.innerHTML = '<div class="notif-loading">تعذّر تحميل الإشعارات</div>'; });
}

if (markAllBtn) {
  markAllBtn.addEventListener('click', (e) => {
    e.preventDefault();
    fetch(window.APP_BASE + '/api/notifications.php?action=read_all')
      .then(() => {
        document.querySelectorAll('.notif-item.unread').forEach(i => i.classList.remove('unread'));
        const badge = notifBtn.querySelector('.badge');
        if (badge) badge.remove();
      });
  });
}

// ── DataTables init ──────────────────────────────────────────
document.addEventListener('DOMContentLoaded', () => {
  const tables = document.querySelectorAll('.dt-table');
  if (tables.length && typeof $.fn.DataTable !== 'undefined') {
    tables.forEach(t => {
      $(t).DataTable({
        language: {
          search:         'بحث:',
          lengthMenu:     'عرض _MENU_ سجلات',
          info:           'عرض _START_ إلى _END_ من _TOTAL_ سجل',
          infoEmpty:      'لا توجد سجلات',
          paginate:       { first:'الأول', last:'الأخير', next:'التالي', previous:'السابق' },
          zeroRecords:    'لا توجد نتائج',
          infoFiltered:   '(مفلترة من _MAX_ سجل)',
          emptyTable:     'لا توجد بيانات',
        },
        order: [],
        pageLength: 15,
        responsive: true,
      });
    });
  }
});

// ── Upload zone drag & drop ──────────────────────────────────
document.querySelectorAll('.upload-zone').forEach(zone => {
  const input = zone.querySelector('input[type="file"]');
  zone.addEventListener('click', () => input && input.click());
  zone.addEventListener('dragover', e => { e.preventDefault(); zone.classList.add('drag-over'); });
  zone.addEventListener('dragleave', () => zone.classList.remove('drag-over'));
  zone.addEventListener('drop', e => {
    e.preventDefault();
    zone.classList.remove('drag-over');
    if (input && e.dataTransfer.files.length) {
      input.files = e.dataTransfer.files;
      zone.querySelector('p').textContent = e.dataTransfer.files[0].name;
    }
  });
  if (input) {
    input.addEventListener('change', () => {
      if (input.files[0]) zone.querySelector('p').textContent = input.files[0].name;
    });
  }
});

// ── Export helpers ───────────────────────────────────────────
window.exportTableExcel = function(tableId, filename) {
  const wb = XLSX.utils.book_new();
  const ws = XLSX.utils.table_to_sheet(document.getElementById(tableId));
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
  XLSX.writeFile(wb, (filename || 'export') + '.xlsx');
};

window.printSection = function(sectionId) {
  const content = document.getElementById(sectionId).innerHTML;
  const w = window.open('', '_blank');
  w.document.write(`<html dir="rtl"><head>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.rtl.min.css">
    <style>body{font-family:'Cairo',sans-serif;padding:20px}</style>
    </head><body>${content}</body></html>`);
  w.document.close();
  w.print();
};

// ── Confirm delete ───────────────────────────────────────────
document.querySelectorAll('[data-confirm]').forEach(el => {
  el.addEventListener('click', e => {
    if (!confirm(el.dataset.confirm || 'هل أنت متأكد؟')) e.preventDefault();
  });
});

// ── Time ago (Arabic) ────────────────────────────────────────
function timeAgo(dateStr) {
  const diff = Math.floor((Date.now() - new Date(dateStr)) / 1000);
  if (diff < 60)    return 'الآن';
  if (diff < 3600)  return Math.floor(diff/60) + ' دقيقة';
  if (diff < 86400) return Math.floor(diff/3600) + ' ساعة';
  return Math.floor(diff/86400) + ' يوم';
}

// ── Flash messages auto-dismiss ──────────────────────────────
setTimeout(() => {
  document.querySelectorAll('.alert-dismissible').forEach(a => {
    a.style.transition = 'opacity .4s';
    a.style.opacity = '0';
    setTimeout(() => a.remove(), 400);
  });
}, 4000);
