<?php

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

$page_meta['title'] = 'Manage Delivery Costs';
$messages = [];

// Sets messages based on sessions flash message
if (!empty($_SESSION['flash_message'])) {
    $flash_message = $_SESSION['flash_message'];
    unset($_SESSION['flash_message']);

    switch ($flash_message['type']) {
        case 'success':
            $message = $flash_message['message'];
            break;
        case 'error':
            $errors = $flash_message['message'];
            break;
    }
}


if (filter_input(INPUT_POST, 'action') === 'update') {
    // Collect all posted data and loop through them
    // key is method id, rates within
    collect($_REQUEST['rates'])
        ->each(function ($rates, $method_id): void {
            // update base cost and free delivery limit
            $method = DeliveryMethod::query()->find($method_id);
            $method->cost = (float)$_REQUEST['base_cost'][$method_id];
            $method->max = (int)$_REQUEST['max'][$method_id];
            $method->service_id = (int)$_REQUEST['service'][$method_id];
            $method->disable = (int)($_REQUEST['disable'][$method_id] ?? null);
            $method->save();

            // now loop through all rates of this method
            collect($rates)
                ->reject(function ($rate) {
                    return empty($rate['weight_min'])
                        && empty($rate['weight_max'])
                        && empty($rate['line_ost'])
                        && empty($rate['kg_cost']);
                })
                ->each(function ($rate_data, $id) use($method_id): void {
                    if (is_numeric($id)) {
                        $rate = \Mtc\Shop\DeliveryMethodRate::query()->find($id);
                    } else {
                        $rate = new \Mtc\Shop\DeliveryMethodRate();
                        $rate->method_id = $method_id;
                    }

                    if (!empty($rate_data['line_cost'])) {
                        unset($rate_data['kg_cost']);
                    } else {
                        unset($rate_data['line_cost']);
                    }
                    if (empty($rate_data['remove'])) {
                        $rate->fill($rate_data);
                        $rate->save();
                    } else {
                        $rate->delete();
                    }
                });

        });

    $_SESSION['message'] = 'Delivery methods updated';
    header('Location: ' . \Util::add_query_arg([]));
    exit();
}

//set messages
if (!empty($_SESSION['message'])) {
    $messages[] = [
        'content' => $_SESSION['message'],
        'type' => 'success'
    ];
    unset($_SESSION['message']);
}

  //Delete The Delivery
if (!empty(filter_input(INPUT_GET, 'action')) && filter_input(INPUT_GET, 'action') == 'delete' && is_numeric(filter_input(INPUT_GET, 'delete_id')) && ADMIN_DELETE_DELIVERY_METHODS == true) {
    $delivery_method = DeliveryMethod::find(filter_input(INPUT_GET, 'delete_id'));
    $delivery_method->delete();
    header('Location: manage.delivery.php');
    exit;
}

$rates = DeliveryMethod::query()
    ->with('rates')
    ->orderBy('order')
    ->get();

$zones = $rates->groupBy('zone')
    ->keyBy(function ($by_zone, $zone_id) {

        return \Mtc\Shop\DeliveryZone::query()
            ->where('zone', $zone_id)
            ->pluck('country_code')
            ->implode(', ');
    });


$twig->display('shop/admin/delivery/rates.twig', [
    'self' => $_SERVER['PHP_SELF'],
    'messages' => $messages,
    'zones' => $zones,
    'services' => \Mtc\Shop\DeliveryServicesOption::all(),
]);
