/**
 * Standalone employee final report — loads reports/final using admin_token from localStorage.
 */
(function () {
  'use strict';

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

  async function api(method, endpoint, body) {
    const authToken = typeof localStorage !== 'undefined' ? localStorage.getItem('admin_token') : null;
    const opts = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: 'Bearer ' + (authToken || '')
      }
    };
    const payload = body ? { ...body } : {};
    if (method !== 'POST') payload._method = method;
    opts.body = JSON.stringify(payload);
    try {
      const r = await fetch(`${API}?route=${encodeURIComponent(endpoint)}`, opts);
      return await r.json();
    } catch (e) {
      return { success: false, message: 'Network error' };
    }
  }

  function showError(msg) {
    const el = document.getElementById('frPrintError');
    if (!el) return;
    el.textContent = msg;
    el.style.display = 'block';
  }

  async function init() {
    const I = window.hrproFinalReportPrintI18n;
    if (!I) return showError('Missing i18n');

    I.syncDocumentLangDir();
    I.applyDom(document);
    window.hrproFinalReportT = I.t;

    const params = new URLSearchParams(window.location.search);
    const employee_id = params.get('employee_id');
    const from = params.get('from');
    const to = params.get('to');
    const hide = params.get('hide') || 'all';

    if (!employee_id || !from || !to) {
      showError(I.t('fr_print_load_error'));
      return;
    }

    if (!localStorage.getItem('admin_token')) {
      showError(I.t('fr_print_auth_required'));
      return;
    }

    const res = await api('GET', 'reports/final', { employee_id, from, to });
    if (!res.success) {
      showError(String(res.message || I.t('fr_print_load_error')).replace(/</g, ''));
      return;
    }

    const profile = (res.data && res.data.employee_profile) || {};
    const displayName = profile.name || '—';

    window.HRProFinalReport.render(res.data, {
      mode: 'print',
      omitSettlementColumn: true,
      hideMode: hide,
      fromStr: from,
      toStr: to,
      employeeDisplayName: displayName,
      t: I.t
    });

    I.applyDom(document);
  }

  document.getElementById('frPrintDoPrint')?.addEventListener('click', () => {
    window.print();
  });
  document.getElementById('frPrintClose')?.addEventListener('click', () => {
    window.close();
  });

  init();
})();
