<?php require_once __DIR__.'/layout/header.php'; ?>
<?php require_once __DIR__.'/layout/sidebar.php'; ?>

<style>

/* ===== KPI GRID ===== */
.kpi-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 16px;
}

.kpi-card {
  background: #fff;
  padding: 16px;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0,0,0,0.05);
}

.kpi-label {
  font-size: 13px;
  color: #6b7280;
  margin-bottom: 6px;
}

.kpi-value {
  font-size: 28px;
  font-weight: bold;
  color: #111827;
}

/* ===== SECTION ===== */
.section {
  margin-top: 32px;
}

.section h2 {
  font-size: 16px;
  margin-bottom: 12px;
}

/* ===== STATES ===== */
.loading {
  color: #6b7280;
}

.error {
  color: #b91c1c;
  background: #fee2e2;
  padding: 12px;
}

/* ===== KPI COLORS ===== */
.kpi-value.green { color: #059669; }
.kpi-value.amber { color: #d97706; }
.kpi-value.red   { color: #dc2626; }

</style>

<main class="main">

<h1>Dashboard</h1>

<div id="dashboardState" class="loading">Loading KPIs…</div>

<div id="dashboardContent" style="display:none">

<!-- USERS -->
<div class="section">

<h2>Users</h2>

<div class="kpi-grid">

<div class="kpi-card">
<div class="kpi-label">Total Users</div>
<div class="kpi-value" id="kpiUsersTotal">–</div>
</div>

<div class="kpi-card">
<div class="kpi-label">Active Users</div>
<div class="kpi-value" id="kpiUsersActive">–</div>
</div>

<div class="kpi-card">
<div class="kpi-label">Locked Users</div>
<div class="kpi-value" id="kpiUsersLocked">–</div>
</div>

<div class="kpi-card">
<div class="kpi-label">Disabled Users</div>
<div class="kpi-value" id="kpiUsersDisabled">–</div>
</div>

</div>
</div>


<!-- COMPANIES -->
<div class="section" id="companiesSection">

<h2>Companies</h2>

<div class="kpi-grid">

<div class="kpi-card">
<div class="kpi-label">Total Companies</div>
<div class="kpi-value" id="kpiCompaniesTotal">–</div>
</div>

<div class="kpi-card">
<div class="kpi-label">Active Companies</div>
<div class="kpi-value" id="kpiCompaniesActive">–</div>
</div>

</div>
</div>


<!-- SUBSCRIPTIONS -->
<div class="section">

<h2>Subscriptions</h2>

<div class="kpi-grid">

<div class="kpi-card">
<div class="kpi-label">Active Subscriptions</div>
<div class="kpi-value" id="kpiSubsActive">–</div>
</div>

<div class="kpi-card">
<div class="kpi-label">Expired Subscriptions</div>
<div class="kpi-value" id="kpiSubsExpired">–</div>
</div>

</div>
</div>


<!-- USAGE -->
<div class="section">

<h2>Last 24 Hours</h2>

<div class="kpi-grid">

<div class="kpi-card">
<div class="kpi-label">Logins</div>
<div class="kpi-value" id="kpiLogins">–</div>
</div>

<div class="kpi-card">
<div class="kpi-label">Failed Logins</div>
<div class="kpi-value" id="kpiFailedLogins">–</div>
</div>

<div class="kpi-card">
<div class="kpi-label">Admin Actions</div>
<div class="kpi-value" id="kpiAdminActions">–</div>
</div>

</div>
</div>

</div>

</main>


<script>

/* ===== STATE ===== */

const stateEl = document.getElementById('dashboardState');
const contentEl = document.getElementById('dashboardContent');
const companiesSection = document.getElementById('companiesSection');

let dashboardRefreshTimer = null;

const DASHBOARD_REFRESH_MS = 60000;


/* ===== HELPERS ===== */

function setKpi(id, value, level) {

const el = document.getElementById(id);

if (!el) return;

el.innerText = value;

el.classList.remove('green','amber','red');

if (level) el.classList.add(level);

}


/* ================= CSRF ================= */

let CSRF_TOKEN = null;


// Load CSRF token once per page load

fetch('/auth/csrf_token.php', { credentials: 'include' })

.then(r => r.json())

.then(d => {

CSRF_TOKEN = d.csrf_token;

});


// CSRF-aware fetch wrapper

function csrfFetch(url, options = {}) {

return fetch(url, {

...options,

credentials: 'include',

headers: {

...(options.headers || {}),

'X-CSRF-Token': CSRF_TOKEN

}

});

}


function percent(part, total) {

return total ? Math.round((part / total) * 100) : 0;

}


function showError(msg) {

stateEl.className = 'error';

stateEl.innerText = msg;

stateEl.style.display = 'block';

contentEl.style.display = 'none';

}


function showContent() {

stateEl.style.display = 'none';

contentEl.style.display = 'block';

}


/* ===== LOAD DASHBOARD ===== */

function loadDashboard(isRefresh = false) {

if (!isRefresh) {

stateEl.className = 'loading';

stateEl.innerText = 'Loading KPIs…';

stateEl.style.display = 'block';

contentEl.style.display = 'none';

}


fetch('/dashboard/kpis.php', { credentials: 'same-origin' })

.then(r => r.json())

.then(res => {

if (res.status !== 'success') throw new Error();

const d = res.data;

const total = d.users.total;

setKpi('kpiUsersTotal', total, 'green');

setKpi('kpiUsersActive', d.users.active, percent(d.users.active,total)>=90?'green':percent(d.users.active,total)>=75?'amber':'red');

setKpi('kpiUsersLocked', d.users.locked, percent(d.users.locked,total)<=2?'green':percent(d.users.locked,total)<=5?'amber':'red');

setKpi('kpiUsersDisabled', d.users.disabled, percent(d.users.disabled,total)<=5?'green':percent(d.users.disabled,total)<=10?'amber':'red');


if (d.companies) {

companiesSection.style.display = 'block';

setKpi('kpiCompaniesTotal', d.companies.total, 'green');

setKpi('kpiCompaniesActive', d.companies.active, percent(d.companies.active,d.companies.total)>=95?'green':percent(d.companies.active,d.companies.total)>=85?'amber':'red');

}

else {

companiesSection.style.display = 'none';

}


const subsTotal = d.subscriptions.active + d.subscriptions.expired;

setKpi('kpiSubsActive', d.subscriptions.active, 'green');

setKpi('kpiSubsExpired', d.subscriptions.expired, percent(d.subscriptions.expired,subsTotal)<=5?'green':percent(d.subscriptions.expired,subsTotal)<=15?'amber':'red');


setKpi('kpiLogins', d.usage.logins_24h, 'green');

setKpi('kpiFailedLogins', d.usage.failed_logins_24h, d.usage.failed_logins_24h<=5?'green':d.usage.failed_logins_24h<=15?'amber':'red');

setKpi('kpiAdminActions', d.usage.admin_actions_24h, d.usage.admin_actions_24h>0?'green':'amber');


showContent();

})

.catch(() => {

if (!isRefresh) showError('Dashboard service unavailable.');

});

}


/* ===== AUTO REFRESH ===== */

function startDashboardAutoRefresh() {

if (!dashboardRefreshTimer) {

dashboardRefreshTimer = setInterval(() => loadDashboard(true), DASHBOARD_REFRESH_MS);

}

}


function stopDashboardAutoRefresh() {

if (dashboardRefreshTimer) {

clearInterval(dashboardRefreshTimer);

dashboardRefreshTimer = null;

}

}


/* ===== INIT ===== */

document.addEventListener('DOMContentLoaded', () => {

loadDashboard(false);

startDashboardAutoRefresh();

});


document.addEventListener('visibilitychange', () => {

document.hidden ? stopDashboardAutoRefresh() : (loadDashboard(true), startDashboardAutoRefresh());

});

</script>

<?php require_once __DIR__.'/layout/footer.php'; ?>