82 lines
2.8 KiB
PHP
82 lines
2.8 KiB
PHP
<?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]);
|