<?php

use Mtc\Shop\DeliveryZone;

$path = '../../../';
require_once $path . 'core/includes/header.inc.php';

$page_meta['title'] = 'Manage Delivery Zones';

$errors = [];

if ($_REQUEST['action'] == 'update') {

    foreach ($_REQUEST['zone'] as $country => $zone) {

        if ($zone > 199) {
            $errors['zone'] = "Country zones cannot be over 200";
            continue;
        }

        if (!empty($zone)) {
            DeliveryZone::query()
                ->where('country_code', $country)
                ->update([
                    'zone' => $zone,
                ]);
        }

    }

    DeliveryZone::query()
        ->update([
            'disable' => false,
        ]);

    if (is_array($_REQUEST['disable_zone'])) {
        foreach ($_REQUEST['disable_zone'] as $country => $zone) {
            if ($zone == 'on') {
                DeliveryZone::query()
                    ->where('country_code', $country)
                    ->update([
                        'disable' => true,
                    ]);
            }
        }
    }

}

require_once $path . 'core/admin/templates/adminheader.html.php';
?>

    <ul class="breadcrumbs el">
        <li><a href="/admin/">Home</a> /</li>
        <li class="end">Manage Delivery Zones</li>
    </ul>

    <h1>Manage Delivery Zones</h1>

<?php

if (sizeof((array)$errors) > 0) {
    showerrors($errors);
}

if (sizeof((array)$errors) == 0 && isset($_REQUEST['action'])) {
    echo showmsg("Zones updated", "success", $path);
}

?>

<?php
$deliveryZones = DeliveryZone::query()
    ->orderBy('country_name')
    ->get();

if ($deliveryZones->count() > 0) {
    ?>

    <form method="post">

        <table class="manage-items">
            <tr>
                <th>Country Code</th>
                <th>Country Name</th>
                <th>Zone</th>
                <th>Disabled?</th>
            </tr>

            <?php
            foreach ($deliveryZones as $deliveryZone) {
                $data = $deliveryZone->toArray();
                ?>

                <tr>
                    <td><?= clean_page($data['country_code']); ?></td>
                    <td><?= clean_page($data['country_name']); ?></td>
                    <td><input type="text" name="zone[<?= $data['country_code']; ?>]"
                               value="<?= clean_page($data['zone']); ?>"/></td>
                    <td><input type="checkbox"
                               name="disable_zone[<?= $data['country_code']; ?>]" <?php if ($data['disable'] == true) { ?> checked<?php } ?> />
                    </td>
                </tr>

                <?php
            }
            ?>

        </table>


        <input type="hidden" name="action" value="update"/>
        <input type="submit" value="Save"/>

    </form>

    <?php
} else {
    ?>
    <p>There were no products found matching your search criteria</p>
    <?php
}
?>

<?php
require_once $path . 'core/admin/templates/adminfooter.html.php';
