<?php
require_once __DIR__ . '/../functions.php';
header('Content-Type: application/json');

$pincode = trim($_GET['pincode'] ?? '');

if (!preg_match('/^\d{6}$/', $pincode)) {
    echo json_encode(['success' => false, 'message' => 'Invalid pincode']);
    exit;
}

$url = 'https://api.postalpincode.in/pincode/' . $pincode;
$ctx = stream_context_create(['http' => ['timeout' => 10]]);
$response = @file_get_contents($url, false, $ctx);

if ($response === false) {
    echo json_encode(['success' => false, 'message' => 'Could not fetch pincode data']);
    exit;
}

$data = json_decode($response, true);

if (!empty($data[0]['Status'] === 'Success') && !empty($data[0]['PostOffice'])) {
    $po = $data[0]['PostOffice'][0];
    echo json_encode([
        'success' => true,
        'city' => $po['District'] ?? '',
        'state' => $po['State'] ?? '',
        'country' => $po['Country'] ?? 'India',
    ]);
} else {
    echo json_encode(['success' => false, 'message' => 'Pincode not found']);
}
