let allClients = [];
let filteredClients = [];
let selectedClientId = null;
let currentClientPage = 1;
const CLIENTS_PER_PAGE = 10;

document.addEventListener('DOMContentLoaded', () => {
  const userJson = localStorage.getItem('user');
  if (!userJson) {
    window.location.href = '../index.html';
    return;
  }
  const user = JSON.parse(userJson);

  // User info
  const fullEl = document.getElementById('user-fullname');
  const roleEl = document.getElementById('user-role');
  const initEl = document.getElementById('user-initial');
  if (fullEl) fullEl.textContent = user.FullName || '';
  if (roleEl) roleEl.textContent = user.Role || '';
  if (initEl && user.FullName) initEl.textContent = user.FullName.charAt(0).toUpperCase();

  // Role-based navigation filter
  const userRole = user.Role;
  const navLinks = document.querySelectorAll('.nav-link');

  navLinks.forEach(link => {
    const allowedRoles = link.getAttribute('data-role');
    if (!allowedRoles || allowedRoles === 'all') return;
    if (userRole === 'Director') return;

    const rolesArray = allowedRoles.split(',').map(r => r.trim());
    if (!rolesArray.includes(userRole)) link.remove();
  });

  // Search
  const searchInput = document.getElementById('client-search');
  if (searchInput) searchInput.addEventListener('input', onSearchChange);

  const mobileSearchInput = document.getElementById('client-search-mobile');
  if (mobileSearchInput) mobileSearchInput.addEventListener('input', onSearchChange);

  const prevPageBtn = document.getElementById('clients-prev-page');
  const nextPageBtn = document.getElementById('clients-next-page');
  if (prevPageBtn) {
    prevPageBtn.addEventListener('click', () => {
      if (currentClientPage > 1) {
        currentClientPage -= 1;
        renderClientsPage();
      }
    });
  }
  if (nextPageBtn) {
    nextPageBtn.addEventListener('click', () => {
      const totalPages = Math.max(1, Math.ceil(filteredClients.length / CLIENTS_PER_PAGE));
      if (currentClientPage < totalPages) {
        currentClientPage += 1;
        renderClientsPage();
      }
    });
  }

  // Mobile sidebar
  const mobileToggle = document.getElementById('mobile-toggle');
  const sidebar = document.getElementById('sidebar');
  const overlay = document.getElementById('sidebar-overlay');

  if (sidebar) {
    if (window.innerWidth < 1024) sidebar.classList.add('-translate-x-full');
    else sidebar.classList.remove('-translate-x-full');
  }

  if (mobileToggle && sidebar && overlay) {
    mobileToggle.addEventListener('click', () => {
      sidebar.classList.toggle('-translate-x-full');
      overlay.classList.toggle('hidden');
    });

    overlay.addEventListener('click', () => {
      sidebar.classList.add('-translate-x-full');
      overlay.classList.add('hidden');
    });

    window.addEventListener('resize', () => {
      if (window.innerWidth >= 1024) {
        sidebar.classList.remove('-translate-x-full');
        overlay.classList.add('hidden');
      } else {
        sidebar.classList.add('-translate-x-full');
      }
    });
  }

  // Summary button
  const summaryBtn = document.getElementById('btn-client-summary');
  if (summaryBtn) {
    summaryBtn.addEventListener('click', () => {
      if (!selectedClientId) return;
      window.open(`templates/summary.html?clientId=${encodeURIComponent(selectedClientId)}`, '_blank');
    });
  }

  // Pay button redirect
  const payBtn = document.getElementById('btn-client-pay');
  if (payBtn) {
    payBtn.addEventListener('click', () => {
      if (!selectedClientId) return;
      window.location.href = `record_payment.html?clientId=${encodeURIComponent(selectedClientId)}`;
    });
  }

  fetchClients();
});

async function fetchClients() {
  try {
    const response = await fetch('../api/get_clients.php');
    const data = await response.json();

    allClients = Array.isArray(data) ? data : [];

    const countEl = document.getElementById('client-count');
    if (countEl) countEl.textContent = `${allClients.length} Clients Registered`;

    filteredClients = allClients;
    currentClientPage = 1;
    renderClientsPage();
  } catch (err) {
    console.error('Fetch clients failed:', err);
  }
}

