// (اختياري) مكان لأي تحسينات UI لاحقاً

// v0.2 Dashboard charts (Chart.js via CDN optional)
async function renderDashboardCharts(){
  const el = document.querySelector('[data-dashboard-charts]');
  if(!el) return;

  // Load Chart.js CDN if not present
  if(typeof Chart === 'undefined'){
    try{
      await new Promise((resolve,reject)=>{
        const s=document.createElement('script');
        s.src='https://cdn.jsdelivr.net/npm/chart.js';
        s.onload=resolve; s.onerror=reject;
        document.head.appendChild(s);
      });
    }catch(e){
      console.warn('Chart.js not available (offline).');
      return;
    }
  }

  try{
    const res = await fetch('api/dashboard.php',{credentials:'same-origin'});
    const data = await res.json();

    const ctx1=document.getElementById('chartMaintenanceStatus');
    if(ctx1){
      new Chart(ctx1,{type:'doughnut',data:{labels:data.maintenanceStatus.labels,datasets:[{data:data.maintenanceStatus.values}]},options:{responsive:true}});
    }

    const ctx2=document.getElementById('chartMonthly');
    if(ctx2){
      new Chart(ctx2,{type:'bar',data:{labels:data.monthly.labels,datasets:[
        {label:'إجمالي البلاغات',data:data.monthly.total},
        {label:'منجز',data:data.monthly.done},
      ]},options:{responsive:true,scales:{y:{beginAtZero:true}}}});
    }
  }catch(e){
    console.warn('Dashboard API error', e);
  }
}

document.addEventListener('DOMContentLoaded', renderDashboardCharts);

// v0.3.6.0 - Date/Datetime pickers (HTML5) across the system
// الهدف: أي حقل تاريخ/وقت يُظهر للمستخدم أداة اختيار (date / datetime-local / month)
function enhanceDateFields(){
  const inputs = Array.from(document.querySelectorAll('input'))
    .filter(i => !i.disabled && i.type !== 'hidden' && i.type !== 'file' && i.type !== 'password');

  const toDatetimeLocalValue = (v) => {
    if (!v) return '';
    v = String(v).trim();
    // 2025-12-28 14:30:00 -> 2025-12-28T14:30
    if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}/.test(v)) {
      return v.replace(' ', 'T').slice(0, 16);
    }
    // 2025-12-28T14:30:00 -> 2025-12-28T14:30
    if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/.test(v)) {
      return v.slice(0, 16);
    }
    return v;
  };

  const looksLikeDate = (v) => /^\d{4}-\d{2}-\d{2}$/.test(String(v || '').trim());
  const looksLikeMonth = (v) => /^\d{4}-\d{2}$/.test(String(v || '').trim());
  const looksLikeDatetime = (v) => /^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}/.test(String(v || '').trim());

  for (const i of inputs) {
    const name = (i.getAttribute('name') || '').toLowerCase();
    const ph = (i.getAttribute('placeholder') || '').toLowerCase();

    // month
    if (i.type === 'text' && (ph.includes('yyyy-mm') || name === 'month' || name.endsWith('_month'))) {
      if (looksLikeMonth(i.value) || i.value === '') i.type = 'month';
      continue;
    }

    // datetime-local (reported_at وغيره)
    const wantDatetime = (
      ph.includes('hh:mm') ||
      name.includes('reported_at') ||
      name.includes('completed_at') ||
      name.includes('started_at') ||
      name.includes('ended_at')
    );

    // date
    const wantDate = (
      name.endsWith('_date') ||
      name.includes('due_date') ||
      name.includes('start_date') ||
      name.includes('end_date') ||
      name.includes('installed_at') ||
      name === 'from' || name === 'to' ||
      ph.includes('yyyy-mm-dd')
    );

    if (i.type === 'text' && wantDatetime) {
      // keep current value but normalize
      i.value = toDatetimeLocalValue(i.value);
      i.type = 'datetime-local';
      continue;
    }

    if ((i.type === 'text' || i.type === 'date') && wantDate) {
      // normalize values: keep only YYYY-MM-DD
      if (looksLikeDatetime(i.value)) i.value = String(i.value).trim().replace(' ', 'T').slice(0, 10);
      if (i.value === '' || looksLikeDate(i.value)) i.type = 'date';
      continue;
    }
  }
}

document.addEventListener('DOMContentLoaded', enhanceDateFields);
