<?php
// check_zip.php
require_once '../config/database.php';
require_once '../config/location_validator.php';
require_once '../includes/app_helpers.php';

header('Content-Type: application/json');

$response = ['serviceable' => false, 'message' => 'Invalid request'];

if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['zip_code'])) {
    try {
        $database = new Database();
        $db = $database->getConnection();
        $validator = new LocationValidator($db);
        
        $zip_code = trim($_POST['zip_code']);
        
        // Validate zip code format (5 digits)
        if(!preg_match('/^\d{5}$/', $zip_code)) {
            $response['message'] = 'Please enter a valid 5-digit ZIP code';
            echo json_encode($response);
            exit;
        }
        
        ensureAddressAndCallQueueTables($db);
        $result = $validator->getServiceableMessage($zip_code);
        $meta = getZipAddressMeta($db, $zip_code);
        if ($meta) {
            $result['city_id'] = $meta['city_id'];
            $result['city_name'] = $meta['city_name'];
            $result['city'] = $meta['city_name'];
            $result['service_region_name'] = $meta['service_region_name'] ?? $meta['region'];
            $result['state'] = $meta['state'];
            $result['region'] = $meta['region'];
            $result['location_id'] = $meta['location_id'];
            $result['location_name'] = $meta['location_name'];
        }
        echo json_encode($result);
        
    } catch(Exception $e) {
        $response['message'] = 'Error checking ZIP code: ' . $e->getMessage();
        echo json_encode($response);
    }
} else {
    echo json_encode($response);
}
?>