<?php
namespace Mtc\Plugins\DeliveryCouriers\Classes;

use Mtc\Core\Models\Country;

$path = '../../../';
require_once $path . 'core/includes/header.inc.php';
$page_meta['title'] = 'Delivery Couriers';
$services = false;

if (filter_input(INPUT_POST, 'action') === 'initialize') {
    try {
        Courier::initialize($_POST);
        $_SESSION['message'] = 'Client Initialized';
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit;
    } catch (\Exception $exception) {
        $messages = collect(json_decode($exception->getMessage(), true))
            ->map(function ($error) {
                return [
                    'type' => 'error',
                    'content' => is_array($error) ? reset($error) : $error
                ];
            });
    }
}

if (filter_input(INPUT_POST, 'action') === 'save') {
    Courier::saveCourierData($_POST);
    $_SESSION['message'] = 'Information Saved';
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

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

$test_notify_url = SITE_URL . '/plugins/DeliveryCouriers/webhook/';

$installed = defined('DELIVERY_SERVICES_TOKEN_TEST') && !empty(DELIVERY_SERVICES_TOKEN_TEST);

$site_couriers = DeliveryCourier::query()->get();

if ($installed) {
    //$couriers = Courier::getCourierServiceList();
    //$available_services = Courier::filterAvailableServices($couriers);
}


$twig->display('DeliveryCouriers/admin/index.twig', [
    'page_meta' => $page_meta,
    'test_notify_url' => $test_notify_url,
    'messages' => $messages,
    'installed' => $installed,
    //'services' => $available_services,
    //'couriers' => $couriers,
    'countries' => Country::getCountryList(),
    'location' => CourierCollectLocation::query()->first(),
    'site_couriers' => $site_couriers->keyBy('api_courier_id'),
    'supported_label_formats' => Courier::$supported_label_formats,
]);