<?php
// ai-generator.php
require_once 'config.php';

// Set the correct header to return JSON
header('Content-Type: application/json');

// Function to send a structured response
function send_json_response($success, $data) {
    echo json_encode(['success' => $success, $success ? 'description' : 'message' => $data]);
    exit();
}

// 1. VALIDATE THE REQUEST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    send_json_response(false, 'Invalid request method.');
}

$input = json_decode(file_get_contents('php://input'), true);
$keywords = trim($input['keywords'] ?? '');

if (empty($keywords)) {
    send_json_response(false, 'Keywords are required.');
}

// 2. CONSTRUCT THE AI PROMPT
// This prompt guides the AI to write in the correct style and format.
$prompt = "You are a creative travel copywriter. Write a compelling, SEO-friendly tour description for a package titled '{$keywords}'. The description should be engaging, around 100-150 words, and highlight the key attractions and experiences. Do not include a title or any markdown formatting. The tone should be exciting and inviting.";

// 3. PREPARE THE API REQUEST TO OPENAI
$api_url = 'https://api.openai.com/v1/chat/completions';
$api_key = OPENAI_API_KEY;

$headers = [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $api_key
];

$body = [
    'model' => 'gpt-3.5-turbo', // A powerful and cost-effective model
    'messages' => [
        ['role' => 'user', 'content' => $prompt]
    ],
    'max_tokens' => 250, // Max length of the response
    'temperature' => 0.7 // Controls creativity (0.2=focused, 1.0=creative)
];

// 4. EXECUTE THE API CALL USING cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$api_response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if (curl_errno($ch)) {
    send_json_response(false, 'cURL Error: ' . curl_error($ch));
}
curl_close($ch);

// 5. PROCESS THE RESPONSE
$response_data = json_decode($api_response, true);

if ($http_code !== 200 || isset($response_data['error'])) {
    send_json_response(false, $response_data['error']['message'] ?? 'Failed to get a valid response from AI API.');
}

// Extract the generated text from the response
$generated_description = trim($response_data['choices'][0]['message']['content'] ?? '');

if (empty($generated_description)) {
    send_json_response(false, 'The AI returned an empty description. Try again.');
}

// 6. SEND THE SUCCESSFUL RESPONSE BACK TO THE FRONTEND
send_json_response(true, $generated_description);
?>
