<?php

use PPLCZ\Model\Model\ParcelDataModel;
use PPLCZ\Model\Model\AdditionalDataModel;
use \PPLCZ\Model\Model\CartDataModel;
use PPLCZ\Model\Model\CartModel;
use PPLCZ\Serializer;

defined("WPINC") or die();

function pplcz_create_name($name)
{
    return "pplcz_" . $name;
}

function pplcz_map_args()
{
    return PPLCZ\Front\Components\Map\Map::args();
}

function pplcz_asset_icon($name)
{

    return plugins_url("src/Admin/Assets/Images/$name", realpath(__DIR__));
}

function pplcz_set_shipment_print($shipmentId, $print)
{
    set_transient(pplcz_create_name("print_shipment_{$shipmentId}"), $print, 60 * 60 * 48);
}

function pplcz_get_shipment_print($shipmentId)
{
    return get_transient(pplcz_create_name("print_shipment_{$shipmentId}"));
}

function pplcz_set_batch_print($batchId, $print)
{
    set_transient(pplcz_create_name("print_batch_{$batchId}"), $print, 60 * 60 * 48);
}

function pplcz_get_batch_print($batchId)
{
    return get_transient(pplcz_create_name("print_batch_{$batchId}"));
}

function pplcz_get_download_pdf($download, $shipment = null, $package = null, $print = null)
{
    return \PPLCZ\Admin\Page\FilePage::createUrl($download, $shipment, $package, $print);
}

function pplcz_normalize($value)
{
    return Serializer::getInstance()->normalize($value);
}

function pplcz_denormalize($value, $type, $context = [])
{
    return Serializer::getInstance()->denormalize($value, $type, null, $context);
}

function pplcz_validate($model, $errors = null, $path = "")
{
    if (!$errors)
        $errors = new WP_Error();
    \PPLCZ\Validator\Validator::getInstance()->validate($model, $errors, $path);
    return $errors;
}

function pplcz_get_parcel_countries()
{
    $countries_obj = new \WC_Countries();

    $get_countries = $countries_obj->get_allowed_countries();

    foreach ($get_countries as $key => $v) {
        $mapCountries = ['CZ', 'SK', 'PL', 'DE', 'NL', 'RO', 'BG', 'HU', 'AT'];
        if (!in_array($key, $mapCountries, true))
            unset($get_countries[$key]);
    }

    return $get_countries;
}

function pplcz_get_allowed_countries()
{
    $countries_obj = new \WC_Countries();

    $get_countries = $countries_obj->get_allowed_countries();
    $output = [];

    $countries = include __DIR__ . '/config/countries.php';
    foreach ($get_countries as $key => $v) {
        if (!isset($countries[$key]))
            unset($get_countries[$key]);
    }

    return $get_countries;
}

function pplcz_get_cod_currencies()
{
    $currencies = include __DIR__ . '/config/cod_currencies.php';
    return $currencies;
}


function pplcz_get_version()
{
    if (!function_exists('get_plugin_data')) {
        require_once(ABSPATH . 'wp-admin/includes/plugin.php');
    }
    $pluginData = get_plugin_data(__DIR__ . '/../ppl-cz.php');
    return $pluginData['Version'];
}

function pplcz_set_cart_cartdata(?CartDataModel $data)
{
    $session = wc()->session;
    $session->set(pplcz_create_name("parcelshop_data"), $data && $data->getParcelData() ? pplcz_normalize($data->getParcelData()) : null);
    $session->set(pplcz_create_name("additional_data"), $data && $data->getAdditionalData() ? pplcz_normalize($data->getAdditionalData()) : null);
}


/**
 * @return CartDataModel|null
 */
function pplcz_get_cart_cartdata()
{

    $rate = pplcz_get_cart_shipping_method();
    if (!$rate)
        return null;

    $session = wc()->session;

    $cartData = new \PPLCZ\Model\Model\CartDataModel();

    /**
     * @var CartModel $metadata
     */
    $metadata = pplcz_denormalize($rate->get_meta_data(), CartModel::class);
    if ($metadata->getParcelRequired()) {
        $parcelshop_data = $session->get(pplcz_create_name("parcelshop_data"));
        if ($parcelshop_data) {
            /**
             * @var ParcelDataModel $parcelshop_data
             */
            $parcelshop_data = pplcz_denormalize($parcelshop_data, ParcelDataModel::class);
            $cartData->setParcelData($parcelshop_data);
        }
    }

    $additionaldata = $session->get(pplcz_create_name("additional_data"));
    if ($additionaldata)
        $cartData->setAdditionalData(pplcz_denormalize($additionaldata, AdditionalDataModel::class));

    return $cartData;
}

/**
 * @return \WC_Shipping_Rate|null
 */
