<?php
declare(strict_types=1);

$apiBaseUrl = 'YOUR_API_BASE_URL';
$apiKey = 'YOUR_API_KEY';
$resultMessage = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $payload = [
        'name' => trim($_POST['name'] ?? ''),
        'email' => trim($_POST['email'] ?? ''),
        'phone' => trim($_POST['phone'] ?? ''),
        'caseTypeId' => (int)($_POST['caseTypeId'] ?? 0),
        'message' => trim($_POST['message'] ?? ''),
        'sourceUrl' => $_SERVER['HTTP_REFERER'] ?? '',
    ];

    $ch = curl_init($apiBaseUrl . '/api/leads');
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'X-Api-Key: ' . $apiKey,
        ],
        CURLOPT_POSTFIELDS => json_encode($payload, JSON_THROW_ON_ERROR),
    ]);

    $responseBody = curl_exec($ch);
    $statusCode = (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    curl_close($ch);

    if ($statusCode >= 200 && $statusCode < 300) {
        $resultMessage = 'Lead submitted successfully.';
    } else {
        $resultMessage = 'Submission failed: ' . $responseBody;
    }
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>PHP Affiliate Form Starter</title>
</head>
<body>
  <h1>PHP Affiliate Form</h1>
  <?php if ($resultMessage !== ''): ?>
    <p><?php echo htmlspecialchars($resultMessage, ENT_QUOTES); ?></p>
  <?php endif; ?>

  <form method="post">
    <p><label>Name<br><input name="name" required></label></p>
    <p><label>Email<br><input name="email" type="email" required></label></p>
    <p><label>Phone<br><input name="phone" required></label></p>
    <p><label>Case Type Id<br><input name="caseTypeId" type="number" required></label></p>
    <p><label>Message<br><textarea name="message" required></textarea></label></p>
    <button type="submit">Submit Lead</button>
  </form>
</body>
</html>
