<?php
require_once __DIR__ . '/includes/auth.php';
require_admin();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && csrf_check()) {
    $name = trim($_POST['name'] ?? '');
    $title = trim($_POST['title'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $whatsapp = trim($_POST['whatsapp'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $bio = trim($_POST['bio'] ?? '');
    $sortOrder = (int)($_POST['sort_order'] ?? 0);

    $uploadedPhoto = null;
    if (!empty($_FILES['photo']['tmp_name']) && is_uploaded_file($_FILES['photo']['tmp_name'])) {
        $ext = strtolower(pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION));
        if (in_array($ext, ['jpg', 'jpeg', 'png', 'webp'], true)) {
            $dir = __DIR__ . '/../assets/images/team/';
            if (!is_dir($dir)) mkdir($dir, 0755, true);
            $filename = 'agent-' . time() . '.' . $ext;
            move_uploaded_file($_FILES['photo']['tmp_name'], $dir . $filename);
            $uploadedPhoto = 'assets/images/team/' . $filename;
        }
    }

    if ($name !== '' && $title !== '') {
        if (!empty($_POST['id'])) {
            if ($uploadedPhoto) {
                db()->prepare('UPDATE agents SET name=?, title=?, phone=?, whatsapp=?, email=?, bio=?, sort_order=?, photo=? WHERE id=?')
                    ->execute([$name, $title, $phone, $whatsapp, $email, $bio, $sortOrder, $uploadedPhoto, (int)$_POST['id']]);
            } else {
                db()->prepare('UPDATE agents SET name=?, title=?, phone=?, whatsapp=?, email=?, bio=?, sort_order=? WHERE id=?')
                    ->execute([$name, $title, $phone, $whatsapp, $email, $bio, $sortOrder, (int)$_POST['id']]);
            }
        } else {
            db()->prepare('INSERT INTO agents (name, title, phone, whatsapp, email, bio, sort_order, photo) VALUES (?,?,?,?,?,?,?,?)')
                ->execute([$name, $title, $phone, $whatsapp, $email, $bio, $sortOrder, $uploadedPhoto ?: '']);
        }
    }
    header('Location: /admin/agents.php');
    exit;
}
if (!empty($_GET['delete']) && isset($_GET['csrf']) && hash_equals($_SESSION['csrf'] ?? '', $_GET['csrf'])) {
    db()->prepare('DELETE FROM agents WHERE id=?')->execute([(int)$_GET['delete']]);
    header('Location: /admin/agents.php');
    exit;
}

$editing = null;
if (!empty($_GET['edit'])) {
    $stmt = db()->prepare('SELECT * FROM agents WHERE id=?');
    $stmt->execute([(int)$_GET['edit']]);
    $editing = $stmt->fetch();
}

$agents = db()->query('SELECT * FROM agents ORDER BY sort_order')->fetchAll();
$pageTitle = 'Agents';
include __DIR__ . '/includes/layout-header.php';
?>
<div class="admin-card mb-6">
  <h3><?= $editing ? 'Edit Agent' : 'Add Agent' ?></h3>
  <form method="post" enctype="multipart/form-data">
    <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
    <?php if ($editing): ?><input type="hidden" name="id" value="<?= (int)$editing['id'] ?>"><?php endif; ?>
    <div class="field-row mb-4">
      <div class="field"><label>Name</label><input type="text" name="name" value="<?= e($editing['name'] ?? '') ?>" required></div>
      <div class="field"><label>Title</label><input type="text" name="title" value="<?= e($editing['title'] ?? '') ?>" required></div>
    </div>
    <div class="field-row mb-4">
      <div class="field"><label>Phone</label><input type="text" name="phone" value="<?= e($editing['phone'] ?? SITE_PHONE) ?>"></div>
      <div class="field"><label>WhatsApp (digits only)</label><input type="text" name="whatsapp" value="<?= e($editing['whatsapp'] ?? SITE_WHATSAPP) ?>"></div>
      <div class="field"><label>Email</label><input type="email" name="email" value="<?= e($editing['email'] ?? '') ?>"></div>
    </div>
    <div class="field mb-4"><label>Bio</label><textarea name="bio" rows="3"><?= e($editing['bio'] ?? '') ?></textarea></div>
    <div class="field-row mb-4">
      <div class="field"><label>Sort Order</label><input type="number" name="sort_order" value="<?= e($editing['sort_order'] ?? '0') ?>"></div>
      <div class="field"><label>Photo (optional — falls back to initials avatar)</label><input type="file" name="photo" accept="image/*"></div>
    </div>
    <button type="submit" class="btn btn-primary"><?= $editing ? 'Update' : 'Add' ?> Agent</button>
    <?php if ($editing): ?><a href="/admin/agents.php" class="btn btn-outline">Cancel</a><?php endif; ?>
  </form>
</div>
<div class="admin-card" style="padding:0;overflow-x:auto;">
  <table class="admin-table">
    <thead><tr><th></th><th>Name</th><th>Title</th><th>Contact</th><th></th></tr></thead>
    <tbody>
      <?php foreach ($agents as $a): ?>
        <tr>
          <td><?= avatar_html($a['name'], 'sm', $a['photo']) ?></td>
          <td class="fw-semibold"><?= e($a['name']) ?></td>
          <td><?= e($a['title']) ?></td>
          <td><?= e($a['phone']) ?><br><span class="text-muted text-xs"><?= e($a['email']) ?></span></td>
          <td class="flex gap-2">
            <a href="/admin/agents.php?edit=<?= (int)$a['id'] ?>" class="btn btn-outline btn-sm">Edit</a>
            <a href="/admin/agents.php?delete=<?= (int)$a['id'] ?>&csrf=<?= e(csrf_token()) ?>" class="btn btn-outline btn-sm" onclick="return confirm('Delete this agent?')">Delete</a>
          </td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>
<?php include __DIR__ . '/includes/layout-footer.php'; ?>
