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

$month = trim($_GET['month'] ?? 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) {
  $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.*, 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 2000", $params);

$oasisName = 'كل الواحات';
if ($oasis_id>0) {
  $o = db_one("SELECT name,code FROM oases WHERE id=?", [$oasis_id]);
  if ($o) $oasisName = $o['name'].' ('.$o['code'].')';
}


// --- Logo + KPI helpers (print / Save as PDF from browser) ---
if (!function_exists('file_to_data_uri')) {
function file_to_data_uri(string $absPath): string {
  if (!is_file($absPath)) return '';
  $ext = strtolower(pathinfo($absPath, PATHINFO_EXTENSION));
  $mime = 'image/png';
  if ($ext==='svg') $mime='image/svg+xml';
  elseif ($ext==='jpg' || $ext==='jpeg') $mime='image/jpeg';
  elseif ($ext==='webp') $mime='image/webp';
  $data = file_get_contents($absPath);
  if ($data === false) return '';
  return 'data:'.$mime.';base64,'.base64_encode($data);
}}
$logoRel = trim((string)app_config('REPORT_LOGO','assets/logo-placeholder.svg'));
$logoAbs = __DIR__ . '/' . ltrim($logoRel, '/');
if (!is_file($logoAbs)) { $logoAbs = __DIR__ . '/assets/logo-placeholder.svg'; }
$logoData = file_to_data_uri($logoAbs);

// KPI summary for selected month
$kpi_total = count($rows);
$kpi_by_status = ['open'=>0,'assigned'=>0,'in_progress'=>0,'done'=>0,'cancelled'=>0];
$kpi_overdue = 0;
$kpi_completed = 0;
$kpi_total_days = 0;
foreach ($rows as $r) {
  $st = (string)($r['status'] ?? '');
  if (isset($kpi_by_status[$st])) $kpi_by_status[$st]++; 
  // overdue: due_at exists and status not done/cancelled and due_at < now
  $due = $r['due_at'] ?? null;
  if ($due && !in_array($st, ['done','cancelled'], true)) {
    if (strtotime((string)$due) !== false && strtotime((string)$due) < time()) $kpi_overdue++;
  }
  $comp = $r['completed_at'] ?? null;
  if ($comp && strtotime((string)$comp) !== false) {
    $kpi_completed++;
    $ra = $r['reported_at'] ?? null;
    if ($ra && strtotime((string)$ra) !== false) {
      $kpi_total_days += max(0, (strtotime((string)$comp) - strtotime((string)$ra)) / 86400);
    }
  }
}
$kpi_avg_days = ($kpi_completed>0) ? round($kpi_total_days / $kpi_completed, 1) : 0;
$hdr = app_config('REPORT_HEADER','بلدية العين - نظام إدارة الواحات والأفلاج');
$sub = app_config('REPORT_SUBHEADER','تقرير رسمي');
$ftr = app_config('REPORT_FOOTER','هذا التقرير صادر إلكترونيًا عن النظام.');
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>تقرير شهري</title>
  <style>
    body{font-family:Tahoma,Arial,sans-serif;margin:24px;color:#111}
    .head{display:flex;justify-content:space-between;align-items:flex-start;gap:16px}
    .brand{font-weight:800;font-size:18px}
    .sub{color:#444;margin-top:6px}
    .meta{font-size:12px;color:#333;text-align:left;direction:ltr}
    hr{border:0;border-top:1px solid #ddd;margin:14px 0}
    
    .head{direction:rtl}
    .head .r{flex:1;direction:rtl;text-align:right}
    .head .l{width:240px;direction:ltr;text-align:left}
    .logo{max-width:220px;max-height:64px;display:block;margin-left:auto}
    .kpis{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin-top:12px}
    .kpi{border:1px solid #ddd;border-radius:10px;padding:10px}
    .kpi .k{font-size:11px;color:#444;margin-bottom:6px}
    .kpi .v{font-size:18px;font-weight:800}
    @media print {
      body{margin:0;padding:0}
      .no-print{display:none !important}
      .kpis{grid-template-columns:repeat(4,1fr)}
      th,td{font-size:10px}
    }

table{width:100%;border-collapse:collapse;font-size:12px}
    th,td{border:1px solid #ddd;padding:8px;vertical-align:top}
    th{background:#f6f6f6;text-align:right}
    .tag{display:inline-block;padding:2px 8px;border:1px solid #ddd;border-radius:999px;font-size:11px}
    .footer{margin-top:18px;font-size:12px;color:#333}
    @media print { .no-print{display:none} body{margin:0} }
  </style>
</head>
<body>
  <div class="no-print" style="margin-bottom:12px">
    <button onclick="window.print()">طباعة / حفظ PDF</button>
  </div>

  <div class="head">
    <div class="r">
      <div class="brand"><?php echo h($hdr); ?></div>
      <div class="sub"><?php echo h($sub); ?> — <b><?php echo h($month); ?></b></div>
      <div class="sub">النطاق: <?php echo h($oasisName); ?></div>
    </div>
    <div class="l">
      <?php if ($logoData): ?>
        <img class="logo" src="<?php echo $logoData; ?>" alt="logo">
      <?php endif; ?>
      <div class="meta">
        Generated: <?php echo date('Y-m-d H:i'); ?><br>
        Records: <?php echo (int)$kpi_total; ?>
      </div>
    </div>
  </div>
  <div class="kpis">
    <div class="kpi"><div class="k">إجمالي البلاغات</div><div class="v"><?php echo (int)$kpi_total; ?></div></div>
    <div class="kpi"><div class="k">مفتوح</div><div class="v"><?php echo (int)$kpi_by_status['open']; ?></div></div>
    <div class="kpi"><div class="k">مسند</div><div class="v"><?php echo (int)$kpi_by_status['assigned']; ?></div></div>
    <div class="kpi"><div class="k">قيد التنفيذ</div><div class="v"><?php echo (int)$kpi_by_status['in_progress']; ?></div></div>
    <div class="kpi"><div class="k">منجز</div><div class="v"><?php echo (int)$kpi_by_status['done']; ?></div></div>
    <div class="kpi"><div class="k">متأخر</div><div class="v"><?php echo (int)$kpi_overdue; ?></div></div>
    <div class="kpi"><div class="k">متوسط أيام الإنجاز</div><div class="v"><?php echo h((string)$kpi_avg_days); ?></div></div>
  </div>
  <hr>

  <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 style="color:#666"><?= e($r['asset_category']) ?></div></td>
          <td><?= e(owner_label($r['owner_type'], intval($r['owner_id']))) ?></td>
          <td><?= e($r['title']) ?></td>
          <td><?= e($r['priority']) ?></td>
          <td><span class="tag"><?= e($r['status']) ?></span></td>
          <td><?= e((string)$r['reported_at']) ?></td>
          <td><?= e((string)($r['due_date'] ?? '-')) ?></td>
          <td><?= e((string)($r['reported_name'] ?? '-')) ?></td>
          <td><?= e((string)($r['assigned_name'] ?? '-')) ?></td>
          <td><?= e((string)($r['actual_cost'] ?? '-')) ?></td>
        </tr>
      <?php endforeach; ?>
      <?php if (!$rows): ?>
        <tr><td colspan="11">لا توجد بيانات.</td></tr>
      <?php endif; ?>
    </tbody>
  </table>

  <div class="footer">
    <div>التوقيع: _______________________</div>
    <div style="margin-top:6px"><?= e(app_config('REPORT_FOOTER','هذا التقرير صادر إلكترونيًا عن النظام.')) ?></div>
  </div>
</body>
</html>
