<?php
declare(strict_types=1);

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/inc/layout.php';

if (empty($_SESSION['user_id'])) {
    header("Location: index.html?e=1");
    exit;
}

$role = strtoupper((string)($_SESSION['role'] ?? ''));
if (!in_array($role, ['OWNER', 'ADMIN'], true)) {
    http_response_code(403);
    exit('غير مصرح');
}

function h($s): string
{
    return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8');
}

function get_table_columns(PDO $pdo, string $table): array
{
    $st = $pdo->prepare("
        SELECT COLUMN_NAME
        FROM information_schema.columns
        WHERE table_schema = DATABASE()
          AND table_name = ?
    ");
    $st->execute([$table]);
    return $st->fetchAll(PDO::FETCH_COLUMN);
}

$pdo = db();
if (!$pdo instanceof PDO) {
    http_response_code(500);
    exit('DB not ready');
}

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

$rows = [];

try {
    $userCols = get_table_columns($pdo, 'users');

    $displayExpr = "CAST(u.id AS CHAR)";

    if (in_array('full_name', $userCols, true)) {
        $displayExpr = "u.full_name";
    } elseif (in_array('name', $userCols, true)) {
        $displayExpr = "u.name";
    } elseif (in_array('username', $userCols, true)) {
        $displayExpr = "u.username";
    } elseif (in_array('email', $userCols, true)) {
        $displayExpr = "u.email";
    }

    $emailExpr = in_array('email', $userCols, true) ? "u.email" : "NULL";

    $sql = "
        SELECT
            r.id,
            r.employee_id,
            r.note,
            r.status,
            r.created_at,
            {$displayExpr} AS display_name,
            {$emailExpr} AS email
        FROM password_reset_requests r
        LEFT JOIN users u ON u.id = r.employee_id
        ORDER BY
            CASE WHEN r.status = 'pending' THEN 0 ELSE 1 END,
            r.created_at DESC
    ";

    $rows = $pdo->query($sql)->fetchAll();
} catch (Throwable $e) {
    die($e->getMessage());
}

function status_ar(string $status): string
{
    return match ($status) {
        'pending'  => 'قيد الانتظار',
        'approved' => 'تمت الموافقة',
        'rejected' => 'مرفوض',
        'done'     => 'تم التنفيذ',
        default    => $status,
    };
}
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>طلبات إعادة تعيين كلمة المرور</title>
  <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700;800&display=swap" rel="stylesheet">
  <style>
    body{font-family:'Tajawal',sans-serif;background:#f4f7f8;margin:0}
    .page{max-width:1200px;margin:24px auto;padding:0 16px}
    .card{
      background:#fff;border:1px solid #e6edef;border-radius:18px;
      box-shadow:0 10px 30px rgba(0,0,0,.06);overflow:hidden
    }
    .head{
      padding:18px 20px;border-bottom:1px solid #e6edef;
      display:flex;align-items:center;justify-content:space-between
    }
    .head h1{margin:0;color:#00424f;font-size:26px}
    table{width:100%;border-collapse:collapse}
    th,td{padding:14px 12px;border-bottom:1px solid #eef3f4;text-align:right;vertical-align:top}
    th{background:#f9fbfb;color:#00424f}
    .badge{
      display:inline-block;padding:6px 10px;border-radius:999px;font-size:13px;font-weight:700
    }
    .pending{background:#fff7e8;color:#9a6700}
    .approved{background:#eef7ff;color:#155b9a}
    .rejected{background:#fff1f1;color:#9f1d1d}
    .done{background:#ecfdf3;color:#0f6b3f}
    .btn{
      display:inline-block;
      padding:10px 14px;
      border-radius:12px;
      background:#006a7a;
      color:#fff;
      text-decoration:none;
      font-weight:700;
    }
    .muted{color:#6b7a7f}
    @media (max-width:900px){
      .table-wrap{overflow:auto}
      table{min-width:900px}
    }
  </style>
</head>
<body>
  <div class="page">
    <div class="card">
      <div class="head">
        <h1>طلبات إعادة تعيين كلمة المرور</h1>
      </div>

      <div class="table-wrap">
        <table>
          <thead>
            <tr>
              <th>#</th>
              <th>المستخدم</th>
              <th>الإيميل</th>
              <th>الملاحظة</th>
              <th>الحالة</th>
              <th>التاريخ</th>
              <th>إجراء</th>
            </tr>
          </thead>
          <tbody>
            <?php if (!$rows): ?>
              <tr>
                <td colspan="7" class="muted">لا توجد طلبات حالياً.</td>
              </tr>
            <?php else: ?>
              <?php foreach ($rows as $r): ?>
                <tr>
                  <td><?= (int)$r['id'] ?></td>
                  <td><?= h($r['display_name'] ?: ('مستخدم #' . (int)$r['employee_id'])) ?></td>
                  <td><?= h($r['email'] ?: '—') ?></td>
                  <td><?= h($r['note'] ?: '—') ?></td>
                  <td>
                    <span class="badge <?= h((string)$r['status']) ?>">
                      <?= h(status_ar((string)$r['status'])) ?>
                    </span>
                  </td>
                  <td><?= h($r['created_at']) ?></td>
                  <td>
                    <?php if ((string)$r['status'] === 'pending'): ?>
                      <a class="btn" href="admin_reset_password.php?request_id=<?= (int)$r['id'] ?>">إعادة التعيين</a>
                    <?php else: ?>
                      <span class="muted">—</span>
                    <?php endif; ?>
                  </td>
                </tr>
              <?php endforeach; ?>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</body>
</html>