<?php
header('Content-Type: application/json');
require_once __DIR__ . '/db.php';
$pdo = db();

function json($data, $code = 200) {
  http_response_code($code);
  echo json_encode($data);
  exit;
}

$method = $_SERVER['REQUEST_METHOD'];
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : ($method === 'GET' ? 'list' : '');

try {
  if ($method === 'GET' && $action === 'list') {
    $stmt = $pdo->query("SELECT * FROM agents ORDER BY id DESC");
    $rows = $stmt->fetchAll();
    json(['ok' => true, 'data' => $rows]);
  }

  if ($method === 'GET' && $action === 'get') {
    $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
    $stmt = $pdo->prepare("SELECT * FROM agents WHERE id = ?");
    $stmt->execute([$id]);
    $row = $stmt->fetch();
    if (!$row) json(['ok' => false, 'error' => 'Not found'], 404);
    json(['ok' => true, 'data' => $row]);
  }

  if ($method === 'POST' && $action === 'create') {
    $fields = [
      'agent_name', 'email', 'contact_number', 'second_phone',
      'business_name', 'country', 'address'
    ];
    $data = [];
    foreach ($fields as $f) $data[$f] = isset($_POST[$f]) ? trim($_POST[$f]) : null;
    if (!$data['agent_name']) json(['ok' => false, 'error' => 'agent_name required'], 400);
    $stmt = $pdo->prepare("
      INSERT INTO agents (agent_name, email, contact_number, second_phone, business_name, country, address)
      VALUES (?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->execute([
      $data['agent_name'], $data['email'], $data['contact_number'], $data['second_phone'],
      $data['business_name'], $data['country'], $data['address']
    ]);
    $id = (int)$pdo->lastInsertId();
    json(['ok' => true, 'id' => $id]);
  }

  if ($method === 'POST' && $action === 'update') {
    $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
    $stmt = $pdo->prepare("SELECT id FROM agents WHERE id = ?");
    $stmt->execute([$id]);
    if (!$stmt->fetch()) json(['ok' => false, 'error' => 'Not found'], 404);
    $fields = [
      'agent_name', 'email', 'contact_number', 'second_phone',
      'business_name', 'country', 'address'
    ];
    $data = [];
    foreach ($fields as $f) $data[$f] = isset($_POST[$f]) ? trim($_POST[$f]) : null;
    $stmt = $pdo->prepare("
      UPDATE agents SET agent_name = ?, email = ?, contact_number = ?, second_phone = ?, 
      business_name = ?, country = ?, address = ?, updated_at = NOW() WHERE id = ?
    ");
    $stmt->execute([
      $data['agent_name'], $data['email'], $data['contact_number'], $data['second_phone'],
      $data['business_name'], $data['country'], $data['address'], $id
    ]);
    json(['ok' => true, 'id' => $id]);
  }

  if ($method === 'POST' && $action === 'delete') {
    $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
    $stmt = $pdo->prepare("DELETE FROM agents WHERE id = ?");
    $stmt->execute([$id]);
    json(['ok' => true]);
  }

  json(['ok' => false, 'error' => 'invalid request'], 400);
} catch (Throwable $e) {
  json(['ok' => false, 'error' => $e->getMessage()], 500);
}
