<?php
require __DIR__ . '/../../app/bootstrap.php';
auth_require();

header('Content-Type: application/json; charset=utf-8');

$u = auth_user();
if (!auth_can('view_dashboard')) {
  http_response_code(403);
  echo json_encode(['error'=>'forbidden'], JSON_UNESCAPED_UNICODE);
  exit;
}

// Maintenance status distribution
$ms = db_all("SELECT status, COUNT(*) c FROM maintenance_requests GROUP BY status");
$map = ['open'=>0,'assigned'=>0,'in_progress'=>0,'done'=>0,'cancelled'=>0];
foreach ($ms as $r) {
  $k = (string)$r['status'];
  if (isset($map[$k])) $map[$k] = intval($r['c']);
}
$labels = ['مفتوح','مُسند','قيد التنفيذ','منجز','ملغي'];
$values = [$map['open'],$map['assigned'],$map['in_progress'],$map['done'],$map['cancelled']];

// Monthly totals last 6 months
$labels2 = [];
$total = [];
$done = [];
for ($i=5; $i>=0; $i--) {
  $m = date('Y-m', strtotime("-{$i} months"));
  $labels2[] = $m;
  $t = db_one("SELECT COUNT(*) c FROM maintenance_requests WHERE DATE_FORMAT(reported_at,'%Y-%m') = ?", [$m])['c'] ?? 0;
  $d = db_one("SELECT COUNT(*) c FROM maintenance_requests WHERE status='done' AND DATE_FORMAT(reported_at,'%Y-%m') = ?", [$m])['c'] ?? 0;
  $total[] = intval($t);
  $done[] = intval($d);
}

echo json_encode([
  'maintenanceStatus' => ['labels'=>$labels,'values'=>$values],
  'monthly' => ['labels'=>$labels2,'total'=>$total,'done'=>$done],
], JSON_UNESCAPED_UNICODE);
