38975-vm/api/generate.php
2026-03-04 16:24:17 +00:00

82 lines
2.8 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';
header('Content-Type: application/json');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
exit;
}
$input = json_decode(file_get_contents('php://input'), true);
// 1. Generate Itinerary (Mock fallback if API keys are missing)
function getMockItinerary($input) {
return [
'days' => [
[
'day' => 1,
'items' => [
['place_name' => 'Göreme Açık Hava Müzesi', 'category' => 'History', 'estimated_duration_minutes' => 120, 'description' => 'Historical cave churches.'],
['place_name' => 'Paşabağları', 'category' => 'Nature', 'estimated_duration_minutes' => 90, 'description' => 'Fairy chimneys.']
]
]
]
];
}
// 2. Google Places Lookup (Cache Check)
function getPlaceDetails($pdo, $placeName) {
$normalized = strtolower(trim($placeName));
$stmt = $pdo->prepare("SELECT * FROM places_cache WHERE place_name_normalized = ?");
$stmt->execute([$normalized]);
$cached = $stmt->fetch(PDO::FETCH_ASSOC);
if ($cached) return $cached;
$apiKey = getenv('GOOGLE_MAPS_API_KEY');
if (!$apiKey) return null;
$url = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=" . urlencode($placeName . " Cappadocia") . "&key=" . $apiKey;
$response = json_decode(file_get_contents($url), true);
if (!empty($response['results'])) {
$r = $response['results'][0];
$data = [
'place_name_normalized' => $normalized,
'place_id' => $r['place_id'],
'name' => $r['name'],
'formatted_address' => $r['formatted_address'],
'lat' => $r['geometry']['location']['lat'],
'lng' => $r['geometry']['location']['lng'],
'rating' => $r['rating'] ?? 0,
'photo_reference' => $r['photos'][0]['photo_reference'] ?? null
];
$stmt = $pdo->prepare("INSERT INTO places_cache (place_name_normalized, place_id, name, formatted_address, lat, lng, rating, photo_reference) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->execute(array_values($data));
return $data;
}
return null;
}
// Logic: Attempt OpenAI, fallback to mock
$itinerary = getMockItinerary($input); // Simplified for now
// Enrich with Places
foreach ($itinerary['days'] as &$day) {
foreach ($day['items'] as &$item) {
$details = getPlaceDetails($pdo, $item['place_name']);
if ($details) {
$item['place_id'] = $details['place_id'];
$item['lat'] = $details['lat'];
$item['lng'] = $details['lng'];
}
}
}
echo json_encode(['success' => true, 'itinerary' => $itinerary]);