<?php
use Mtc\Core\PaginationTemplate;
use Mtc\Shop\Category;
use Illuminate\Support\Facades\DB;

$path = '../../../';
require_once $path . 'core/includes/header.inc.php';
$page_meta['title'] = 'Manage Restricted Zones';

$errors = [];

if (empty($_REQUEST['id'])) {
    header('Location: /shop/admin/categories/manage.categories.php');
    exit();
}

$category = (new Category())->find($_REQUEST['id']);

if (filter_input(INPUT_POST, 'action') === 'update') {
    $category->restricted_zones()->delete();
    if (!empty($_REQUEST['zones'])) {
        foreach (array_keys($_REQUEST['zones']) as $zone) {
            $category->restricted_zones()->create([
                'zone' => $zone
            ]);
        }
    }
    header('Location: /shop/admin/categories/restricted.zones.php?id=' . $_REQUEST['id'] . '&message=' . urlencode('Restricted zones saved successfully!'));
    exit();
}

$message = filter_input(INPUT_GET, 'message');

$delivery_zones = \Mtc\Shop\DeliveryZone::query()->groupBy('zone')->pluck('zone');

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

<ul class="breadcrumbs el">
    <li><a href="/admin/">Home</a> /</li>
    <li><a href="/shop/admin/categories/manage.categories.php">Categories</a> /</li>
    <li>Restricted Zones</li>
</ul>

<h1>Restricted Zones</h1>

<?php
include __DIR__ . '/tabnav.php';

if (!empty($errors)) {
    showerrors($errors);
}
if (!empty($message)) {
    echo showmsg($message, 'success', $path);
}
?>

<form method="post">
    <table class="manage-items">
        <tr>
            <th nowrap="">Delivery zone</th>
            <th>Countries</th>
            <th>Restricted</th>
        </tr>
            <tbody class="tabular">
            <?php
            foreach ($delivery_zones as $delivery_zone) {
                $countries = implode(', ', \Mtc\Shop\DeliveryZone::query()->where('zone', $delivery_zone)->pluck('country_name')->toArray());
                $checked = $category->restricted_zones()->where('zone', $delivery_zone)->count() ? 'checked' : '';
                ?>
                <tr id="rorder-<?= $delivery_zone ?>">
                    <td><?= $delivery_zone; ?></td>
                    <td><label for="zone-<?= $delivery_zone; ?>"><?= $countries; ?></label></td>
                    <td><input type="checkbox" value="1" id="zone-<?= $delivery_zone; ?>" name="zones[<?= $delivery_zone; ?>]" <?= $checked; ?>></td>
                </tr>
                <?php
            }
            ?>
        </tbody>
    </table>
    <input type="submit" value="Save" />
    <input type="hidden" name="action" value="update">
</form>
<?php
require_once $path . 'core/admin/templates/adminfooter.html.php';
