<?php
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_DEPRECATED);
ob_start();
session_start();
if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') {
    die();
}
require_once("../../backend/functions.php");
require_once("../../db/connection.php");
$settings = get_settings();
$tripadvisor_api_key = $settings["tripadvisor_api_key"];
$location_id = $_POST['location_id'] ?? '';
$language = $_POST['language'] ?? 'en';
$id_marker = (int)$_POST['id_marker'];
if (empty($location_id)) {
    http_response_code(400);
    header('Content-Type: application/json');
    ob_end_clean();
    echo json_encode(['error' => _('Missing location id')]);
    exit;
}
$query = "SELECT tripadvisor_update_date, tripadvisor_rating, tripadvisor_reviews, tripadvisor_link 
          FROM sml_markers 
          WHERE id = $id_marker 
          LIMIT 1;";
$result = $mysqli->query($query);
if ($result && $row = $result->fetch_array(MYSQLI_ASSOC)) {
    $last_update = strtotime($row['tripadvisor_update_date']);
    $now = time();
    if ($now - $last_update < 86400) {
        header('Content-Type: application/json');
        ob_end_clean();
        echo json_encode([
            'rating' => $row['tripadvisor_rating'],
            'num_reviews' => $row['tripadvisor_reviews'],
            'web_url' => $row['tripadvisor_link'],
        ]);
        exit;
    }
}
$base_url = 'https://api.content.tripadvisor.com/api/v1/location/' . $location_id . '/details';
$params = [
    'key' => $tripadvisor_api_key,
    'language' => get_tripadvisor_language($language),
];
$api_url = $base_url . '?' . http_build_query($params);
$ch = curl_init($api_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($http_code === 200 && $response) {
    $data = json_decode($response, true);
    $rating = $data['rating'] ?? null;
    $reviews = $data['num_reviews'] ?? null;
    $link = $data['web_url'] ?? null;
    if ($rating !== null && $reviews !== null && $link !== null) {
        $now = date('Y-m-d H:i:s');
        $stmt = $mysqli->prepare("UPDATE sml_markers SET tripadvisor_rating=?, tripadvisor_reviews=?, tripadvisor_link=?, tripadvisor_update_date=? WHERE id=?");
        $stmt->bind_param("ddssi", $rating, $reviews, $link, $now, $id_marker);
        $stmt->execute();
        $stmt->close();
    }
    http_response_code($http_code);
    header('Content-Type: application/json');
    ob_end_clean();
    echo json_encode([
        'rating' => $rating,
        'num_reviews' => $reviews,
        'web_url' => $link,
    ]);
} else {
    http_response_code(400);
    header('Content-Type: application/json');
    ob_end_clean();
    echo json_encode(['error' => "Error"]);
}

function get_tripadvisor_language($language_code) {
    switch ($language_code) {
        case 'ar_SA':
            $mapped_code = 'ar';
            break;
        case 'da_DK':
            $mapped_code = 'da';
            break;
        case 'de_DE':
            $mapped_code = 'de';
            break;
        case 'el_GR':
            $mapped_code = 'el';
            break;
        case 'en_GB':
            $mapped_code = 'en_UK';
            break;
        case 'en_US':
            $mapped_code = 'en';
            break;
        case 'es_ES':
            $mapped_code = 'es';
            break;
        case 'es_MX':
            $mapped_code = 'es_MX';
            break;
        case 'fil_PH':
            $mapped_code = 'en_PH';
            break;
        case 'fr_FR':
            $mapped_code = 'fr';
            break;
        case 'he_IL':
            $mapped_code = 'iw';
            break;
        case 'id_ID':
            $mapped_code = 'in';
            break;
        case 'it_IT':
            $mapped_code = 'it';
            break;
        case 'ja_JP':
            $mapped_code = 'ja';
            break;
        case 'ko_KR':
            $mapped_code = 'ko';
            break;
        case 'nb_NO':
            $mapped_code = 'no';
            break;
        case 'nl_NL':
            $mapped_code = 'nl';
            break;
        case 'pt_BR':
            $mapped_code = 'pt';
            break;
        case 'pt_PT':
            $mapped_code = 'pt_PT';
            break;
        case 'ru_RU':
            $mapped_code = 'ru';
            break;
        case 'sv_SE':
            $mapped_code = 'sv';
            break;
        case 'th_TH':
            $mapped_code = 'th';
            break;
        case 'tr_TR':
            $mapped_code = 'tr';
            break;
        case 'vi_VN':
            $mapped_code = 'vi';
            break;
        case 'zh_CN':
            $mapped_code = 'zh';
            break;
        case 'zh_TW':
            $mapped_code = 'zh_TW';
            break;
        default:
            $mapped_code = 'en';
            break;
    }
    return $mapped_code;
}