<?php
require_once '../includes/db.php';
header('Content-Type: application/json');

if (!isset($_SESSION['admin_logged_in'])) {
    echo json_encode([]);
    exit;
}

$term = $_GET['term'] ?? '';
$type = $_GET['type'] ?? 'location';

if (empty($term)) {
    echo json_encode([]);
    exit;
}

$like_term = $term . '%';
$results = [];
$sql = "";

switch ($type) {
    case 'tour_location':
        $sql = "SELECT DISTINCT location FROM tours WHERE location LIKE ? LIMIT 10";
        break;
    case 'hotel_location':
        $sql = "SELECT DISTINCT location FROM hotels WHERE location LIKE ? LIMIT 10";
        break;
    // Add more cases here in the future for other fields
}

if (!empty($sql)) {
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $like_term);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $results[] = $row[array_keys($row)[0]]; // Get the first column's value
    }
}

echo json_encode($results);
?>
