<?php
session_start();
require_once __DIR__ . '/config.php';
ensure_schema();
require_admin();

$pdo = db();

$status = trim($_GET['status'] ?? '');
$payment = trim($_GET['payment'] ?? '');
$q = trim($_GET['q'] ?? '');

$where = "1=1";
$params = [];

if ($status !== '' && in_array($status, ['PENDING','PROCESSING','COMPLETED','REJECTED'], true)) {
  $where .= " AND r.status = ?";
  $params[] = $status;
}
if ($payment !== '' && in_array($payment, ['UNPAID','PAID'], true)) {
  $where .= " AND r.payment_status = ?";
  $params[] = $payment;
}
if ($q !== '') {
  if (ctype_digit($q)) {
    $where .= " AND r.id = ?";
    $params[] = (int)$q;
  } else {
    $where .= " AND (u.username LIKE ? OR r.manufacturer LIKE ? OR r.model LIKE ? OR r.ecu LIKE ? OR r.device LIKE ?)";
    $like = "%".$q."%";
    $params = array_merge($params, [$like,$like,$like,$like,$like]);
  }
}

$st = $pdo->prepare("SELECT r.*, u.username
  FROM requests r
  JOIN users u ON u.id = r.user_id
  WHERE $where
  ORDER BY r.id DESC
  LIMIT 500");
$st->execute($params);
$rows = $st->fetchAll();

$cnt = $pdo->query("SELECT
  SUM(status='PENDING') pending,
  SUM(status='PROCESSING') processing,
  SUM(status='COMPLETED') completed,
  SUM(status='REJECTED') rejected
  FROM requests")->fetch();

?>
<!doctype html><html lang="tr"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php echo h(APP_NAME); ?> • Admin • All Requests</title>
<link rel="stylesheet" href="<?php echo h(BASE_URL); ?>/assets/css/app.css"></head>
<body class="frameGlow"><div class="bgDots"></div><div class="network"></div>

<div style="max-width:1200px;margin:5vh auto;padding:24px;position:relative;z-index:2">
  <div class="card">
    <div class="cardHeader" style="justify-content:space-between">
      <div class="cardTitle"><span class="ico"></span> Admin • All Requests</div>
      <div style="display:flex;gap:10px;align-items:center">
        <span class="badge warn">PENDING <?php echo (int)($cnt['pending']??0); ?></span>
        <span class="badge teal">PROCESSING <?php echo (int)($cnt['processing']??0); ?></span>
        <span class="badge ok">COMPLETED <?php echo (int)($cnt['completed']??0); ?></span>
        <span class="badge bad">REJECTED <?php echo (int)($cnt['rejected']??0); ?></span>
        <a class="btnLink" href="<?php echo h(BASE_URL); ?>/admin_logout.php" style="padding:8px 10px">Çıkış</a>
      </div>
    </div>
    <div class="body">
      <form method="get" style="display:flex;gap:10px;flex-wrap:wrap;align-items:flex-end">
        <div class="field" style="flex:1;min-width:220px">
          <label>Search (ID / username / vehicle / ECU / device)</label>
          <input class="input" name="q" value="<?php echo h($q); ?>" placeholder="e.g. 123  |  bmw  |  demo" />
        </div>
        <div class="field" style="width:220px">
          <label>Status</label>
          <select class="input" name="status">
            <option value="">ALL</option>
            <?php foreach(['PENDING','PROCESSING','COMPLETED','REJECTED'] as $s): ?>
              <option value="<?php echo h($s); ?>" <?php echo $status===$s?'selected':''; ?>><?php echo h($s); ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="field" style="width:180px">
          <label>Payment</label>
          <select class="input" name="payment">
            <option value="">ALL</option>
            <?php foreach(['UNPAID','PAID'] as $p): ?>
              <option value="<?php echo h($p); ?>" <?php echo $payment===$p?'selected':''; ?>><?php echo h($p); ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="field" style="width:160px">
          <button class="btnLink" type="submit" style="width:100%;justify-content:center">Filter</button>
        </div>
      </form>

      <div class="hr"></div>

      <div style="overflow:auto">
        <table class="table">
          <thead>
            <tr>
              <th style="width:90px">ID</th>
              <th>User</th>
              <th>Vehicle</th>
              <th>ECU</th>
              <th>Status</th>
              <th>Payment</th>
              <th style="width:160px">Created</th>
              <th style="width:140px">Action</th>
            </tr>
          </thead>
          <tbody>
          <?php if(!$rows): ?>
            <tr><td colspan="8"><small>No requests found.</small></td></tr>
          <?php else: foreach($rows as $r): ?>
            <tr>
              <td>#<?php echo (int)$r['id']; ?></td>
              <td><?php echo h($r['username']); ?></td>
              <td><?php echo h(trim(($r['manufacturer']??'').' '.($r['model']??''))); ?></td>
              <td><?php echo h($r['ecu']??'-'); ?></td>
              <td>
                <?php
                  $cls = 'warn';
                  if($r['status']==='COMPLETED') $cls='ok';
                  elseif($r['status']==='PROCESSING') $cls='teal';
                  elseif($r['status']==='REJECTED') $cls='bad';
                ?>
                <span class="badge <?php echo $cls; ?>"><?php echo h($r['status']); ?></span>
              </td>
              <td>
                <?php $pcls = ($r['payment_status']==='PAID') ? 'ok' : 'warn'; ?>
                <span class="badge <?php echo $pcls; ?>"><?php echo h($r['payment_status']??'UNPAID'); ?></span>
              </td>
              <td><?php echo h($r['created_at']); ?></td>
              <td><a class="btnLink" href="<?php echo h(BASE_URL); ?>/admin_request_view.php?id=<?php echo (int)$r['id']; ?>" style="padding:8px 10px">Open</a></td>
            </tr>
          <?php endforeach; endif; ?>
          </tbody>
        </table>
      </div>
      <div class="note" style="margin-top:14px">
        Admin login: <b>admin</b> / <b>admin123</b> (ilk girişten sonra değiştirmen önerilir).
      </div>
    </div>
  </div>
</div>
</body></html>
