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

    // 2. Hydrate User Session Info
    const fullnameEl = document.getElementById('user-fullname');
    const roleEl = document.getElementById('user-role');
    const initialEl = document.getElementById('user-initial');

    if (fullnameEl) fullnameEl.textContent = user.FullName || '';
    if (roleEl) roleEl.textContent = user.Role || '';
    if (initialEl && user.FullName) {
        initialEl.textContent = user.FullName.charAt(0).toUpperCase();
    }

    // 3. Role-Based Navigation Filter
    const userRole = user.Role;
    const navLinks = document.querySelectorAll('.nav-link');

    // 3b. Director-only stat card (Total Revenue)
const revenueCard = document.getElementById('card-total-revenue');
if (revenueCard && userRole !== 'Director') {
  revenueCard.remove(); // removes the whole card from DOM [web:32]
}


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

        // Director sees everything (super admin)
        if (userRole === 'Director') return;

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

    // 3a. Desktop App visibility by role
    const desktopCard = document.getElementById('desktop-app-card');
    if (desktopCard) {
        const allowedDesktopRoles = ['Director', 'Admin', 'Accountant']; // adjust if needed
        if (!allowedDesktopRoles.includes(userRole)) {
            desktopCard.remove();
        }
    }

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

    const toggleSidebar = () => {
        if (!sidebar || !overlay) return;
        sidebar.classList.toggle('-translate-x-full');
        overlay.classList.toggle('hidden');
    };

    if (mobileToggle) mobileToggle.addEventListener('click', toggleSidebar);
    if (overlay) overlay.addEventListener('click', toggleSidebar);

    // 5. Load dashboard stats from API
    fetchDashboardStats();

    // 6. Load recent activity (payments + purchases)
    fetchRecentPayments();
    fetchRecentPurchases();
});

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

async function fetchDashboardStats() {
  const user = JSON.parse(localStorage.getItem('user') || '{}');
  const userRole = user.Role;

  const revenueEl = document.getElementById('total-revenue');
  const plotsEl = document.getElementById('active-plots');
  const clientsEl = document.getElementById('total-clients');
  const outstandingEl = document.getElementById('outstanding-balance');

  // Clear any dummy text while loading
  if (userRole === 'Director' && revenueEl) revenueEl.textContent = 'Loading...';
  if (plotsEl) plotsEl.textContent = '...';
  if (clientsEl) clientsEl.textContent = '...';
  if (outstandingEl) outstandingEl.textContent = 'Loading...';

  try {
    const response = await fetch('../api/dashboard.php');
    if (!response.ok) return;

    const data = await response.json();

    // Only Directors should see revenue
    if (userRole === 'Director' && data.totalRevenue != null && revenueEl) {
      revenueEl.textContent = `₦${Number(data.totalRevenue).toLocaleString()}`;
    }

    if (data.activePlots != null && plotsEl) {
      plotsEl.textContent = String(data.activePlots).padStart(2, '0');
    }
    if (data.totalClients != null && clientsEl) {
      clientsEl.textContent = String(data.totalClients).padStart(2, '0');
    }
    if (data.outstandingBalance != null && outstandingEl) {
      outstandingEl.textContent = `₦${Number(data.outstandingBalance).toLocaleString()}`;
    }
  } catch {
    if (userRole === 'Director' && revenueEl) revenueEl.textContent = '₦0';
    if (plotsEl) plotsEl.textContent = '00';
    if (clientsEl) clientsEl.textContent = '00';
    if (outstandingEl) outstandingEl.textContent = '₦0';
  }
}


/**
 * Recent Payments
 * Expected API: GET https://portal.legitempire.com.ng/api/recent_payments.php
 * Returns: [{ PaymentDate, ClientName, Amount, Method }, ...]
 */
