<?php
/**
 * Country-by-Country OSM Property Seeder
 * 
 * Usage:
 *   Dry run:  ?page=tools-seed-osm-country&token=letmein-CHANGE-ME&country=TZ&dry=yes
 *   Live run: ?page=tools-seed-osm-country&token=letmein-CHANGE-ME&country=TZ&confirm=yes
 *   Resume:   ?page=tools-seed-osm-country&token=letmein-CHANGE-ME&country=TZ&offset=2&confirm=yes
 * 
 * Optional params:
 *   &min_pop=100000      only seed cities with population >= this
 *   &radius=25           search radius in km around each city center
 *   &per_city=50         max properties to insert per city
 *   &max_cities=100      cap the number of cities processed this run
 *   &offset=0            skip N cities (for resuming after a failure)
 *   &vendor=29           which vendor_id owns the imported rows
 */

if (!defined('APP_START')) { http_response_code(403); exit('Direct access denied'); }

$TOKEN = $_GET['token'] ?? '';
if ($TOKEN !== 'letmein-CHANGE-ME') { http_response_code(403); exit('Invalid token'); }

header('Content-Type: text/plain; charset=utf-8');
@set_time_limit(7200);
@ini_set('memory_limit', '512M');
ignore_user_abort(true);

$db = db();

// ============================================================
// PARAMS
// ============================================================
$COUNTRY_CODE   = strtoupper(trim($_GET['country'] ?? ''));
$MIN_POP        = max(10000, (int)($_GET['min_pop'] ?? 100000));
$RADIUS_KM      = max(5, min(50, (int)($_GET['radius'] ?? 25)));
$LIMIT_PER_CITY = max(5, min(100, (int)($_GET['per_city'] ?? 50)));
$MAX_CITIES     = max(1, min(500, (int)($_GET['max_cities'] ?? 100)));
$OFFSET         = max(0, (int)($_GET['offset'] ?? 0));
$VENDOR_ID      = (int)($_GET['vendor'] ?? 29);
$CONFIRM        = $_GET['confirm'] ?? '';
$DRY            = !empty($_GET['dry']);
$SLEEP_SECONDS  = max(2, min(30, (int)($_GET['sleep'] ?? 8)));

// ============================================================
// HEADER
// ============================================================
echo "═══════════════════════════════════════════════════════\n";
echo " COUNTRY-BY-COUNTRY OSM PROPERTY SEEDER\n";
echo "═══════════════════════════════════════════════════════\n";
echo " Country:        " . ($COUNTRY_CODE ?: '(missing — add &country=XX)') . "\n";
echo " Min pop:        " . number_format($MIN_POP) . "\n";
echo " Radius:         {$RADIUS_KM} km\n";
echo " Per city limit: {$LIMIT_PER_CITY}\n";
echo " Max cities:     {$MAX_CITIES}\n";
echo " Offset:         {$OFFSET}\n";
echo " Vendor:         {$VENDOR_ID}\n";
echo " Sleep between:  {$SLEEP_SECONDS} sec\n";
echo " Mode:           " . ($DRY ? 'DRY RUN' : 'LIVE INSERT') . "\n";
echo "═══════════════════════════════════════════════════════\n\n";

if ($COUNTRY_CODE === '') {
    exit("ERROR: Missing &country=XX (ISO 3166-1 alpha-2, e.g. TZ, KE, NG)\n");
}

// ============================================================
// LOAD CATEGORIES (map slug → id)
// ============================================================
$catMap = [];
try {
    $rows = $db->fetchAll("SELECT id, slug FROM categories WHERE is_active = 1");
    foreach ($rows as $r) $catMap[strtolower($r['slug'])] = (int)$r['id'];
} catch (Throwable $e) {
    exit("Failed to load categories: " . $e->getMessage() . "\n");
}

if (empty($catMap)) {
    exit("ERROR: No categories found. Add categories before importing.\n");
}

echo "Loaded " . count($catMap) . " categories\n";

// ============================================================
// OSM tourism → your category slug
// ============================================================
$tourismToCat = [
    'hotel'        => 'hotels',
    'resort'       => 'resorts',
    'guest_house'  => 'bed-breakfast',
    'hostel'       => 'hostels',
    'apartment'    => 'serviced-apartments',
    'camp_site'    => 'camps',
    'chalet'       => 'villas',
    'motel'        => 'hotels',
];

