<?php
include_once('./_common.php');

if (!$is_member) {
    die(json_encode(['status' => 'error', 'msg' => '로그인이 필요합니다.']));
}

$ip_input = isset($_POST['ip']) ? trim($_POST['ip']) : '';

if (!$ip_input) {
    die(json_encode(['status' => 'error', 'msg' => 'IP address is empty.']));
}

// 1. Validate IP / Resolve Domain
$resolved_ip = gethostbyname($ip_input);

// Check validity
if (!filter_var($resolved_ip, FILTER_VALIDATE_IP)) {
    die(json_encode(['status' => 'error', 'msg' => 'Invalid IP or Domain.']));
}

// Check Private/Reserved
if (!filter_var($resolved_ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
    die(json_encode(['status' => 'error', 'msg' => 'Private/Reserved IP.']));
}

// 2. Query GeoIP
// Using the same query structure found in the project
$sql = "
    SELECT
        locations.country_name,
        locations.country_iso_code
    FROM
        geoip_city_blocks_ipv4 AS blocks
    JOIN
        geoip_city_locations AS locations
    ON
        blocks.geoname_id = locations.geoname_id
    WHERE
        INET6_ATON('{$resolved_ip}') BETWEEN blocks.start_ip AND blocks.end_ip
    LIMIT 1
";

$result = sql_query($sql);
$row = sql_fetch_array($result);

if ($row) {
    $country_code = strtolower($row['country_iso_code']);
    $country_name = $row['country_name'];
    
    echo json_encode([
        'status' => 'success',
        'country_code' => $country_code, // e.g., 'kr', 'us'
        'country_name' => $country_name,
        'ip' => $resolved_ip
    ]);
} else {
    echo json_encode([
        'status' => 'error', 
        'msg' => 'Country not found.'
    ]);
}
?>