<?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;
  }

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

  // Build payload according to the Partner JSON schema
  $payload = [
    "companyName" => $clean($data['companyName'] ?? ''),
    "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'] ?? ''),
    "partnershipTypes" => $data['partnershipTypes'] ?? [],
    "contributionInterest" => $clean($data['contributionInterest'] ?? ''),
    "valueExpectations" => $data['valueExpectations'] ?? [],
    "valueExpectationsOther" => $clean($data['valueExpectationsOther'] ?? '')
  ];

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

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

  if ($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;
}
?>
