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

$month = isset($_GET['month']) ? trim((string)$_GET['month']) : '';
// تأكد من الصيغة YYYY-MM
if ($month !== '' && !preg_match('/^\d{4}-\d{2}$/', $month)) {
  $month = '';
}

// إذا لم يتم تحديد شهر، اختر آخر شهر فيه بلاغات صيانة
// (بدل الاعتماد على تاريخ النظام الذي قد يكون غير مضبوط على جهاز المستخدم)
if ($month === '') {
  $lastYm = null;
  try {
    if (function_exists('db_first')) {
      $r = db_first("SELECT DATE_FORMAT(MAX(reported_at),'%Y-%m') AS ym FROM maintenance_requests");
      $lastYm = $r['ym'] ?? null;
    } else {
      $r = db_all("SELECT DATE_FORMAT(MAX(reported_at),'%Y-%m') AS ym FROM maintenance_requests");
      $lastYm = $r[0]['ym'] ?? null;
    }
  } catch (Throwable $e) {
    $lastYm = null;
  }
  $month = $lastYm ?: date('Y-m');
}
$oasis_id = intval($_GET['oasis_id'] ?? 0);
$status = trim($_GET['status'] ?? '');
$assigned_to = intval($_GET['assigned_to'] ?? 0);

$params = [];
$where = [];

if (preg_match('/^\d{4}-\d{2}$/', $month)) {
  $where[] = "DATE_FORMAT(mr.reported_at,'%Y-%m') = ?";
  $params[] = $month;
}
if ($status !== '' && in_array($status, ['open','assigned','in_progress','done','cancelled'], true)) {
  $where[] = "mr.status = ?";
  $params[] = $status;
}
if ($assigned_to > 0) {
  $where[] = "mr.assigned_to = ?";
  $params[] = $assigned_to;
}
if ($oasis_id > 0) {
  // filter by oasis through asset owner_type/owner_id relations:
  // if asset owned by oasis directly OR by falaj/farm within that oasis
  $where[] = "( (a.owner_type='oasis' AND a.owner_id=?) 
            OR (a.owner_type='falaj' AND a.owner_id IN (SELECT id FROM aflaj WHERE oasis_id=?))
            OR (a.owner_type='farm'  AND a.owner_id IN (SELECT id FROM farms WHERE oasis_id=?)) )";
  $params[] = $oasis_id; $params[] = $oasis_id; $params[] = $oasis_id;
}

$whereSql = $where ? ("WHERE " . implode(" AND ", $where)) : "";

