<?php
require_once __DIR__ . '/../config.php';
requireAdmin();
$db = getDB();
$admin_page = 'dealers';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['update_status'])) {
        $id = (int)$_POST['dealer_id'];
        $status = $_POST['status'];
        $db->prepare("UPDATE dealers SET status=? WHERE id=?")->execute([$status, $id]);
    }
}

$dealers = $db->query("SELECT * FROM dealers ORDER BY created_at DESC")->fetchAll();
$page_title = 'Dealer Management';
include __DIR__ . '/header.php';
?>
<div class="card">
  <div class="card-header">
    <h2>All Dealers (<?= count($dealers) ?>)</h2>
  </div>
  <div class="table-wrap">
    <table>
      <thead>
        <tr>
          <th>Company / Name</th>
          <th>Contact</th>
          <th>Location</th>
          <th>GSTIN</th>
          <th>Status</th>
          <th>Joined</th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($dealers as $d): ?>
        <tr>
          <td>
            <strong><?= h($d['company_name']) ?></strong><br>
            <span style="font-size:.8rem;color:var(--text-light);"><?= h($d['name']) ?></span>
          </td>
          <td>
            <a href="mailto:<?= h($d['email']) ?>"><?= h($d['email']) ?></a><br>
            <a href="tel:<?= h($d['phone']) ?>"><?= h($d['phone']) ?></a>
          </td>
          <td><?= h($d['city'] . ', ' . $d['state']) ?></td>
          <td><?= h($d['gstin'] ?: 'N/A') ?></td>
          <td>
            <span class="badge badge-<?= $d['status']==='approved'?'active':($d['status']==='pending'?'new':'inactive') ?>">
              <?= ucfirst($d['status']) ?>
            </span>
          </td>
          <td><?= date('d M Y', strtotime($d['created_at'])) ?></td>
          <td>
            <form method="POST" style="display:inline-flex;gap:5px;">
              <input type="hidden" name="update_status" value="1">
              <input type="hidden" name="dealer_id" value="<?= $d['id'] ?>">
              <select name="status" onchange="this.form.submit()" style="padding:4px;font-size:.8rem;border-radius:4px;border:1px solid #e2e8f0;">
                <option value="pending" <?= $d['status']==='pending'?'selected':'' ?>>Pending</option>
                <option value="approved" <?= $d['status']==='approved'?'selected':'' ?>>Approved</option>
                <option value="rejected" <?= $d['status']==='rejected'?'selected':'' ?>>Rejected</option>
                <option value="blocked" <?= $d['status']==='blocked'?'selected':'' ?>>Blocked</option>
              </select>
            </form>
          </td>
        </tr>
        <?php endforeach; ?>
        <?php if(!$dealers): ?>
        <tr><td colspan="7" style="text-align:center;">No dealers found.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>
<?php include __DIR__ . '/footer.php'; ?>