// Verify every mapped category exists
$missingCats = [];
foreach (array_unique(array_values($tourismToCat)) as $slug) {
    if (!isset($catMap[$slug])) $missingCats[] = $slug;
}
if (!empty($missingCats)) {
    echo "⚠ Missing categories (will fall back to 'hotels'): "
        . implode(', ', $missingCats) . "\n";
}
echo "\n";

// ============================================================
// FETCH CITIES FROM destinations
// ============================================================
try {
    $cities = $db->fetchAll(
        "SELECT id, name, country_code, country_name, parent_id, population,
                latitude, longitude
         FROM destinations
         WHERE type = 'city'
           AND is_active = 1
           AND country_code = ?
           AND population >= ?
           AND latitude IS NOT NULL
           AND longitude IS NOT NULL
         ORDER BY population DESC
         LIMIT {$MAX_CITIES} OFFSET {$OFFSET}",
        [$COUNTRY_CODE, $MIN_POP]
    );
} catch (Throwable $e) {
    exit("Failed to query cities: " . $e->getMessage() . "\n");
}

if (empty($cities)) {
    exit("No cities found for country $COUNTRY_CODE with pop >= $MIN_POP at offset $OFFSET.\n");
}

echo "Found " . count($cities) . " cities in $COUNTRY_CODE\n\n";

// ============================================================
// DRY RUN — show cities and exit
// ============================================================
if ($DRY) {
    echo "═══════════════════════════════════════════════════════\n";
    echo " CITIES THAT WILL BE PROCESSED\n";
    echo "═══════════════════════════════════════════════════════\n";
    foreach ($cities as $i => $c) {
        printf("  %3d. %-32s pop=%-12s (%9.4f, %9.4f)\n",
            $i + 1 + $OFFSET,
            mb_substr($c['name'], 0, 30),
            number_format((int)$c['population']),
            (float)$c['latitude'],
            (float)$c['longitude']
        );
    }
    echo "\n═══════════════════════════════════════════════════════\n";
    echo " DRY RUN COMPLETE\n";
    echo "═══════════════════════════════════════════════════════\n";
    echo " No data was written.\n";
    echo " To run for real, replace &dry=yes with &confirm=yes\n";
    exit;
}

if ($CONFIRM !== 'yes') {
    exit("Add &confirm=yes to run for real.\n");
}

// ============================================================
// RESOLVE COUNTRY_ID
// ============================================================
$countryId = null;
try {
    $row = $db->fetchOne(
        "SELECT id FROM destinations WHERE type='country' AND country_code = ? LIMIT 1",
        [$COUNTRY_CODE]
    );
    $countryId = $row ? (int)$row['id'] : null;
} catch (Throwable $e) {}

if (!$countryId) {
    exit("ERROR: Country $COUNTRY_CODE not found in destinations.\n");
}

echo "Country ID: $countryId\n";

// ============================================================
// INITIALIZE BATCH
// ============================================================
$batchTag = 'osm_' . strtolower($COUNTRY_CODE) . '_' . date('Ymd_His');
echo "Batch tag: $batchTag\n\n";
echo "═══════════════════════════════════════════════════════\n\n";

$stats = [
    'cities_processed' => 0,
    'cities_with_hits' => 0,
    'inserted'         => 0,
    'skipped'          => 0,
    'errors'           => 0,
    'overpass_fails'   => 0,
];

// ============================================================
// PREPARED INSERT (matches your exact schema)
// ============================================================
$insertSql = "INSERT INTO properties (
                vendor_id, category_id, country_id, city_id, destination_id,
                name, slug, property_type,
                address_line1, latitude, longitude,
                min_price_per_night, max_price_per_night,
                currency, base_currency, tax_rate, service_fee_rate,
                check_in_time, check_out_time,
                cancellation_policy, house_rules,
                amenities,
                is_active, status, star_rating,
                average_rating, total_reviews,
                claim_status, meta_keywords, created_at
              ) VALUES (
                ?, ?, ?, ?, ?,
                ?, ?, ?,
                ?, ?, ?,
                ?, ?,
                ?, ?, 12.00, 5.00,
                '14:00:00', '11:00:00',
                'Free cancellation up to 48 hours before check-in',
                'No smoking. Quiet hours 10pm-8am.',
                ?,
                1, 'published', ?,
                0.00, 0,
                'unclaimed', ?, NOW()
              )";