function renderClientsPage() {
  const total = filteredClients.length;
  const totalPages = Math.max(1, Math.ceil(total / CLIENTS_PER_PAGE));
  if (currentClientPage > totalPages) currentClientPage = totalPages;
  if (currentClientPage < 1) currentClientPage = 1;

  const start = (currentClientPage - 1) * CLIENTS_PER_PAGE;
  const pageItems = filteredClients.slice(start, start + CLIENTS_PER_PAGE);

  renderClients(pageItems);
  updateClientsPagination(total, totalPages, start, pageItems.length);
}

function renderClients(list) {
  const tbody = document.getElementById('clients-table-body');
  if (!tbody) return;

  if (!list.length) {
    tbody.innerHTML = `
      <tr>
        <td colspan="5" class="px-6 py-8 text-center text-gray-400 text-sm">
          No clients found
        </td>
      </tr>`;
    return;
  }

  tbody.innerHTML = list.map(client => `
    <tr class="hover:bg-[#f6f9fc] cursor-pointer transition-colors"
        onclick="viewClientDetails(${client.Id})">

      <!-- ✅ CHANGED: brown -> blue -->
      <td class="px-6 py-4 font-bold text-[#125db8] text-[11px]">
        ${client.ClientId || ''}
      </td>

      <td class="px-6 py-4 font-semibold text-gray-800">
        ${client.FullName || ''}
      </td>

      <td class="px-6 py-4 text-gray-500">
        ${client.Phone || 'N/A'}
      </td>

      <td class="px-6 py-4 text-gray-400 text-xs">
        ${client.Email || 'N/A'}
      </td>

      <td class="px-6 py-4 text-center">
        <button
          class="w-8 h-8 rounded-lg bg-gray-50 text-gray-400 hover:text-[#125db8] transition-all"
          title="View Client"
          onclick="event.stopPropagation(); goToViewClient(${client.Id});">
          <i class="fas fa-eye"></i>
        </button>
      </td>
    </tr>
  `).join('');
}

function onSearchChange(e) {
  const term = (e.target.value || '').toLowerCase().trim();
  const desktopSearch = document.getElementById('client-search');
  const mobileSearch = document.getElementById('client-search-mobile');

  if (e.target === desktopSearch && mobileSearch) mobileSearch.value = e.target.value;
  if (e.target === mobileSearch && desktopSearch) desktopSearch.value = e.target.value;

  filteredClients = !term
    ? allClients
    : allClients.filter(c =>
      (c.FullName && c.FullName.toLowerCase().includes(term)) ||
      (c.ClientId && String(c.ClientId).toLowerCase().includes(term)) ||
      (c.Phone && c.Phone.toLowerCase().includes(term)) ||
      (c.Email && c.Email.toLowerCase().includes(term))
    );

  currentClientPage = 1;
  renderClientsPage();
}

function updateClientsPagination(total, totalPages, start, visibleCount) {
  const summaryEl = document.getElementById('clients-pagination-summary');
  const prevBtn = document.getElementById('clients-prev-page');
  const nextBtn = document.getElementById('clients-next-page');
  const buttonsEl = document.getElementById('clients-page-buttons');

  if (summaryEl) {
    summaryEl.textContent = total
      ? `Showing ${start + 1}-${start + visibleCount} of ${total} clients`
      : 'No clients to display';
  }

  if (prevBtn) prevBtn.disabled = currentClientPage <= 1 || total === 0;
  if (nextBtn) nextBtn.disabled = currentClientPage >= totalPages || total === 0;

  if (!buttonsEl) return;

  if (!total) {
    buttonsEl.innerHTML = '';
    return;
  }

  let firstPage = Math.max(1, currentClientPage - 2);
  let lastPage = Math.min(totalPages, firstPage + 4);
  firstPage = Math.max(1, lastPage - 4);

  const pages = [];
  for (let page = firstPage; page <= lastPage; page += 1) pages.push(page);

  buttonsEl.innerHTML = pages.map(page => {
    const active = page === currentClientPage;
    return `
      <button type="button" data-page="${page}"
        class="w-9 h-9 rounded-xl text-xs font-bold transition-all ${active
          ? 'bg-[var(--brand-green)] text-white shadow-sm'
          : 'border border-slate-200 text-slate-500 hover:text-[var(--brand-green)] hover:border-[var(--brand-green)]'}">
        ${page}
      </button>
    `;
  }).join('');

  buttonsEl.querySelectorAll('[data-page]').forEach(btn => {
    btn.addEventListener('click', () => {
      currentClientPage = Number(btn.getAttribute('data-page')) || 1;
      renderClientsPage();
    });
  });
}

