<?php
require_once __DIR__.'/../../config/app.php';
require_once __DIR__.'/../../app/Models/Admin.php';
require_once __DIR__.'/../../app/Models/Document.php';
require_once __DIR__.'/../../app/Models/DocumentTemplate.php';

$user = requireAuth(['admin']);
Document::refreshStatuses();

$counts     = Admin::counts();
$docStatus  = Admin::docsByStatus();
$violStatus = Admin::violationsByStatus();
$regs       = Admin::monthlyRegistrations(6);
$rev        = Admin::monthlyRevenue(6);
$byType     = Admin::docsByType(8);
$topOwners  = Admin::topOwners(5);

// Map document type codes to localized labels
$typeLabels = [];
foreach ($byType as $code=>$c) $typeLabels[$code] = DocumentTemplate::label($code);

$roleLabels = ['owner'=>t('owner_role'),'driver'=>t('driver_role'),'officer'=>t('officer_role'),'admin'=>t('admin_role')];

$pageTitle  = t('analytics');
$activePage = BASE_URL.'/admin/analytics.php';
require __DIR__.'/../../app/Views/shared/layout.php';
?>
<div class="page-header"><h2>📈 <?= t('analytics') ?></h2></div>

<div class="stats-grid" style="margin-bottom:8px">
  <div class="stat-card"><div class="stat-icon blue">👥</div><div><div class="stat-value"><?= $counts['users_total'] ?></div><div class="stat-label"><?= t('total_users') ?></div></div></div>
  <div class="stat-card"><div class="stat-icon blue">🚗</div><div><div class="stat-value"><?= $counts['vehicles'] ?></div><div class="stat-label"><?= t('all_vehicles') ?></div></div></div>
  <div class="stat-card"><div class="stat-icon green">📄</div><div><div class="stat-value"><?= $counts['documents'] ?></div><div class="stat-label"><?= t('all_documents') ?></div></div></div>
  <div class="stat-card"><div class="stat-icon green">💰</div><div><div class="stat-value"><?= number_format($counts['revenue'],0) ?></div><div class="stat-label"><?= t('total_revenue') ?> (DZD)</div></div></div>
</div>

<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px">
  <div class="card"><div class="card-header"><span class="card-title"><?= t('users_by_role') ?></span></div>
    <div class="card-body"><canvas id="chRoles" height="160"></canvas></div></div>
  <div class="card"><div class="card-header"><span class="card-title"><?= t('docs_by_status') ?></span></div>
    <div class="card-body"><canvas id="chDocs" height="160"></canvas></div></div>
  <div class="card"><div class="card-header"><span class="card-title"><?= t('monthly_registrations') ?></span></div>
    <div class="card-body"><canvas id="chRegs" height="160"></canvas></div></div>
  <div class="card"><div class="card-header"><span class="card-title"><?= t('monthly_revenue') ?> (DZD)</span></div>
    <div class="card-body"><canvas id="chRev" height="160"></canvas></div></div>
  <div class="card"><div class="card-header"><span class="card-title"><?= t('docs_by_type') ?></span></div>
    <div class="card-body"><canvas id="chType" height="160"></canvas></div></div>
  <div class="card"><div class="card-header"><span class="card-title"><?= t('violations_by_status') ?></span></div>
    <div class="card-body"><canvas id="chViol" height="160"></canvas></div></div>
</div>

<div class="card" style="margin-top:20px">
  <div class="card-header"><span class="card-title">🏆 <?= t('top_owners') ?></span></div>
  <div style="padding:0">
    <?php if(empty($topOwners)): ?>
      <div class="empty-state" style="padding:20px"><p><?= t('no_data') ?></p></div>
    <?php else: foreach($topOwners as $o): ?>
      <div class="verify-row"><div class="font-bold"><?= e($o['name']) ?></div>
        <span class="badge badge-info"><?= (int)$o['c'] ?> <?= t('vehicles_count') ?></span></div>
    <?php endforeach; endif; ?>
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js"></script>
<script>
const palette = ['#1a56db','#16a34a','#dc2626','#f59e0b','#7c3aed','#0891b2','#db2777','#65a30d'];
const gridc = getComputedStyle(document.body).getPropertyValue('--border') || '#e5e7eb';
function mk(id,type,labels,data,label,colors){
  const el=document.getElementById(id); if(!el||typeof Chart==='undefined')return;
  new Chart(el,{type:type,data:{labels:labels,datasets:[{label:label||'',data:data,
    backgroundColor:colors||palette, borderColor:(type==='line'?'#1a56db':colors||palette),
    borderWidth:type==='line'?2:0, fill:type==='line'?false:true, tension:.3}]},
    options:{responsive:true,plugins:{legend:{display:(type==='doughnut'||type==='pie')}},
      scales:(type==='doughnut'||type==='pie')?{}:{y:{beginAtZero:true,ticks:{precision:0}}}}});
}
mk('chRoles','doughnut',
   <?= json_encode(array_values(array_map(fn($k)=>$roleLabels[$k]??$k, array_keys($counts['roles'])))) ?>,
   <?= json_encode(array_values($counts['roles'])) ?>, '', null);
mk('chDocs','doughnut',
   <?= json_encode([statusWord('valid'),statusWord('expiring'),statusWord('expired')]) ?>,
   [<?= (int)$docStatus['valid'] ?>,<?= (int)$docStatus['expiring'] ?>,<?= (int)$docStatus['expired'] ?>],
   '', ['#16a34a','#f59e0b','#dc2626']);
mk('chRegs','line', <?= json_encode(array_keys($regs)) ?>, <?= json_encode(array_values($regs)) ?>, '<?= e(t('monthly_registrations')) ?>');
mk('chRev','bar',   <?= json_encode(array_keys($rev)) ?>,  <?= json_encode(array_values($rev)) ?>,  'DZD', ['#16a34a']);
mk('chType','bar',  <?= json_encode(array_values($typeLabels)) ?>, <?= json_encode(array_values($byType)) ?>, '', null);
mk('chViol','doughnut',
   ['unpaid','paid','cancelled'],
   [<?= (int)$violStatus['unpaid'] ?>,<?= (int)$violStatus['paid'] ?>,<?= (int)$violStatus['cancelled'] ?>],
   '', ['#dc2626','#16a34a','#9ca3af']);
</script>
<?php
// helper used above for localized status words
function statusWord($s){ $m=['ar'=>['valid'=>'ساري','expiring'=>'ينتهي قريباً','expired'=>'منتهي'],'en'=>['valid'=>'Valid','expiring'=>'Expiring','expired'=>'Expired'],'fr'=>['valid'=>'Valide','expiring'=>'Expire','expired'=>'Expiré']]; return $m[lang()][$s]??$s; }
?>
<?php require __DIR__.'/../../app/Views/shared/layout_end.php'; ?>