// ============================================================
// CITY LOOP
// ============================================================
foreach ($cities as $city) {
    $stats['cities_processed']++;

    $cityId      = (int)$city['id'];
    $cityName    = $city['name'];
    $cityLat     = (float)$city['latitude'];
    $cityLon     = (float)$city['longitude'];
    $cityPop     = (int)$city['population'];
    $cityCountry = $city['country_code'];

    printf("\n▶ [%d/%d] %s (%s, pop %s)\n",
        $stats['cities_processed'] + $OFFSET,
        count($cities) + $OFFSET,
        $cityName,
        $cityCountry,
        number_format($cityPop)
    );

    // ---- Query Overpass ----
    $radiusM = $RADIUS_KM * 1000;
    $overpassQuery = '[out:json][timeout:60];'
                   . '(nwr["tourism"~"hotel|guest_house|hostel|apartment|camp_site|chalet|motel"]'
                   . '(around:' . $radiusM . ',' . $cityLat . ',' . $cityLon . '););'
                   . 'out center tags;';

    $response = osm_fetch_overpass($overpassQuery, $cityName);

    if ($response === null) {
        echo "   ✗ All Overpass mirrors failed after retries\n";
        $stats['errors']++;
        $stats['overpass_fails']++;
        sleep(15);
        continue;
    }

    $data = json_decode($response, true);
    $elements = $data['elements'] ?? [];

    if (empty($elements)) {
        echo "   — no POIs found\n";
        sleep($SLEEP_SECONDS);
        continue;
    }

    // ---- Process elements ----
    $seen = [];
    $insertedThisCity = 0;
    $skippedThisCity  = 0;

    foreach ($elements as $el) {
        if ($insertedThisCity >= $LIMIT_PER_CITY) break;

        $tags = $el['tags'] ?? [];
        $name = trim($tags['name'] ?? '');
        if ($name === '') continue;

        $nameKey = strtolower($name);
        if (isset($seen[$nameKey])) continue;
        $seen[$nameKey] = true;

        // Coordinates
        $elLat = $el['lat'] ?? ($el['center']['lat'] ?? null);
        $elLon = $el['lon'] ?? ($el['center']['lon'] ?? null);
        if ($elLat === null || $elLon === null) continue;

        // Category mapping
        $tourism = strtolower($tags['tourism'] ?? 'hotel');
        $catSlug = $tourismToCat[$tourism] ?? 'hotels';
        $catId   = $catMap[$catSlug] ?? ($catMap['hotels'] ?? reset($catMap));

        // Slug (unique)
        $slug = slugify($name) . '-osm-' . $el['id'];

        // Skip if already imported
        try {
            $exists = $db->fetchOne("SELECT id FROM properties WHERE slug = ? LIMIT 1", [$slug]);
            if ($exists) {
                $skippedThisCity++;
                continue;
            }
        } catch (Throwable $e) {
            $stats['errors']++;
            continue;
        }

        // Address
        $addrStreet = trim($tags['addr:street'] ?? '');
        $addrNumber = trim($tags['addr:housenumber'] ?? '');
        $addr = trim($addrStreet . ' ' . $addrNumber);
        if ($addr === '') $addr = $cityName;

        // Star rating
        $stars = (int)($tags['stars'] ?? 0);
        if ($stars < 0 || $stars > 5) $stars = 0;

        // Price fallback by category
        $priceByType = [
            'resorts'             => 220.00,
            'luxury-villas'       => 350.00,
            'villas'              => 180.00,
            'beach-villas'        => 260.00,
            'boutique-hotels'     => 200.00,
            'wellness-resorts'    => 300.00,
            'beach-resorts'       => 240.00,
            'ski-resorts'         => 260.00,
            'hotels'              => 120.00,
            'city-hotels'         => 100.00,
            'business-hotels'     => 150.00,
            'airport-hotels'      => 110.00,
            'serviced-apartments' => 130.00,
            'lodges'              => 140.00,
            'eco-lodges'          => 160.00,
            'camps'               => 60.00,
            'hostels'             => 35.00,
            'bed-breakfast'       => 90.00,
        ];
        $basePrice = $priceByType[$catSlug] ?? 100.00;
        if ($stars > 0) $basePrice = max($basePrice, $stars * 45);
        $minPrice = round($basePrice, 2);
        $maxPrice = round($basePrice * 1.8, 2);

        // Amenities (empty JSON array — owners fill later)
        $amenitiesJson = json_encode([]);

        // ---- Insert ----
        try {
            $db->query($insertSql, [
                $VENDOR_ID,       // vendor_id
                $catId,           // category_id
                $countryId,       // country_id
                $cityId,          // city_id
                $cityId,          // destination_id
                $name,            // name
                $slug,            // slug
                $catSlug,         // property_type
                $addr,            // address_line1
                $elLat,           // latitude
                $elLon,           // longitude
                $minPrice,        // min_price_per_night
                $maxPrice,        // max_price_per_night
                'USD',            // currency
                'USD',            // base_currency
                $amenitiesJson,   // amenities
                $stars,           // star_rating
                $batchTag,        // meta_keywords
            ]);

            $insertedThisCity++;
            $stats['inserted']++;
        } catch (Throwable $e) {
            $stats['errors']++;
            if ($stats['errors'] <= 5) {
                echo "   ✗ insert failed for '$name': " . $e->getMessage() . "\n";
            }
        }
    }

    if ($insertedThisCity > 0) $stats['cities_with_hits']++;
    $stats['skipped'] += $skippedThisCity;

    echo "   ✓ inserted: $insertedThisCity | skipped: $skippedThisCity\n";

    // Progress heartbeat every 10 cities
    if ($stats['cities_processed'] % 10 === 0) {
        echo "\n   ⏱  Progress: {$stats['cities_processed']} cities, {$stats['inserted']} properties\n\n";
    }

    // Polite pause before next city
    sleep($SLEEP_SECONDS);
}

