// dashboard/js/view_client.js
// Works with: dashboard/view_client.html?clientId=123
// API: ../api/get_client_details.php?id=123

(function () {
  const $ = (id) => document.getElementById(id);

  // ------- Helpers -------
  function escapeText(v) {
    if (v === null || v === undefined) return '';
    return String(v);
  }

  function setText(id, value, fallback = '—') {
    const el = $(id);
    if (!el) return;
    const txt = escapeText(value).trim();
    el.textContent = txt ? txt : fallback;
  }

  function show(el) {
    if (!el) return;
    el.classList.remove('hidden');
  }

  function hide(el) {
    if (!el) return;
    el.classList.add('hidden');
  }

  function formatDateOnly(value) {
    // API returns DateOfBirth as YYYY-MM-DD (date-only) or empty
    const v = escapeText(value).trim();
    if (!v) return '—';
    return v; // keep YYYY-MM-DD
  }

  function formatIsoDateTime(value) {
    // API returns ISO 8601 for CreatedAt; LastModified may be ISO or MySQL timestamp string
    const v = escapeText(value).trim();
    if (!v) return '—';
    const d = new Date(v);
    if (isNaN(d.getTime())) return v;
    try {
      return d.toLocaleString();
    } catch {
      return v;
    }
  }

  function getQueryParam(name) {
    const url = new URL(window.location.href);
    return url.searchParams.get(name);
  }

  function showError(message) {
    const errBox = $('error-box');
    if (errBox) {
      errBox.textContent = message;
      show(errBox);
    }
  }

  function setLoading(isLoading) {
    const loading = $('loading-state');
    const content = $('content');
    const errBox = $('error-box');

    if (errBox) hide(errBox);

    if (isLoading) {
      if (loading) show(loading);
      if (content) hide(content);
    } else {
      if (loading) hide(loading);
      if (content) show(content);
    }
  }

  // ------- Boot -------
  document.addEventListener('DOMContentLoaded', () => {
    // Back button (safe even if you already wired it inline)
    const back = $('btn-back');
    if (back) back.addEventListener('click', () => (window.location.href = 'clients.html'));

    // Auth check (same pattern as clients.js)
    const userJson = localStorage.getItem('user');
    if (!userJson) {
      window.location.href = '../index.html';
      return;
    }

    let user;
    try {
      user = JSON.parse(userJson);
    } catch {
      localStorage.removeItem('user');
      window.location.href = '../index.html';
      return;
    }

    // User display
    if ($('user-fullname')) $('user-fullname').textContent = user.FullName || '';
    if ($('user-role')) $('user-role').textContent = user.Role || '';
    if ($('user-initial')) {
      const initial = (user.FullName || 'U').trim().charAt(0).toUpperCase();
      $('user-initial').textContent = initial || 'U';
    }

    // Read clientId from URL
    const clientId = getQueryParam('clientId');
    if (!clientId || isNaN(Number(clientId)) || Number(clientId) <= 0) {
      setLoading(false);
      showError('Missing or invalid clientId in URL. Example: view_client.html?clientId=123');
      return;
    }

    loadClientDetails(Number(clientId));
  });

  async function loadClientDetails(clientId) {
    setLoading(true);

    try {
      const res = await fetch(`../api/get_client_details.php?id=${encodeURIComponent(clientId)}`);

      // Try JSON even on error responses
      let payload = null;
      try {
        payload = await res.json();
      } catch {
        payload = null;
      }

      if (!res.ok) {
        const msg = payload && payload.error ? payload.error : `Failed to load client (HTTP ${res.status})`;
        setLoading(false);
        showError(msg);
        return;
      }

      if (!payload || !payload.Id) {
        setLoading(false);
        showError('Invalid response from server (missing client record).');
        return;
      }

      // Header
      setText('client-fullname', payload.FullName);
      setText('client-clientid', payload.ClientId);
      setText('client-id', payload.Id);
      setText('client-gender', payload.Gender);
      setText('client-marital', payload.MaritalStatus);

      // Personal
      setText('client-surname', payload.Surname);
      setText('client-firstname', payload.FirstName);
      setText('client-othername', payload.OtherName);
      setText('client-dob', formatDateOnly(payload.DateOfBirth));

      // Origin
      setText('client-nationality', payload.Nationality);
      setText('client-state', payload.StateOfOrigin);
      setText('client-lga', payload.Lga);

      // Contact
      setText('client-phone', payload.Phone);
      setText('client-altphone', payload.AltPhone);
      setText('client-email', payload.Email);
      setText('client-address', payload.Address);

      // Next of kin
      setText('client-nok-name', payload.NokName);
      setText('client-nok-relationship', payload.NokRelationship);
      setText('client-nok-phone', payload.NokPhone);
      setText('client-nok-address', payload.NokAddress);

      // System
      setText('client-created', formatIsoDateTime(payload.CreatedAt));
      setText('client-modified', formatIsoDateTime(payload.LastModified));

      // Optional subtitle
      setText(
        'page-subtitle',
        payload.FullName ? `Viewing profile: ${payload.FullName}` : 'Complete client profile',
        'Complete client profile'
      );

      setLoading(false);
    } catch (err) {
      console.error('Load client details failed:', err);
      setLoading(false);
      showError('Cannot connect to server. Make sure backend is running.');
    }
  }
})();
