<?php
header('Content-Type: application/json');

require_once __DIR__ . '/config.php';

if (!function_exists('curl_init')) {
  echo json_encode(array('reply' => 'Server error: cURL is not enabled on this hosting.'));
  exit;
}

$message = '';
if (isset($_GET['m'])) {
  $message = $_GET['m'];
} else {
  $raw = file_get_contents('php://input');
  $json = json_decode($raw, true);
  if (is_array($json) && isset($json['message'])) $message = $json['message'];
}
$message = trim($message);

if ($message === '') {
  echo json_encode(array('reply' => 'Please type a message.'));
  exit;
}

$system = "You are the AI assistant for WhataShine Hospitality (commercial & hospitality cleaning). Ask 1–3 quick questions to qualify the request (city, rooms/sqft, frequency, timeline). Keep it concise.";

$payload = array(
  'model' => OPENAI_MODEL,
  'input' => array(
    array('role' => 'system', 'content' => $system),
    array('role' => 'user', 'content' => $message)
  )
);

$ch = curl_init('https://api.openai.com/v1/responses');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  'Content-Type: application/json',
  'Authorization: Bearer ' . OPENAI_API_KEY
));
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 25);

$response = curl_exec($ch);
$http = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if (curl_errno($ch)) {
  $err = curl_error($ch);
  curl_close($ch);
  echo json_encode(array('reply' => 'cURL error: ' . $err));
  exit;
}
curl_close($ch);

if ($http < 200 || $http >= 300) {
  echo json_encode(array('reply' => 'OpenAI HTTP ' . $http, 'raw' => $response));
  exit;
}

$data = json_decode($response, true);

// Robust output extraction
$reply = '';
if (isset($data['output_text']) && is_string($data['output_text'])) {
  $reply = $data['output_text'];
}
if ($reply === '' && isset($data['output']) && is_array($data['output'])) {
  foreach ($data['output'] as $outItem) {
    if (isset($outItem['content']) && is_array($outItem['content'])) {
      foreach ($outItem['content'] as $c) {
        if (isset($c['type']) && $c['type'] === 'output_text' && isset($c['text'])) {
          $reply .= $c['text'];
        }
      }
    }
  }
}

if ($reply === '') $reply = 'No output returned.';
echo json_encode(array('reply' => $reply));
exit;
?>



