<?php
/**
 * SET OUT ALL POSTAL ZONES IN AN ARRAY
 * THE CHECKOUT ALLOWS USE OF POSTCODE ZONES
 * SET WHETHER EACH ZONE REQUIRES POSTCODE OR COUNTRY VALIDATION
 * TO KEEP ALL SIMILAR I HAVE LEFT ZONES 1-200 FREE FOR COUNTRIES AND 20+ FOR POSTCODE ZONES
 *
 * POSTCODE ZONES CAN BE WRITTEN IN AN ARRAY AS FOLLOWS
 * $zone20 = array(
    'IV' => array(), THIS ALLOWS ALL INVERNESS POSTCODES TO BE USED!
    'HS' => array(),

    OR IF THERE IS A RANGE IN THE POSTCODES ADD A MULTI-DIMENSIONAL ARRAY WHICH ALLOWS YOU TO
    SET AN UPPER AND LOWER LIMIT FOR EACH SECTION

    'AB' => array(array(33, 38), array(44, 56)), //this allows AB33-AB38 and AB44-AB56

 * Single postcode zones are written like below
     'GY' => array(array(1, 1)) //this will only exclud GY1 postcodes!
 */


// Select all from delivery zones
use Mtc\Shop\DeliveryZone;
use Illuminate\Support\Facades\Cache;

// Cache postal zones data for 1 hour
$cachedData = Cache::remember('postal_zones_data', 3600, function () {
    $postal_zones = [];
    $zone_data = [];
    $zone = [];

    $deliveryZones = DeliveryZone::query()
        ->where('disable', 0)
        ->orderBy('zone')
        ->get();

    foreach ($deliveryZones as $deliveryZone) {
        $postal_zones[$deliveryZone->zone] = 'country';
        $zone_data[$deliveryZone->zone][] = $deliveryZone;
    }

    foreach($postal_zones as $zone_number => $zone_type) {
        $zone[$zone_number] = [];

        foreach($zone_data[$zone_number] as $zone_datum) {
            $zone[$zone_number][$zone_datum['country_code']] = $zone_datum['country_name'];
        }
    }

    return [
        'postal_zones' => $postal_zones,
        'zone' => $zone
    ];
});

// Extract cached data into global scope
$GLOBALS['postal_zones'] = $cachedData['postal_zones'];
$zone = $cachedData['zone'];
