<?php
$openai_api_key = "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"; // Replace with your OpenAI key

$user_query = trim($_POST['q'] ?? '');
if (empty($user_query)) {
    echo json_encode(['error' => 'Missing query.']);
    // exit;
}
else
{
    echo $user_query;
}

// === STEP 1: IP Rate Limiting ===
$ip = $_SERVER['REMOTE_ADDR'];
$limit = 100; // Max requests per IP
$log_file = __DIR__ . "/ip_limiter.json";

$ip_log = file_exists($log_file) ? json_decode(file_get_contents($log_file), true) : [];

$now = time();
$window = 24 * 60 * 60; // 24 hours

// Cleanup old entries
foreach ($ip_log as $ip_key => $record) {
    if ($now - $record['first_request'] > $window) {
        unset($ip_log[$ip_key]);
    }
}

// Check if IP has exceeded limit
if (isset($ip_log[$ip])) {
    if ($ip_log[$ip]['count'] >= $limit) {
        echo json_encode([
            'success' => false,
            'error' => "Request limit exceeded for your IP. Try again later."
        ]);
        exit;
    } else {
        $ip_log[$ip]['count'] += 1;
    }
} else {
    $ip_log[$ip] = ['count' => 1, 'first_request' => $now];
}

// Save updated log
file_put_contents($log_file, json_encode($ip_log));

// === STEP 2: Check preloaded queries
$preloaded = load_preloaded_queries();
$matched = match_preloaded_query($user_query, $preloaded);
if ($matched) {
    json_encode([
        'success' => true,
        'country' => $matched['country'],
        'product_name' => $matched['product_name'],
        'source' => 'preloaded'
    ]);
    exit;
}
if (!empty($user_query)) {
// === STEP 3: Call GPT if needed
$prompt = <<<EOT
Extract the country and product_name from this query:
"$user_query"

You are a strict JSON API. Respond ONLY with valid JSON like this
{
  "country": "...",
  "product_name": "..."
}
EOT;

$response = call_openai_chat($openai_api_key, $prompt);

$filters = json_decode($response, true);

//preg_match('/\{.*?\}/s', $response, $matches);
//$filters = json_decode($matches[0] ?? '', true);

//print_r($filters);

if (json_last_error() === JSON_ERROR_NONE && isset($filters['country'], $filters['product_name'])) {
    echo json_encode([
        'success' => true,
        'country' => $filters['country'],
        'product_name' => $filters['product_name'],
        'source' => 'chatgpt'
    ]);
} else {
    echo json_encode([
        'success' => false,
        'error' => 'Could not understand your search query.',
        'suggestions' => [
            "Steel pipe manufacturers in UAE",
            "Brass fitting exporters in India",
            "Pharmaceutical suppliers in Saudi Arabia",
            "Plastic packaging companies in Egypt",
            "Granite exporters from Turkey"
        ],
        'raw_ai_response' => $response
    ]);
    
}
}
// === Helper: Call ChatGPT ===
function call_openai_chat($api_key, $prompt) {
    $postData = [
        'model' => 'gpt-3.5-turbo',
        'messages' => [
            ['role' => 'system', 'content' => 'You extract structured data from user queries.'],
            ['role' => 'user', 'content' => $prompt]
        ],
        'temperature' => 0.2
    ];
    // print_r($postData);
    
    $ch = curl_init('https://api.openai.com/v1/chat/completions');
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        "Authorization: Bearer $api_key"
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);

    $data = json_decode($response, true);
    return $data['choices'][0]['message']['content'] ?? '';
}

// === Helper: Preloaded Queries ===
function load_preloaded_queries() {
    $file = __DIR__ . '/preloaded_queries.json';
    return file_exists($file) ? json_decode(file_get_contents($file), true) : [];
}
function match_preloaded_query($input, $preloaded) {
    foreach ($preloaded as $query => $data) {
        if (strcasecmp(trim($input), trim($query)) === 0) {
            return $data;
        }
    }
    return false;
}
?>
<!-- put this in pagefooter1.htm -->
<html>
<script type="text/javascript">
function smartSearch(query) {
    fetch('extract-filters.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'q=' + encodeURIComponent(query)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Redirect to your real search with extracted filters
            const url = `https://gulfyp.com/directory/search.php?country=${encodeURIComponent(data.country)}&q=${encodeURIComponent(data.product_name)}`;
            window.location.href = url;
        } else {
            alert("Could not understand search. Try again.");
            console.log(data);
        }
    });
}
const voiceBtn = document.getElementById('voiceBtn');
const searchInput = document.getElementById('q');

// Voice Recognition Setup
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
const recognition = new SpeechRecognition();
recognition.lang = 'en-US';
recognition.interimResults = false;
recognition.maxAlternatives = 1;

voiceBtn.onclick = () => {
    recognition.start();
};

recognition.onresult = function(event) {
    const transcript = event.results[0][0].transcript;
    searchInput.value = transcript;
    SmartSearch(transcript); // You can auto-submit or show suggestions
};

recognition.onerror = function(event) {
    alert('Voice search failed: ' + event.error);
};
</script>

<form name="searchtest" id="searchtest" method="post" action="">
    <input type="text" name ='q' id="q" value="" size="100">
    <br/>
    <button id="voiceBtn" onclick="return false;">🎤</button>
    <br/>
    <input type="submit" name ='SmartSearchsubmit' id="SmartSearchsubmit">
</form>
</html>