async function viewClientDetails(id) {
  try {
    const response = await fetch(`../api/get_client_summary.php?id=${id}`);
    const data = await response.json();

    if (!data || !data.client) {
      console.error('Invalid summary payload', data);
      return;
    }

    selectedClientId = id;

    const c = data.client;
    const s = data.summary || { totalPlots: 0, totalPaid: 0, balance: 0 };
    const plots = Array.isArray(data.plots) ? data.plots : [];
    const payments = Array.isArray(data.payments) ? data.payments : [];

    const summaryBtn = document.getElementById('btn-client-summary');
    const payBtn = document.getElementById('btn-client-pay');
    if (summaryBtn) summaryBtn.disabled = false;
    if (payBtn) payBtn.disabled = false;

    // Overview
    const nameEl = document.getElementById('view-client-name');
    const contactEl = document.getElementById('view-client-contact');
    const totalPlotsEl = document.getElementById('view-total-plots');
    const paidEl = document.getElementById('view-amount-paid');
    const outstandingEl = document.getElementById('view-outstanding');

    if (nameEl) nameEl.textContent = c.FullName || 'Unknown client';
    if (contactEl) contactEl.textContent = `${c.Phone || 'No Phone'} | ${c.Email || 'No Email'}`;
    if (totalPlotsEl) totalPlotsEl.textContent = s.totalPlots || 0;
    if (paidEl) paidEl.textContent = '₦' + Number(s.totalPaid || 0).toLocaleString();
    if (outstandingEl) outstandingEl.textContent = '₦' + Number(s.balance || 0).toLocaleString();

    // Purchased plots
    const plotsBody = document.getElementById('client-plots-body');
    const plotsCountEl = document.getElementById('client-plots-count');

    if (plotsCountEl) plotsCountEl.textContent = `${plots.length} plot${plots.length === 1 ? '' : 's'}`;

    if (plotsBody) {
      if (plots.length) {
        plotsBody.innerHTML = plots.map(p => `
          <tr class="group">
            <td class="py-3 font-medium text-gray-700">${p.AreaName || ''}</td>

            <!-- ✅ CHANGED: brown -> blue -->
            <td class="py-3 font-bold text-[#125db8]">${p.PlotCode || ''}</td>

            <td class="py-3 text-right font-bold text-green-600">
              ₦${Number(p.FinalPrice || 0).toLocaleString()}
            </td>
          </tr>
        `).join('');
      } else {
        plotsBody.innerHTML = `<tr><td colspan="3" class="py-8 text-center text-gray-300">No plots found</td></tr>`;
      }
    }

    // Payment history
    const payBody = document.getElementById('client-payments-body');
    const payCountEl = document.getElementById('client-payments-count');

    if (payCountEl) payCountEl.textContent = `${payments.length} payment${payments.length === 1 ? '' : 's'}`;

    if (payBody) {
      if (payments.length) {
        payBody.innerHTML = payments.map(p => {
          const amount = Number(p.Amount || 0).toLocaleString();
          const date = p.PaymentDate || '';
          const invoice = p.InvoiceNumber || '';
          const method = p.Method || '';
          const reference = p.Reference || '';
          const paymentId = p.Id;

          return `
            <tr>
              <td class="py-3">${date}</td>
              <td class="py-3">${invoice}</td>
              <td class="py-3 text-right font-semibold text-gray-800">₦${amount}</td>
              <td class="py-3">${method}</td>
              <td class="py-3">${reference}</td>
              <td class="py-3 text-center">
                <button
                  class="w-8 h-8 rounded-lg bg-gray-50 text-gray-400 hover:text-[#125db8] transition-all"
                  onclick="openReceipt(${paymentId})"
                  title="View Receipt">
                  <i class="fas fa-receipt"></i>
                </button>
              </td>
            </tr>
          `;
        }).join('');
      } else {
        payBody.innerHTML = `<tr><td colspan="6" class="py-8 text-center text-gray-300">No payments found</td></tr>`;
      }
    }

  } catch (err) {
    console.error('Fetch summary failed:', err);
  }
}

function openReceipt(paymentId) {
  if (!paymentId) return;
  window.open(`templates/receipt.html?paymentId=${encodeURIComponent(paymentId)}`, '_blank');
}

function goToViewClient(clientId) {
  if (!clientId) return;
  window.location.href = `view_client.html?clientId=${encodeURIComponent(clientId)}`;
}

function openAddClientModal() {
  window.location.href = 'add_client.html';
}

function logout() {
  localStorage.removeItem('user');
  window.location.replace('../index.html');
}
