<?php
/**
 * Plugin Name: BestCityToLive City Brief Example
 * Description: A source-linked city card using server-side partner credentials.
 * Version: 1.0.0
 */
if (!defined('ABSPATH')) { exit; }

// Configure BCTL_GATEWAY_URL and BCTL_PARTNER_TOKEN in your server environment.
// Keep this file server-side. Do not put credentials in HTML or JavaScript.
add_shortcode('bestcity_city', function ($attributes) {
    $attributes = shortcode_atts(array('city' => 'calgary'), $attributes, 'bestcity_city');
    $slug = strtolower(trim($attributes['city']));
    if (!preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/', $slug)) { return ''; }
    $base = getenv('BCTL_GATEWAY_URL');
    $token = getenv('BCTL_PARTNER_TOKEN');
    $parsed = $base ? wp_parse_url($base) : false;
    if (!$parsed || ($parsed['scheme'] ?? '') !== 'https' || isset($parsed['user']) || isset($parsed['pass']) || isset($parsed['query']) || isset($parsed['fragment']) || !$token) { return ''; }
    $cache_key = 'bctl_city_' . md5($base . '|' . $slug);
    $city = get_transient($cache_key);
    if ($city === false) {
        $response = wp_safe_remote_get(untrailingslashit($base) . '/v1/cities/' . rawurlencode($slug), array(
            'timeout' => 10, 'redirection' => 0,
            'headers' => array('Authorization' => 'Bearer ' . $token, 'Accept' => 'application/json')
        ));
        if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) { return ''; }
        $city = json_decode(wp_remote_retrieve_body($response), true);
        if (!is_array($city) || ($city['kind'] ?? '') !== 'city' || ($city['slug'] ?? '') !== $slug) { return ''; }
        set_transient($cache_key, $city, 15 * MINUTE_IN_SECONDS);
    }
    $canonical = 'https://bestcitytolive.com/city/' . rawurlencode($slug);
    $name = esc_html($city['name'] ?? $slug);
    $summary = esc_html($city['editorial_guide']['dek'] ?? '');
    $reviewed = esc_html($city['citation']['reviewed_at'] ?? 'See source');
    return '<aside class="bestcity-city-brief"><h3>' . $name . '</h3><p>' . $summary . '</p><p><small>Guide reviewed ' . $reviewed . '</small></p><a href="' . esc_url($canonical) . '">Read the city dossier at BestCityToLive / AINT.app</a></aside>';
});