async function fetchRecentPayments() {
    const tbody = document.getElementById('recent-payments-body');
    if (!tbody) return;

    // show loading row
    tbody.innerHTML = `
        <tr>
            <td colspan="4" class="px-4 py-6 text-center text-gray-400 text-xs">
                Loading recent payments...
            </td>
        </tr>
    `;

    try {
        const response = await fetch('../api/recent_payments.php');
        if (!response.ok) {
            throw new Error('Failed to load');
        }

        const items = await response.json();
        if (!Array.isArray(items) || items.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="4" class="px-4 py-6 text-center text-gray-400 text-xs">
                        No payments yet. Once you start recording payments, they will show up here.
                    </td>
                </tr>
            `;
            return;
        }

        tbody.innerHTML = '';
        items.forEach(p => {
            const tr = document.createElement('tr');
            tr.className = 'hover:bg-gray-50';

            const date = (p.PaymentDate || '').toString();
            const client = p.ClientName || 'Unknown';
            const amount = p.Amount != null
                ? `₦${Number(p.Amount).toLocaleString()}`
                : '₦0';
            const method = p.Method || 'N/A';

            tr.innerHTML = `
                <td class="px-4 py-3 text-xs text-gray-600">${date}</td>
                <td class="px-4 py-3 text-xs text-gray-800 font-medium">${client}</td>
                <td class="px-4 py-3 text-xs text-gray-800 font-semibold">${amount}</td>
                <td class="px-4 py-3 text-xs text-gray-500">${method}</td>
            `;
            tbody.appendChild(tr);
        });
    } catch {
        tbody.innerHTML = `
            <tr>
                <td colspan="4" class="px-4 py-6 text-center text-red-400 text-xs">
                    Unable to load recent payments right now.
                </td>
            </tr>
        `;
    }
}

/**
 * Recent Purchases / Contracts
 * Expected API: GET https://portal.legitempire.com.ng/api/recent_purchases.php
 * Returns: [{ CreatedAt, ClientName, PlotCode, Status }, ...]
 */
async function fetchRecentPurchases() {
    const tbody = document.getElementById('recent-purchases-body');
    if (!tbody) return;

    // show loading row
    tbody.innerHTML = `
        <tr>
            <td colspan="4" class="px-4 py-6 text-center text-gray-400 text-xs">
                Loading recent purchases...
            </td>
        </tr>
    `;

    try {
        const response = await fetch('../api/recent_purchases.php');
        if (!response.ok) {
            throw new Error('Failed to load');
        }

        const items = await response.json();
        if (!Array.isArray(items) || items.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="4" class="px-4 py-6 text-center text-gray-400 text-xs">
                        No purchases yet. New contracts will appear in this list.
                    </td>
                </tr>
            `;
            return;
        }

        tbody.innerHTML = '';
        items.forEach(c => {
            const tr = document.createElement('tr');
            tr.className = 'hover:bg-gray-50';

            const date = (c.CreatedAt || '').toString();
            const client = c.ClientName || 'Unknown';
            const plot = c.PlotCode || 'N/A';
            const status = c.Status || 'Pending';

            let statusColor = 'bg-gray-100 text-gray-700';
            if (status.toLowerCase() === 'active') statusColor = 'bg-green-100 text-green-700';
            if (status.toLowerCase() === 'completed') statusColor = 'bg-blue-100 text-blue-700';
            if (status.toLowerCase() === 'cancelled') statusColor = 'bg-red-100 text-red-700';

            tr.innerHTML = `
                <td class="px-4 py-3 text-xs text-gray-600">${date}</td>
                <td class="px-4 py-3 text-xs text-gray-800 font-medium">${client}</td>
                <td class="px-4 py-3 text-xs text-gray-700">${plot}</td>
                <td class="px-4 py-3 text-xs">
                    <span class="inline-flex px-2 py-0.5 rounded-full text-[10px] font-semibold ${statusColor}">
                        ${status}
                    </span>
                </td>
            `;
            tbody.appendChild(tr);
        });
    } catch {
        tbody.innerHTML = `
            <tr>
                <td colspan="4" class="px-4 py-6 text-center text-red-400 text-xs">
                    Unable to load recent purchases right now.
                </td>
            </tr>
        `;
    }
}