function pplcz_get_cart_shipping_method($shipmentid = null)
{
    $session = WC()->session;
    if (!$session)
        WC()->initialize_session();
    $session = WC()->session;
    $cart = WC()->cart;
    if (!$cart)
        WC()->initialize_cart();
    $cart = WC()->cart;

    $chosen_shipping_methods = $session->get('chosen_shipping_methods');
    if (!$chosen_shipping_methods)
        return null;


    $chosen_shipping_method = $chosen_shipping_methods[0];

    foreach ($chosen_shipping_methods as $key => $shipping_method) {
        $method = str_replace(pplcz_create_name(""), "", $chosen_shipping_method);
        $methods = \PPLCZ\Setting\MethodSetting::getMethods();

        $method = preg_replace("~:[0-9]+$~", "", $method);
        $method = array_filter($methods, function ($item) use ($method) {
            return $method === $item->getCode();
        });
        $method = reset($method);

        if ($method) {
            $shipping = WC()->session->get("shipping_for_package_{$key}");
            /**
             * @var \WC_Shipping_Rate $rate
             */
            $rate = null;
            if ($shipping && isset($shipping['rates']) && isset($shipping['rates'][$chosen_shipping_method]))
                $rate = $shipping["rates"][$chosen_shipping_method];

            if ($rate)
                return $rate;
            // problem se zasilkovnou, proste to bez diskuzi vycisti
            $cart->calculate_shipping();
            $shipping = WC()->session->get("shipping_for_package_{$key}");
            if ($shipping && isset($shipping["rates"]) && isset($shipping["rates"][$chosen_shipping_method]))
                $rate = $shipping["rates"][$chosen_shipping_method];
            return $rate;
        }
    }
    return null;
}

function pplcz_get_update_setting()
{
    return get_option(pplcz_create_name("update_setting")) ?: "";
}

function pplcz_set_update_setting()
{
    add_option(pplcz_create_name("update_setting"), "" . time(), null, "yes") || update_option(pplcz_create_name("update_setting"), "" . time(), "yes");
}


function pplcz_currency($params)
{
    foreach ($params as $key => $value) {
        $params[$key]['pplcz_currency'] = get_woocommerce_currency();
        $params[$key]['pplcz_version'] = pplcz_get_version();
        $params[$key]['pplcz_update_setting'] = pplcz_get_update_setting();
    }
    return $params;
}

function pplcz_tables($activate = false)
{
    $version = get_option(pplcz_create_name("version"));
    if ($version !== pplcz_get_version()) {
        if (!$version) {
            $phases = \PPLCZ\Setting\PhaseSetting::getPhases()->getPhases();
            foreach ($phases as $phase) {
                \PPLCZ\Setting\PhaseSetting::setPhase($phase->getCode(), true, null);
            }
            $globalSetting = new \PPLCZ\Model\Model\GlobalSettingModel();
            $globalSetting->setUseOrderNumberInPackages(true);
            $globalSetting->setUseOrderNumberInVariableSymbol(true);

        }

        require_once __DIR__ . '/installdb.php';
        pplcz_installdb();

        add_action("admin_init", function () use ($activate) {
            as_unschedule_action("woocommerceppl_refresh_shipments_cron");
            as_unschedule_action("woocommerceppl_refresh_setting_cron");

            as_unschedule_action(pplcz_create_name("refresh_shipments_cron"));
            as_unschedule_action(pplcz_create_name("refresh_setting_cron"));
            as_unschedule_action(pplcz_create_name("delete_logs"));

            as_unschedule_all_actions(pplcz_create_name("refresh_setting_cron"));
            as_unschedule_all_actions(pplcz_create_name("refresh_shipments_cron"));

            as_schedule_recurring_action(time(), 60 * 60 * 6, pplcz_create_name("refresh_shipments_cron"));
            as_schedule_recurring_action(time(), 60 * 60 * 24, pplcz_create_name("refresh_setting_cron"));
            as_schedule_recurring_action(time(), 60 * 60 * 24, pplcz_create_name("delete_logs"));

            if (!$activate)
                add_option(pplcz_create_name("version"), pplcz_get_version(), null, 'yes') || update_option(pplcz_create_name("version"), pplcz_get_version(), 'yes');

        });
    }


    $rules = get_option(pplcz_create_name("rules_version"));

    if ($rules !== pplcz_get_version() || $activate) {
        add_action("wp_loaded", function () use ($activate) {
            flush_rewrite_rules();
            if (!$activate) {
                add_option(pplcz_create_name("rules_version"), pplcz_get_version(), null, 'yes') || update_option(pplcz_create_name("rules_version"), pplcz_get_version(), 'yes');
            }
        });
    }

    if ($activate) {
        delete_option(pplcz_create_name("rules_version"));
        update_option(pplcz_create_name("version"), "1.0.0");
    }
}

function pplcz_woocommerce_loaded()
{
    if (!WC()->session)
        WC()->initialize_session();
}

function pplcz_simple_guid()
{
    $site_url = get_site_url();
    $timestamp = current_time('timestamp');

    $raw_string = $site_url . '-' . $timestamp;

    $hash = hash('sha256', $raw_string);
    $time = (new \DateTime())->format("YmdHis");
    $guid = sprintf('%s-%08s-%04s-%04s-%04s-%12s',
        substr($time, 2),
        substr($hash, 0, 8),
        substr($hash, 8, 4),
        substr($hash, 12, 4),
        substr($hash, 16, 4),
        substr($hash, 20, 12)
    );

    return $guid;
}


function pplcz_activate()
{
    pplcz_tables(true);
}

function pplcz_deactivate()
{
    as_unschedule_action(pplcz_create_name("refresh_shipments_cron"));
    as_unschedule_action(pplcz_create_name("refresh_setting_cron"));
    as_unschedule_action(pplcz_create_name("delete_logs"));
}


