<?php
include_once 'auth-core.php';
header('Content-Type: application/json');

try {
  // Capture JSON payload from AJAX request
  $input = file_get_contents("php://input");
  $data = json_decode($input, true);

  // Handle invalid or empty payload
  if (!$data) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid or empty JSON payload']);
    exit;
  }

  // Simple sanitizer helper
  $clean = function($val) { return htmlspecialchars(trim($val ?? '')); };

  // Build payload according to the Sponsorship JSON schema
  $payload = [
    "companyName" => $clean($data['companyName'] ?? ''),
    "packageInterest" => $clean($data['packageInterest'] ?? ''),
    "contactPersonAndTitle" => $clean($data['contactPersonAndTitle'] ?? ''),
    "email" => filter_var($data['email'] ?? '', FILTER_SANITIZE_EMAIL),
    "phone" => $clean($data['phone'] ?? ''),
    "businessCity" => $clean($data['businessCity'] ?? ''),
    "businessCountry" => $clean($data['businessCountry'] ?? ''),
    "website" => $clean($data['website'] ?? ''),
    "customPackageDetails" => $clean($data['customPackageDetails'] ?? ''),
    "preferredSectors" => $data['preferredSectors'] ?? [],
    "preferredSectorsOther" => $clean($data['preferredSectorsOther'] ?? ''),
    "objectivesRoi" => $clean($data['objectivesRoi'] ?? '')
  ];

  // --- Make API call ---
  $call_type = 'POST';
  $callurl = 'sponsors'; // ✅ replace with your actual endpoint route (e.g. 'sponsorship/register')
  $sendRequest = postRequest($callurl, $payload);

  // --- Handle API response ---
  $requestStatus = $sendRequest['status'] ?? 'error';
  $responseMessage = $sendRequest['message']['errorMessage'] ?? 'No message from API';

  if (strtolower($requestStatus) === 'success') {
    echo json_encode([
      'status' => 'success',
      'message' => $sendRequest
    ]);
  } else {
    echo json_encode([
      'status' => 'error',
      'message' => $sendRequest
    ]);
  }

  exit;

} catch (Throwable $e) {
  // --- Handle exceptions gracefully ---
  echo json_encode([
    'status' => 'error',
    'message' => 'Internal Server Error: ' . $e->getMessage()
  ]);
  exit;
}
?>
