<?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 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 schema
  $payload = [
    "fullName" => $clean($data['fullName'] ?? ''),
    "email" => filter_var($data['email'] ?? '', FILTER_SANITIZE_EMAIL),
    "mobile" => $clean($data['mobile'] ?? ''),
    "gender" => $clean($data['gender'] ?? ''),
    "dateOfBirth" => $clean($data['dateOfBirth'] ?? ''),
    "residentialCity" => $clean($data['residentialCity'] ?? ''),
    "residentialCountry" => $clean($data['residentialCountry'] ?? ''),
    "nationality" => $clean($data['nationality'] ?? ''),
    "occupationDesignation" => $clean($data['occupationDesignation'] ?? ''),
    "organizationInstitution" => $clean($data['organizationInstitution'] ?? ''),
    "industrySectors" => $data['industrySectors'] ?? [],
    "industrySectorsOther" => $clean($data['industrySectorsOther'] ?? ''),
    "expectations" => $data['expectations'] ?? [],
    "expectationsOther" => $clean($data['expectationsOther'] ?? ''),
    "heardAbout" => $clean($data['heardAbout'] ?? ''),
    "specialRequirements" => $clean($data['specialRequirements'] ?? ''),
    "consent" => isset($data['consent']) && $data['consent'] === 'true'
  ];

  $call_type = 'POST';
  $callurl = 'register'; // ✅ change to your API route
  $sendRequest = postRequest($callurl, $payload);

  // --- Extract response ---
  $requestStatus = $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) {
  // Return any unhandled exceptions as JSON
  echo json_encode([
    'status' => 'error',
    'message' => 'Internal Server Error: ' . $e->getMessage()
  ]);
  exit;
}
?>
