<?php
Use Mtc\Core\UkPostcode;
/**
 * Ajax postcode lookup script
 *
 * @author Martins Fridenbergs <martins.fridenbergs@mtcmedia.co.uk>
 */
$path = '../../';
if (!empty($_REQUEST['as_json'])) {
    header('Content-Type: application/json');
}
include_once($path . "core/includes/header.inc.php");
if (!empty($_REQUEST['postcode'])) {
    $postcode = new UkPostcode(strtoupper($_REQUEST['postcode']));
    if ($postcode->validates($postcode)) {
        // Only proceed with search if we have a valid postcode
        $address_list = UkPostcode::retrievePAFAddresses((string)$postcode);
        if (!empty($address_list)) {
            array_unshift($address_list, "Select Your Address");
        } else {
            $message = 'Your Postcode could not be found';
            $response_status = 'not_found';
            $failed = true;
        }
    } else {
        $response_status = 'invalid';
        $message = 'Please enter a valid postcode';
        $failed = true;
    }
} else {
    $response_status = 'invalid';
    $message = 'Please enter a valid postcode';
    $failed = true;
}

// Return results
if (!empty($address_list)) {
    if (!empty($_REQUEST['as_json'])) {
        echo json_encode([
            'status' => 'ok',
            'addresses' => $address_list
        ]);
    } else {
        foreach ($address_list as $address) {
            ?>
            <option value="<?= clean_page($address['display_name']) ?>">
                <?= clean_page($address['display_name']) ?>
            </option>
            <?php
        }
    }
} elseif (!empty($failed)) {
    if (!empty($_REQUEST['as_json'])) {
        echo json_encode([
            'status' => $response_status,
            'addresses' => [
                $message
            ]
        ]);
    } else {
        ?>
        <option value=""><?= $message ?></option>
        <?php
    }
}
