<?php
require __DIR__ . '/_common.php';
require_perm('view_dashboard');

// KPIs
$kpi = [
  'oases' => intval((db_one("SELECT COUNT(*) c FROM oases")['c'] ?? 0)),
  'aflaj' => intval((db_one("SELECT COUNT(*) c FROM aflaj")['c'] ?? 0)),
  'farms' => intval((db_one("SELECT COUNT(*) c FROM farms")['c'] ?? 0)),
  'assets' => intval((db_one("SELECT COUNT(*) c FROM assets")['c'] ?? 0)),
  'mr_open' => intval((db_one("SELECT COUNT(*) c FROM maintenance_requests WHERE status IN ('open','assigned','in_progress')")['c'] ?? 0)),
  'mr_done' => intval((db_one("SELECT COUNT(*) c FROM maintenance_requests WHERE status='done'")['c'] ?? 0)),
];

$kpi['mr_overdue'] = intval((db_one("SELECT COUNT(*) c FROM maintenance_requests 
                                   WHERE status NOT IN ('done','cancelled')
                                   AND due_date IS NOT NULL
                                   AND due_date < CURDATE()")['c'] ?? 0));

$month = date('Y-m');
$monthTotal = intval((db_one("SELECT COUNT(*) c FROM maintenance_requests WHERE DATE_FORMAT(reported_at,'%Y-%m') = ?", [$month])['c'] ?? 0));
$monthDone  = intval((db_one("SELECT COUNT(*) c FROM maintenance_requests WHERE status='done' AND DATE_FORMAT(reported_at,'%Y-%m') = ?", [$month])['c'] ?? 0));
$monthRate = $monthTotal > 0 ? round(($monthDone/$monthTotal)*100) : 0;

// Widgets data
$recent = db_all("SELECT mr.id, mr.title, mr.priority, mr.status, mr.reported_at, mr.due_date,
                        a.tag asset_tag, a.category asset_category, a.owner_type, a.owner_id
                 FROM maintenance_requests mr
                 JOIN assets a ON a.id = mr.asset_id
                 ORDER BY mr.reported_at DESC
                 LIMIT 10");

$overdue = db_all("SELECT mr.id, mr.title, mr.priority, mr.status, mr.due_date,
                        a.tag asset_tag, a.owner_type, a.owner_id
                 FROM maintenance_requests mr
                 JOIN assets a ON a.id = mr.asset_id
                 WHERE mr.status NOT IN ('done','cancelled')
                 AND mr.due_date IS NOT NULL
                 AND mr.due_date < CURDATE()
                 ORDER BY mr.due_date ASC
                 LIMIT 10");

$badAssets = db_all("SELECT id, tag, category, status, owner_type, owner_id
                    FROM assets
                    WHERE status IN ('needs_service','out_of_order')
                    ORDER BY FIELD(status,'out_of_order','needs_service'), id DESC
                    LIMIT 10");
?>

<div class="kpis">
  <div class="kpi">
    <div class="num"><?= e((string)$kpi['oases']) ?></div>
    <div class="lbl">إجمالي الواحات</div>
  </div>
  <div class="kpi">
    <div class="num"><?= e((string)$kpi['aflaj']) ?></div>
    <div class="lbl">إجمالي الأفلاج</div>
  </div>
  <div class="kpi">
    <div class="num"><?= e((string)$kpi['farms']) ?></div>
    <div class="lbl">إجمالي المزارع</div>
  </div>
  <div class="kpi">
    <div class="num"><?= e((string)$kpi['assets']) ?></div>
    <div class="lbl">إجمالي الأصول</div>
  </div>
  <div class="kpi">
    <div class="num"><?= e((string)$kpi['mr_open']) ?></div>
    <div class="lbl">بلاغات مفتوحة/قيد التنفيذ</div>
    <div class="hint"><?= $kpi['mr_overdue']>0 ? '<span class="badge">متأخر: '.e((string)$kpi['mr_overdue']).'</span>' : '<span class="badge">لا متأخرات</span>' ?></div>
  </div>
  <div class="kpi">
    <div class="num"><?= e((string)$monthRate) ?>%</div>
    <div class="lbl">إنجاز هذا الشهر</div>
    <div class="progress" title="<?= e((string)$monthDone) ?> من <?= e((string)$monthTotal) ?>">
      <div style="width:<?= e((string)$monthRate) ?>%"></div>
    </div>
    <div class="small muted" style="margin-top:6px"><?= e((string)$monthDone) ?> من <?= e((string)$monthTotal) ?></div>
  </div>
</div>

<hr>

<div class="charts" data-dashboard-charts>
  <div class="chart-card">
    <div class="chart-title">
      <h3>توزيع حالات الصيانة</h3>
      <span class="small muted">آخر تحديث: <?= e(date('Y-m-d H:i')) ?></span>
    </div>
    <canvas id="chartMaintenanceStatus" height="140"></canvas>
    <div class="small muted">* المخططات تظهر عند توفر اتصال إنترنت لتحميل Chart.js</div>
  </div>

  <div class="chart-card">
    <div class="chart-title">
      <h3>إنجاز آخر 6 أشهر</h3>
      <span class="small muted"><?= e($month) ?></span>
    </div>
    <canvas id="chartMonthly" height="140"></canvas>
    <div class="small muted">* البيانات من بلاغات الصيانة حسب تاريخ البلاغ</div>
  </div>
</div>

<hr>

<div class="grid-3">
  <div class="card">
    <h2>آخر بلاغات الصيانة</h2>
    <div style="overflow:auto">
      <table class="table">
        <thead>
          <tr>
            <th>#</th>
            <th>الأصل</th>
            <th>الجهة</th>
            <th>العنوان</th>
            <th>الأولوية</th>
            <th>الحالة</th>
            <th>البلاغ</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($recent as $r): ?>
            <tr>
              <td><?= e((string)$r['id']) ?></td>
              <td><?= e($r['asset_tag']) ?><div class="small"><?= e($r['asset_category']) ?></div></td>
              <td class="small"><?= e(owner_label($r['owner_type'], intval($r['owner_id']))) ?></td>
              <td><?= e($r['title']) ?></td>
              <td><?= e($r['priority']) ?></td>
              <td><?= status_tag($r['status']) ?></td>
              <td class="small"><?= e((string)$r['reported_at']) ?></td>
            </tr>
          <?php endforeach; ?>
          <?php if (!$recent): ?>
            <tr><td colspan="7" class="small">لا توجد بيانات بعد.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>

  <div class="card">
    <h2>متأخرات الصيانة</h2>
    <div class="small muted">بلاغات لم تُغلق وموعدها أقل من اليوم.</div>
    <div style="margin-top:10px;overflow:auto">
      <table class="table">
        <thead>
          <tr>
            <th>#</th>
            <th>الأصل</th>
            <th>الجهة</th>
            <th>العنوان</th>
            <th>الاستحقاق</th>
            <th>الحالة</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($overdue as $r): ?>
            <tr>
              <td><?= e((string)$r['id']) ?></td>
              <td><?= e($r['asset_tag']) ?></td>
              <td class="small"><?= e(owner_label($r['owner_type'], intval($r['owner_id']))) ?></td>
              <td><?= e($r['title']) ?></td>
              <td><?= e((string)$r['due_date']) ?></td>
              <td><?= status_tag($r['status']) ?></td>
            </tr>
          <?php endforeach; ?>
          <?php if (!$overdue): ?>
            <tr><td colspan="6" class="small">لا توجد متأخرات حالياً.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>

  <div class="card">
    <h2>أصول تحتاج تدخّل</h2>
    <div class="small muted">الأصول بحالة (بحاجة صيانة/متعطل).</div>
    <div style="margin-top:10px;overflow:auto">
      <table class="table">
        <thead>
          <tr>
            <th>الملصق</th>
            <th>الفئة</th>
            <th>الجهة</th>
            <th>الحالة</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($badAssets as $a): ?>
            <tr>
              <td><?= e($a['tag']) ?></td>
              <td><?= e($a['category']) ?></td>
              <td class="small"><?= e(owner_label($a['owner_type'], intval($a['owner_id']))) ?></td>
              <td><?= status_tag($a['status']) ?></td>
            </tr>
          <?php endforeach; ?>
          <?php if (!$badAssets): ?>
            <tr><td colspan="4" class="small">كل الأصول سليمة.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