$rows = db_all("SELECT mr.id, mr.title, mr.priority, mr.status, mr.reported_at, mr.due_date, mr.actual_cost,
                      a.tag asset_tag, a.category asset_category, a.owner_type, a.owner_id,
                      u1.name reported_name, u2.name assigned_name
               FROM maintenance_requests mr
               JOIN assets a ON a.id = mr.asset_id
               LEFT JOIN users u1 ON u1.id = mr.reported_by
               LEFT JOIN users u2 ON u2.id = mr.assigned_to
               $whereSql
               ORDER BY mr.reported_at DESC
               LIMIT 500", $params);

$oases = db_all("SELECT id, name, code FROM oases ORDER BY name ASC");
$users = db_all("SELECT id, name, role FROM users ORDER BY name ASC");

// summary
$sumTotal = count($rows);
$sumDone = 0;
$sumCost = 0.0;
foreach ($rows as $r) {
  if (($r['status'] ?? '') === 'done') $sumDone++;
  $sumCost += floatval($r['actual_cost'] ?? 0);
}
$rate = $sumTotal ? round(($sumDone/$sumTotal)*100) : 0;

$qs = http_build_query([
  'month'=>$month,
  'oasis_id'=>$oasis_id ?: '',
  'status'=>$status,
  'assigned_to'=>$assigned_to ?: '',
]);
?>
<h1>التقارير</h1>
<div class="small muted">تقرير شهري لبلاغات الصيانة مع مؤشرات الأداء وتصدير رسمي.</div>

<hr>

<form class="actions" method="get" action="<?= e(url('/index.php')) ?>">
  <input type="hidden" name="page" value="reports">
  <input class="input" type="month" name="month" style="max-width:140px" value="<?= e($month) ?>">
  <select class="input" name="oasis_id" style="max-width:260px">
    <option value="0">كل الواحات</option>
    <?php foreach ($oases as $o): ?>
      <option value="<?= e((string)$o['id']) ?>" <?= $oasis_id==intval($o['id'])?'selected':'' ?>>
        <?= e($o['name']) ?> (<?= e($o['code']) ?>)
      </option>
    <?php endforeach; ?>
  </select>
  <select class="input" name="status" style="max-width:170px">
    <option value="">كل الحالات</option>
    <?php foreach (['open'=>'مفتوح','assigned'=>'مُسند','in_progress'=>'قيد التنفيذ','done'=>'منجز','cancelled'=>'ملغي'] as $k=>$v): ?>
      <option value="<?= e($k) ?>" <?= $status===$k?'selected':'' ?>><?= e($v) ?></option>
    <?php endforeach; ?>
  </select>
  <select class="input" name="assigned_to" style="max-width:240px">
    <option value="0">كل المكلّفين</option>
    <?php foreach ($users as $u): ?>
      <option value="<?= e((string)$u['id']) ?>" <?= $assigned_to==intval($u['id'])?'selected':'' ?>>
        <?= e($u['name']) ?> (<?= e($u['role']) ?>)
      </option>
    <?php endforeach; ?>
  </select>
  <button class="btn primary">تطبيق</button>
  <a class="btn" href="<?= e(url('/index.php?page=reports')) ?>">إعادة ضبط</a>

  <?php if (auth_can('export_reports_pdf')): ?>
    <a class="btn" href="<?= e(url('/report_monthly_print.php?' . $qs)) ?>" target="_blank">نسخة رسمية للطباعة (PDF)</a>
    <a class="btn" href="<?= e(url('/report_monthly_pdf.php?' . $qs)) ?>">PDF نصي سريع</a>
  <?php endif; ?>

  <?php if (auth_can('export_xlsx')): ?>
    <a class="btn" href="<?= e(url('/index.php?page=export_xlsx&entity=master&month=' . urlencode($month) . '&oasis_id=' . intval($oasis_id))) ?>">تقرير Excel شامل (حسب الفلاتر)</a>
    <a class="btn" href="<?= e(url('/index.php?page=export_xlsx&entity=master&all=1')) ?>">تقرير Excel شامل (كل البيانات)</a>
  <?php endif; ?>

</form>

<hr>

<div class="grid-3">
  <div class="kpi">
    <div class="num"><?= e((string)$sumTotal) ?></div>
    <div class="lbl">إجمالي البلاغات</div>
  </div>
  <div class="kpi">
    <div class="num"><?= e((string)$sumDone) ?></div>
    <div class="lbl">بلاغات منجزة</div>
    <div class="progress" title="<?= e((string)$rate) ?>%">
      <div style="width:<?= e((string)$rate) ?>%"></div>
    </div>
  </div>
  <div class="kpi">
    <div class="num"><?= e(number_format($sumCost, 2)) ?></div>
    <div class="lbl">إجمالي تكاليف منفذة</div>
  </div>
</div>

<hr>

<div style="overflow:auto">
  <table class="table">
    <thead>
      <tr>
        <th>#</th>
        <th>الأصل</th>
        <th>الجهة</th>
        <th>العنوان</th>
        <th>الأولوية</th>
        <th>الحالة</th>
        <th>البلاغ</th>
        <th>الاستحقاق</th>
        <th>مُبلِّغ</th>
        <th>مُكلّف</th>
        <th>تكلفة</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($rows 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>
          <td class="small"><?= e((string)($r['due_date'] ?? '-')) ?></td>
          <td class="small"><?= e((string)($r['reported_name'] ?? '-')) ?></td>
          <td class="small"><?= e((string)($r['assigned_name'] ?? '-')) ?></td>
          <td class="small"><?= e((string)($r['actual_cost'] ?? '-')) ?></td>
        </tr>
      <?php endforeach; ?>
      <?php if (!$rows): ?>
        <tr><td colspan="11" class="small">لا توجد بيانات ضمن الفلاتر الحالية.</td></tr>
      <?php endif; ?>
    </tbody>
  </table>
</div>