// ============================================================
// FINAL REPORT
// ============================================================
echo "\n═══════════════════════════════════════════════════════\n";
echo " DONE — $COUNTRY_CODE\n";
echo "═══════════════════════════════════════════════════════\n";
echo " Cities processed:      {$stats['cities_processed']}\n";
echo " Cities with hits:      {$stats['cities_with_hits']}\n";
echo " Properties inserted:   {$stats['inserted']}\n";
echo " Properties skipped:    {$stats['skipped']}\n";
echo " Overpass failures:     {$stats['overpass_fails']}\n";
echo " Other errors:          {$stats['errors']}\n";
echo "\n";
echo " Batch tag:             $batchTag\n";
echo "\n";
echo " ROLLBACK (undo this entire import):\n";
echo "   DELETE FROM properties WHERE meta_keywords = '$batchTag';\n";
echo "\n";
echo " SAMPLE:\n";
echo "   SELECT id, name, city_id, property_type, min_price_per_night\n";
echo "   FROM properties WHERE meta_keywords = '$batchTag' LIMIT 10;\n";
echo "═══════════════════════════════════════════════════════\n";


// ============================================================
// HELPER — Overpass fetcher with mirror rotation + backoff
// ============================================================
function osm_fetch_overpass($query, $cityName = '') {
    // Multiple mirrors — shuffled each call to spread load
    $mirrors = [
        'https://overpass.kumi.systems/api/interpreter',
        'https://overpass-api.de/api/interpreter',
        'https://overpass.openstreetmap.ru/api/interpreter',
    ];

    shuffle($mirrors);

    $maxAttempts = count($mirrors) * 2; // try each mirror twice

    for ($attempt = 0; $attempt < $maxAttempts; $attempt++) {
        $mirror = $mirrors[$attempt % count($mirrors)];

        $response = osm_curl_post(
            $mirror,
            'data=' . urlencode($query),
            'Revenda-OSM-Seeder/1.0 (contact: ' . (defined('SITE_URL') ? SITE_URL : 'example.com') . ')'
        );

        if ($response !== null) {
            return $response;
        }

        // Backoff: 5s, 10s, 20s, 30s...
        $waitTime = min(30, 5 * pow(2, intdiv($attempt, count($mirrors))));
        printf("      ⏳ Retry %d/%d after %ds...\n", $attempt + 1, $maxAttempts, $waitTime);
        sleep($waitTime);
    }

    return null;
}

function osm_curl_post($url, $body, $userAgent = 'Revenda/1.0') {
    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => $body,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 90,
            CURLOPT_CONNECTTIMEOUT => 15,
            CURLOPT_USERAGENT      => $userAgent,
            CURLOPT_SSL_VERIFYPEER => true,
        ]);
        $result = curl_exec($ch);
        $code   = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        // Success = HTTP 200 with a non-trivial body
        if ($code === 200 && $result && strlen($result) > 50) {
            return $result;
        }
        return null;
    }

    // Fallback if curl is not available
    $ctx = stream_context_create([
        'http' => [
            'method'  => 'POST',
            'header'  => "Content-Type: application/x-www-form-urlencoded\r\nUser-Agent: $userAgent\r\n",
            'content' => $body,
            'timeout' => 90,
        ]
    ]);
    $result = @file_get_contents($url, false, $ctx);
    if ($result && strlen($result) > 50) return $result;
    return null;
}