(function () {
  'use strict';

  var API = '../api.php';

  function byId(id) { return document.getElementById(id); }

  function esc(v) {
    return String(v == null ? '' : v)
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;');
  }

  function getAuthToken() {
    try {
      return localStorage.getItem('ap_auth') || localStorage.getItem('admin_token') || '';
    } catch (e) {
      return '';
    }
  }

  async function apiGet(endpoint, payload) {
    var token = getAuthToken();
    var opts = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + token
      },
      body: JSON.stringify(Object.assign({ _method: 'GET' }, payload || {}))
    };
    var res = await fetch(API + '?route=' + encodeURIComponent(endpoint), opts);
    return res.json();
  }

  async function apiPost(endpoint, payload) {
    var token = getAuthToken();
    var opts = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + token
      },
      body: JSON.stringify(payload || {})
    };
    var res = await fetch(API + '?route=' + encodeURIComponent(endpoint), opts);
    return res.json();
  }

  function showError(msg) {
    var e = byId('esrError');
    if (!e) return;
    e.textContent = msg || 'تعذر تحميل التقرير.';
    e.style.display = 'block';
  }

  async function exportPdfDirect() {
    var page = byId('esrPage');
    if (!page) return showError('تعذر تجهيز التقرير للتصدير.');
    if (typeof window.html2pdf !== 'function') {
      return showError('مكتبة تصدير PDF غير متاحة حالياً.');
    }
    var btn = byId('esrPdfBtn');
    var oldText = btn ? btn.textContent : '';
    try {
      if (btn) {
        btn.disabled = true;
        btn.textContent = 'جارٍ الحفظ...';
      }
      await window.html2pdf()
        .set({
          margin: [6, 6, 6, 6],
          filename: (document.title || 'emp_short_report') + '.pdf',
          image: { type: 'jpeg', quality: 0.98 },
          html2canvas: { scale: 2, useCORS: true, backgroundColor: '#ffffff' },
          jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' },
          pagebreak: { mode: ['css', 'legacy'] }
        })
        .from(page)
        .save();
    } catch (e) {
      showError('فشل حفظ ملف PDF. حاول مرة أخرى.');
    } finally {
      if (btn) {
        btn.disabled = false;
        btn.textContent = oldText || 'تصدير PDF';
      }
    }
  }

  function toHHMM(ts) {
    if (!ts) return '—';
    var s = String(ts);
    return s.length >= 16 ? s.slice(11, 16) : '—';
  }

  function toMins(hhmm) {
    if (!hhmm || hhmm === '—') return null;
    var parts = String(hhmm).split(':');
    var h = parseInt(parts[0], 10);
    var m = parseInt(parts[1], 10);
    if (!Number.isFinite(h) || !Number.isFinite(m)) return null;
    return h * 60 + m;
  }

  function fmtBalance(b) {
    if (!b) return '0 / 0';
    var rem = Number(b.rem || 0);
    var total = Number(b.total || 0);
    return (Math.abs(rem - Math.round(rem)) < 0.001 ? String(Math.round(rem)) : rem.toFixed(2)) + ' / ' + total;
  }

  function statusShort(st) {
    if (st === 'present') return 'حضور';
    if (st === 'leave') return 'إجازة';
    if (st === 'official_holiday') return 'إجازة رسمية';
    if (st === 'weekend') return 'إجازة أسبوعية';
    return 'غياب';
  }

  function statusClass(st, isLate) {
    if (st === 'present' && isLate) return 'st-late';
    if (st === 'present') return 'st-present';
    if (st === 'leave') return 'st-leave';
    if (st === 'official_holiday') return 'st-official';
    if (st === 'weekend') return 'st-weekend';
    return 'st-absent';
  }

  function calcStats(rows, totals) {
    var stats = {
      present: 0,
      absent: 0,
      leave: 0,
      official: 0,
      weekend: 0,
      lateDays: 0,
      incomplete: 0,
      workHours: 0,
      earlyOut: 0
    };
    var totalHoursFromRows = 0;
    var hasHoursInRows = false;
    (rows || []).forEach(function (r) {
      if (r.status === 'present') stats.present += 1;
      else if (r.status === 'absent') stats.absent += 1;
      else if (r.status === 'leave') stats.leave += 1;
      else if (r.status === 'official_holiday') stats.official += 1;
      else if (r.status === 'weekend') stats.weekend += 1;

      var inTime = toHHMM(r.check_in);
      var outTime = toHHMM(r.check_out);
      var schIn = r.sch_in ? String(r.sch_in).slice(0, 5) : null;
      var schOut = r.sch_out ? String(r.sch_out).slice(0, 5) : null;
      if (r.status === 'present' && inTime !== '—' && schIn && toMins(inTime) > toMins(schIn)) stats.lateDays += 1;
      if (r.status === 'present' && outTime === '—') stats.incomplete += 1;
      if (r.status === 'present' && outTime !== '—' && schOut && toMins(outTime) < toMins(schOut)) stats.earlyOut += 1;

      var h = Number(r.work_hours);
      if (Number.isFinite(h)) {
        totalHoursFromRows += h;
        hasHoursInRows = true;
      }
    });
    if (totals && totals.work_hours_sum != null && totals.work_hours_sum !== '') {
      stats.workHours = Number(totals.work_hours_sum) || 0;
    } else if (hasHoursInRows) {
      stats.workHours = Number(totalHoursFromRows.toFixed(2));
    }
    if (totals && totals.incomplete_days != null) stats.incomplete = Number(totals.incomplete_days) || stats.incomplete;
    return stats;
  }

  function fillHeaderAndMeta(data, from, to, stats) {
    var p = data.employee_profile || {};
    var balances = data.balances || {};
    var totals = data.totals || {};

    byId('esrCompany').textContent = (localStorage.getItem('admin_company_name') || 'HR Pro');
    byId('esrEmployeeCode').textContent = p.employee_code || '—';
    var periodLine = from + ' → ' + to;
    byId('esrPeriod').textContent = periodLine;
    var fdP = byId('esrFdPeriod');
    if (fdP) fdP.textContent = periodLine;
    byId('esrGeneratedAt').textContent = new Date().toLocaleString('ar-EG');

    byId('esrName').textContent = p.name || '—';
    byId('esrDept').textContent = p.department || '—';
    byId('esrTitle').textContent = p.job_title || '—';
    byId('esrBranch').textContent = p.branch || '—';
    byId('esrNature').textContent = p.work_nature === 'external' ? 'خارجي' : 'داخلي';
    byId('esrPhone').textContent = p.phone || '—';

    byId('esrPresent').textContent = String(stats.present || 0);
    byId('esrAbsent').textContent = String(stats.absent || 0);
    byId('esrOfficial').textContent = String(stats.official || 0);
    byId('esrLateDays').textContent = String(stats.lateDays || 0);
    byId('esrWorkHours').textContent = String(stats.workHours || 0);
    byId('esrAnnual').textContent = fmtBalance(balances.annual);
    byId('esrCasual').textContent = fmtBalance(balances.casual);
    byId('esrSick').textContent = fmtBalance(balances.sick);
    byId('esrIncomplete').textContent = String(stats.incomplete || 0);

    var salDays = totals.salary_deduction_days != null && totals.salary_deduction_days !== ''
      ? Number(totals.salary_deduction_days)
      : 0;
    if (!Number.isFinite(salDays)) salDays = 0;
    var salEl = byId('esrSalaryDeduct');
    if (salEl) {
      salEl.textContent = Math.abs(salDays - Math.round(salDays)) < 0.001
        ? String(Math.round(salDays))
        : salDays.toFixed(2);
    }

    // Most browsers use document.title as the default PDF file name in print/save flow.
    var safeName = String(p.name || 'employee').replace(/[\\/:*?"<>|]+/g, '-').trim();
    var safeFrom = String(from || '').replace(/[\\/:*?"<>|]+/g, '-');
    var safeTo = String(to || '').replace(/[\\/:*?"<>|]+/g, '-');
    document.title = safeName + '_' + safeFrom + '_to_' + safeTo;
  }

  function getHolidayLabel(r) {
    if (!r) return 'إجازة رسمية';
    return r.holiday_name || r.official_holiday_name || r.holiday_title || r.note || 'إجازة رسمية';
  }

  function parseLocalYmd(ymd) {
    var p = String(ymd || '').split('-');
    if (p.length !== 3) return null;
    var y = parseInt(p[0], 10);
    var m = parseInt(p[1], 10);
    var d = parseInt(p[2], 10);
    if (!Number.isFinite(y) || !Number.isFinite(m) || !Number.isFinite(d)) return null;
    return new Date(y, m - 1, d, 12, 0, 0);
  }

  function formatLocalYmd(dt) {
    return dt.getFullYear() + '-' + String(dt.getMonth() + 1).padStart(2, '0') + '-' + String(dt.getDate()).padStart(2, '0');
  }

  var AR_MONTHS = ['يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر'];

  function maxDateStr(a, b) {
    return a >= b ? a : b;
  }

  function minDateStr(a, b) {
    return a <= b ? a : b;
  }

  /** List each calendar month overlapping [fromStr, toStr]. */
  /**
   * Split across pages only when the gap between start and end dates exceeds 30 days
   * (e.g. 27/04 → 27/05 = 30 days → single page; 27/04 → 28/05 = 31 → multiple sheets).
   */
  function shouldSplitReportByPages(fromStr, toStr) {
    var a = parseLocalYmd(fromStr);
    var b = parseLocalYmd(toStr);
    if (!a || !b) return false;
    if (b < a) {
      var swap = a;
      a = b;
      b = swap;
    }
    var diffDays = Math.round((b.getTime() - a.getTime()) / 86400000);
    return diffDays > 30;
  }

  function enumerateMonths(fromStr, toStr) {
    var start = parseLocalYmd(fromStr);
    var end = parseLocalYmd(toStr);
    if (!start || !end) return [];
    if (end < start) {
      var tmp = start;
      start = end;
      end = tmp;
    }
    var months = [];
    var cur = new Date(start.getFullYear(), start.getMonth(), 1, 12, 0, 0);
    var endMonthStart = new Date(end.getFullYear(), end.getMonth(), 1, 12, 0, 0);
    while (cur <= endMonthStart) {
      var y = cur.getFullYear();
      var m = cur.getMonth() + 1;
      var lastDay = new Date(y, m, 0).getDate();
      var monthStart = y + '-' + String(m).padStart(2, '0') + '-01';
      var monthEnd = y + '-' + String(m).padStart(2, '0') + '-' + String(lastDay).padStart(2, '0');
      months.push({ y: y, m: m, monthStart: monthStart, monthEnd: monthEnd });
      cur.setMonth(cur.getMonth() + 1);
    }
    return months;
  }

  function monthTitleAr(y, m) {
    return 'تقويم — ' + AR_MONTHS[m - 1] + ' ' + y;
  }

  function calendarHeadHtml() {
    var days = ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'];
    return '<div class="esr-calendar-head">' + days.map(function (d) {
      return '<span>' + d + '</span>';
    }).join('') + '</div>';
  }

  function renderPerformanceInto(el, stats) {
    if (!el) return;
    el.innerHTML = [
      ['أيام الحضور', stats.present || 0],
      ['أيام الغياب', stats.absent || 0],
      ['أيام الإجازات', stats.leave || 0],
      ['أيام العطلات الرسمية', stats.official || 0],
      ['أيام الإجازة الأسبوعية', stats.weekend || 0],
      ['أيام التأخير', stats.lateDays || 0],
      ['خروج مبكر', stats.earlyOut || 0],
      ['بدون خروج', stats.incomplete || 0]
    ].map(function (item) {
      return '<div><span>' + item[0] + '</span><strong>' + item[1] + '</strong></div>';
    }).join('');
  }

  function renderCalendar(rows, fromStr, toStr, gridEl) {
    var grid = gridEl || byId('esrCalendarGrid');
    if (!grid) return;
    grid.innerHTML = '';

    var start = parseLocalYmd(fromStr);
    var end = parseLocalYmd(toStr);
    if (!start || !end) return;
    if (end < start) {
      var t = start;
      start = end;
      end = t;
    }

    var map = {};
    rows.forEach(function (r) { map[r.date] = r; });

    for (var i = 0; i < start.getDay(); i++) {
      grid.insertAdjacentHTML('beforeend', '<div class="esr-day empty"></div>');
    }

    var cur = new Date(start.getTime());
    while (cur <= end) {
      var date = formatLocalYmd(cur);
      var dayNum = cur.getDate();
      var r = map[date];
      var st = r ? r.status : 'absent';
      var inTime = r ? toHHMM(r.check_in) : '—';
      var outTime = r ? toHHMM(r.check_out) : '—';
      var schIn = r && r.sch_in ? String(r.sch_in).slice(0, 5) : null;
      var late = st === 'present' && inTime !== '—' && schIn && toMins(inTime) > toMins(schIn);
      var cls = statusClass(st, late);
      var dayLabel = st === 'official_holiday' ? getHolidayLabel(r) : statusShort(st);
      var holidaySlash = st === 'official_holiday' ? '<span class="esr-official-slash" aria-hidden="true"></span>' : '';
      grid.insertAdjacentHTML(
        'beforeend',
        '<div class="esr-day ' + cls + '">' +
          holidaySlash +
          '<span class="d">' + dayNum + '</span>' +
          '<span class="s">' + esc(dayLabel) + '</span>' +
          '<span class="t">دخول: ' + esc(inTime) + '</span>' +
          '<span class="t">انصراف: ' + esc(outTime) + '</span>' +
        '</div>'
      );
      cur.setDate(cur.getDate() + 1);
    }
  }

  function renderPerformance(stats) {
    renderPerformanceInto(byId('esrPerformance'), stats);
  }

  function renderMultiMonthPages(reportRows, globalFrom, globalTo) {
    var root = byId('esrMonthsRoot');
    var single = byId('esrCalendarSingle');
    if (!root || !single) return;
    var months = enumerateMonths(globalFrom, globalTo);
    root.innerHTML = '';
    months.forEach(function (mi) {
      var sliceFrom = maxDateStr(mi.monthStart, globalFrom);
      var sliceTo = minDateStr(mi.monthEnd, globalTo);
      var sec = document.createElement('section');
      sec.className = 'esr-month-page esr-calendar-wrap';
      sec.innerHTML =
        '<h3>' + esc(monthTitleAr(mi.y, mi.m)) + '</h3>' +
        '<p class="esr-month-slice">ضمن الفترة الكلية: <strong>' + esc(sliceFrom + ' → ' + sliceTo) + '</strong></p>' +
        calendarHeadHtml() +
        '<div class="esr-calendar-grid"></div>' +
        '<h4 class="esr-month-subtitle">ملخص الشهر</h4>' +
        '<div class="esr-month-perf esr-performance"></div>';
      var grid = sec.querySelector('.esr-calendar-grid');
      renderCalendar(reportRows, sliceFrom, sliceTo, grid);
      var mRows = reportRows.filter(function (r) {
        return r.date >= sliceFrom && r.date <= sliceTo;
      });
      var mStats = calcStats(mRows, {});
      renderPerformanceInto(sec.querySelector('.esr-month-perf'), mStats);
      root.appendChild(sec);
    });
    single.hidden = true;
    root.hidden = false;
  }

  function renderSingleMonthLayout(reportRows, from, to) {
    var root = byId('esrMonthsRoot');
    var single = byId('esrCalendarSingle');
    if (root) {
      root.innerHTML = '';
      root.hidden = true;
    }
    if (single) single.hidden = false;
    renderCalendar(reportRows, from, to);
  }

  async function init() {
    byId('esrPdfBtn')?.addEventListener('click', function () {
      exportPdfDirect();
    });
    byId('esrPrintBtn')?.addEventListener('click', function () { window.print(); });
    byId('esrCloseBtn')?.addEventListener('click', function () { window.close(); });

    var q = new URLSearchParams(window.location.search);
    var reportToken = q.get('rt');
    if (!reportToken) {
      showError('الرابط غير آمن أو غير صالح. افتح التقرير من لوحة الإدارة.');
      return;
    }
    if (!getAuthToken()) {
      showError('التوكن غير موجود. يرجى تسجيل الدخول من لوحة المدير.');
      return;
    }

    try {
      var resolved = await apiPost('reports/final-link-resolve', { token: reportToken });
      if (!resolved || !resolved.success || !resolved.data) {
        showError((resolved && resolved.message) || 'الرابط غير صالح أو منتهي الصلاحية.');
        return;
      }
      var employeeId = resolved.data.employee_id;
      var from = resolved.data.from;
      var to = resolved.data.to;

      var res = await apiGet('reports/final', { employee_id: employeeId, from: from, to: to });
      if (!res || !res.success || !res.data) {
        showError((res && res.message) || 'فشل تحميل البيانات.');
        return;
      }
      var data = res.data;
      var reportRows = Array.isArray(data.report) ? data.report : [];
      var stats = calcStats(reportRows, data.totals || {});

      fillHeaderAndMeta(data, from, to, stats);
      if (shouldSplitReportByPages(from, to)) {
        renderMultiMonthPages(reportRows, from, to);
      } else {
        renderSingleMonthLayout(reportRows, from, to);
      }
      renderPerformance(stats);
    } catch (e) {
      showError('حدث خطأ أثناء تحميل التقرير.');
    }
  }

  init();
})();
