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

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

if (!preg_match('/^\d{6}$/', $pincode)) {
    echo json_encode(['success' => false, 'message' => 'Enter a valid 6-digit pincode.']);
    exit;
}

$db = db();
$stmt = $db->prepare("SELECT * FROM pincodes WHERE pincode = ? AND is_active = 1");
$stmt->execute([$pincode]);
$row = $stmt->fetch();

if ($row) {
    echo json_encode([
        'success' => true,
        'pincode' => $row['pincode'],
        'city' => $row['city'],
        'state' => $row['state'],
        'cod_available' => (bool)$row['cod_available'],
        'delivery_days' => (int)$row['delivery_days'],
        'message' => 'Delivery available to ' . $row['city'] . ', ' . $row['state'] . ' in ' . $row['delivery_days'] . ' business days.'
    ]);
} else {
    echo json_encode(['success' => false, 'message' => 'Delivery is not available to this pincode.']);
}
