<?php
require_once __DIR__ . '/../includes/functions.php';
header('Content-Type: application/json; charset=utf-8');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); echo json_encode(['ok'=>false]); exit; }
$raw = file_get_contents('php://input');
$data = json_decode($raw ?: '[]', true);
if (!is_array($data)) { $data = $_POST; }
$iso2 = strtoupper(trim((string)($data['country_code'] ?? $data['country'] ?? $data['iso2'] ?? '')));
$cityName = trim((string)($data['city'] ?? ''));
$stateName = trim((string)($data['region'] ?? $data['region_name'] ?? $data['state'] ?? ''));
$timezone = trim((string)($data['timezone'] ?? $data['time_zone'] ?? ''));
$lat = trim((string)($data['latitude'] ?? $data['lat'] ?? ''));
$lng = trim((string)($data['longitude'] ?? $data['lon'] ?? $data['lng'] ?? ''));
if (!preg_match('/^[A-Z]{2}$/', $iso2)) { echo json_encode(['ok'=>false,'message'=>'No country detected']); exit; }
$country = country_by_iso2($iso2);
if (!$country) { echo json_encode(['ok'=>false,'message'=>'Detected country is not enabled','iso2'=>$iso2]); exit; }
$state = null; $city = null;
if ($stateName !== '') {
    $slug = slugify($stateName);
    $state = one('SELECT * FROM mj_states WHERE country_id=? AND (slug=? OR name LIKE ?) AND is_active=1 ORDER BY id LIMIT 1', [(int)$country['id'], $slug, $stateName]);
}
if ($cityName !== '') {
    $slug = slugify($cityName);
    $params = [(int)$country['id'], $slug, $cityName];
    $sql = 'SELECT * FROM mj_cities WHERE country_id=? AND (slug=? OR name LIKE ?) AND is_active=1';
    if ($state) { $sql .= ' ORDER BY CASE WHEN state_id='.(int)$state['id'].' THEN 0 ELSE 1 END, id LIMIT 1'; }
    else { $sql .= ' ORDER BY id LIMIT 1'; }
    $city = one($sql, $params);
    if ($city && !$state && !empty($city['state_id'])) { $state = one('SELECT * FROM mj_states WHERE id=? LIMIT 1', [(int)$city['state_id']]); }
}
$expires = time() + 60*60*24*30;
$path = rtrim(mj_app_base(), '/');
$cookiePath = $path === '' ? '/' : $path . '/';
$set = function(string $name, string $value) use ($expires, $cookiePath) {
    setcookie($name, $value, ['expires'=>$expires, 'path'=>$cookiePath, 'samesite'=>'Lax']);
};
$set('mj_country_id', (string)(int)$country['id']);
$set('mj_country_iso2', (string)$country['iso2']);
$set('mj_country_name', (string)$country['name']);
$set('mj_state_id', $state ? (string)(int)$state['id'] : '0');
$set('mj_state_name', $stateName ?: ($state['name'] ?? ''));
$set('mj_city_id', $city ? (string)(int)$city['id'] : '0');
$set('mj_city_name', $cityName ?: ($city['name'] ?? ''));
$set('mj_timezone', $timezone ?: ($city['timezone'] ?? $state['timezone'] ?? $country['timezone_default'] ?? 'UTC'));
$set('mj_latitude', $lat);
$set('mj_longitude', $lng);
try {
    if (table_exists('mj_visitor_locations')) {
        q('INSERT INTO mj_visitor_locations(country_id,state_id,city_id,country_iso2,country_name,state_name,city_name,timezone,latitude,longitude,ip_address,user_agent,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,NOW())', [
            (int)$country['id'], $state ? (int)$state['id'] : null, $city ? (int)$city['id'] : null, $country['iso2'], $country['name'], $stateName ?: ($state['name'] ?? ''), $cityName ?: ($city['name'] ?? ''), $timezone ?: ($country['timezone_default'] ?? 'UTC'),
            is_numeric($lat) ? $lat : null, is_numeric($lng) ? $lng : null, $_SERVER['REMOTE_ADDR'] ?? '', substr((string)($_SERVER['HTTP_USER_AGENT'] ?? ''),0,255)
        ]);
    }
} catch (Throwable $e) {}
echo json_encode([
    'ok'=>true,
    'country_id'=>(int)$country['id'],
    'country_slug'=>$country['slug'],
    'country_name'=>$country['name'],
    'state_id'=>$state ? (int)$state['id'] : 0,
    'city_id'=>$city ? (int)$city['id'] : 0,
    'label'=>trim(implode(', ', array_filter([$cityName ?: ($city['name'] ?? ''), $stateName ?: ($state['name'] ?? ''), $country['name']]))),
    'url'=>country_path($country)
]);
