<?php
/**
 * Plugin Name: PakMail
 * Description: An powerful plugin to rate multi-carrier shipment services and est. delivery dates during checkout, create shipment labels with one click and track.
 * Version: 1.12.8
 * Text Domain: pakmail-for-woocommerce.php
 * Domain Path: /lang/mo
 * License: GPL v3
 */

if (!defined('PAKMAIL_PLUGIN')) {
    define('PAKMAIL_PLUGIN', 'pakmail-for-woocommerce.php');
}

add_filter( 'wc_get_template', function ( $file, $name ) {
    if ( $name === 'order/order-details.php' ) {
        $file = __DIR__ . '/public/templates/order-details.php';
    }
    return $file;
}, 10, 2);

add_filter('wc_get_template', function ($file, $name) {
    if ($name === 'cart/cart-shipping.php') {
        $file = __DIR__ . '/public/templates/cart-shipping.php';
    }
    return $file;
}, 10, 2);

add_filter('plugin_row_meta', 'wk_plugin_row_meta', 10, 2);
function wk_plugin_row_meta($links, $file)
{
    if (plugin_basename(__FILE__) == $file) {
        $row_meta = array(
            'author_uri'        => '<a href="' . esc_url('https://212.api.pakmail.com.mx/') . ' "target="_blank" >' . esc_html__(EYHelper::getReplacingKeyi18n('{#brand_name#}', 'brand_name', 'author_uri'), 'domain') . '</a>',
            /*'plugin_uri'        => '<a href="'.esc_url( 'https://212.api.pakmail.com.mx/' ) .' "target="_blank" >' . esc_html__( EYHelper::i18n('plugin_uri'), 'domain' ) . '</a>',*/
	'documentation'     => '<a href="' . esc_url('https://212.api.pakmail.com.mx/contacto/') . ' "target="_blank" >' . esc_html__(EYHelper::i18n('documentation'), 'domain') . '</a>',
            'premium_support'   => '<a href="' . esc_url('https://212api.pakmail.com.mx/contacto/') . ' "target="_blank" >' . esc_html__(EYHelper::i18n('premium_support'), 'domain') . '</a>'
        );

        return array_merge($links, $row_meta);
    }
    return (array) $links;
}

add_action('admin_menu', 'register_my_custom_submenu_page', 60);
function register_my_custom_submenu_page()
{
    $brand_name = EYHelper::i18n('brand_name');

    add_submenu_page('woocommerce', $brand_name, $brand_name, 'manage_options', 'admin.php?page=wc-settings&amp;tab=shipping&amp;section=enviaya');
}

if (!function_exists('is_plugin_active')) {
    include_once(ABSPATH . 'wp-admin/includes/plugin.php');
}

if (is_plugin_active('woocommerce/woocommerce.php'))
{
    // check if accessed directly
    if (!defined('ABSPATH')) {
        exit;
    }

    // check if WooCommerce is active
    if (!in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
        exit;
    }

    // constant this file
    if (!defined('ENVIAYA_FILE')) {
        define('ENVIAYA_FILE', __FILE__);
    }

    if (!defined('ENVIAYA_API_LOGS_FOLDER')) {
        define('ENVIAYA_API_LOGS_FOLDER', WP_PLUGIN_DIR . '/enviaya-for-woocommerce/api-logs');
        if (!is_dir(ENVIAYA_API_LOGS_FOLDER)) {
            mkdir(ENVIAYA_API_LOGS_FOLDER);
        }
    }

    require_once __DIR__ . "/includes/enviaya.php";
    require_once __DIR__ . "/admin/helpers/hooks.php";
    require_once __DIR__ . "/admin/enviaya-for-woocommerce-admin.php";
    require_once __DIR__ . "/admin/ajax/ajax.php";
    require_once __DIR__ . "/includes/ajax.php";

    function my_enviaya_admin_style()
    {
        wp_register_style('ey-css', plugins_url('admin/css/enviaya.css', ENVIAYA_FILE));
        wp_enqueue_style('ey-css', plugins_url('admin/css/enviaya.css', ENVIAYA_FILE));
    }
    add_action('admin_head', 'my_enviaya_admin_style');

    // front-side ajax
    function enviaya_front_ajax()
    {
        wp_register_script('ey-ajax', plugins_url('public/js/ajax.js', ENVIAYA_FILE), array('jquery'), '1.14');
        wp_localize_script('ey-ajax', 'EnviayaAjax', array('ajaxurl' => admin_url('admin-ajax.php')));
        wp_enqueue_script('ey-ajax');
    }
    add_action('wp_enqueue_scripts', 'enviaya_front_ajax');

    //front-side css
    function enviaya_front_css()
    {
        wp_register_style('ey-css-public', plugins_url('public/css/enviaya.css', ENVIAYA_FILE));
        wp_enqueue_style('ey-css-public', plugins_url('public/css/enviaya.css', ENVIAYA_FILE));
    }
    add_action('wp_enqueue_scripts', 'enviaya_front_css');

    // hooks
    add_filter('plugin_action_links_' . plugin_basename(ENVIAYA_FILE), ['Enviaya', 'plugin_settings_link']);

    //intial shipping methods
    add_filter('woocommerce_shipping_methods',  ['Enviaya', 'shipping_methods']);

    add_filter('allowed_http_origins', 'add_allowed_enviaya_origins');

    function add_allowed_enviaya_origins($origins)
    {
        $origins[] = get_site_url();
        return $origins;
    }


    register_activation_hook( __FILE__, array( 'Enviaya', 'activate' ) );

    function my_enviaya_endpoints()
    {
        add_rewrite_endpoint('webhook', EP_ROOT | EP_PAGES);
    }

    add_action('init', 'my_enviaya_endpoints');

    function my_enviaya_func($args)
    {
        global $wpdb;

        if (isset($args['status'])) {
            if (strtoupper($args['status']) == "SUCCESS") {
                switch ($args['action']) {
                    case 'status_update':
                        try {
                            $wpdb->get_results("UPDATE {$wpdb->prefix}" . PREFIX . "_shipment SET
                                status = '{$args['shipment']['status']}',
                                carrier_shipment_number = '{$args['shipment']['carrier_shipment_number']}',
                                shipment_id = '{$args['shipment']['shipment_id']}',
                                event_code = '{$args['shipment']['event_code']}',
                                event_description = '{$args['shipment']['event_description']}',
                                event = '{$args['shipment']['event']}',
                                status_code = '{$args['shipment']['status_code']}',
                                sub_event_code = '{$args['shipment']['sub_event_code']}',
                                sub_event = '{$args['shipment']['sub_event']}',
                                sub_event_description = '{$args['shipment']['sub_event_description']}'
                                WHERE enviaya_shipment_number = '{$args['shipment']['shipment_number']}'");

                            print_r('{"status":200, "messages":"' . EYHelper::i18n('the_status_was_updated_successfully') . '"}');
                        } catch (Exception $e) {
                            echo EYHelper::i18n('exception'),  $e->getMessage(), "\n";
                        }
                        break;

                    case 'carrier_tracking_number_update':
                        try {

                            $wpdb->get_results("UPDATE {$wpdb->prefix}" . PREFIX . "_shipment SET
                                carrier_shipment_number = '{$args['shipment']['carrier_shipment_number']}'
                                WHERE enviaya_shipment_number = '{$args['shipment']['shipment_number']}'");

                            print_r('{"status":200, "messages":"' . EYHelper::i18n('tracking_number_successfuly_updated') . '"}');
                        } catch (Exception $e) {
                            echo EYHelper::i18n('exception'),  $e->getMessage(), "\n";
                        }
                        break;

                    case 'label_update':
                        try {
                            $wpdb->get_results("UPDATE {$wpdb->prefix}" . PREFIX . "_shipment SET
                                carrier_shipment_number = '{$args['shipment']['carrier_shipment_number']}',
                                label_url = '{$args['shipment']['label']}'
                                WHERE enviaya_shipment_number = '{$args['shipment']['shipment_number']}'");

                            print_r('{"status":200, "messages":"' . EYHelper::i18n('the_label_url_was_updated_successfully') . '"}');
                        } catch (Exception $e) {
                            echo EYHelper::i18n('exception'),  $e->getMessage(), "\n";
                        }
                        break;

                    case 'amounts_update':
                        try {
                            $wpdb->get_results("UPDATE {$wpdb->prefix}" . PREFIX . "_shipment SET
                                carrier_shipment_number = '{$args['shipment']['carrier_shipment_number']}',
                                total_amount = '{$args['shipment']['total_amount']}',
                                net_total_amount = '{$args['shipment']['net_total_amount']}',
                                vat_amount = '{$args['shipment']['vat_amount']}'
                                WHERE enviaya_shipment_number = '{$args['shipment']['shipment_number']}'");

                            print_r('{"status":200, "messages":"' . EYHelper::i18n('the_shipment_amount_was_updated_successfully') . '"}');
                        } catch (Exception $e) {
                            echo EYHelper::i18n('exception'),  $e->getMessage(), "\n";
                        }
                        break;

                    case 'destination_update':
                        try {
                            $states1 = $wpdb->get_results("SELECT order_id FROM {$wpdb->prefix}" . PREFIX . "_shipment
                                WHERE enviaya_shipment_number = '{$args['shipment']['shipment_number']}'");

                            $order_id = $states1[0]->order_id;

                            $wpdb->get_results("UPDATE {$wpdb->prefix}postmeta SET
                                meta_value = '{$args['shipment']['destination_company']}'
                                WHERE post_id = '{$order_id}' AND meta_key = '_billing_company'");


                            $wpdb->get_results("UPDATE {$wpdb->prefix}postmeta SET
                                meta_value = '{$args['shipment']['destination_phone']}'
                                WHERE post_id = '{$order_id}' AND meta_key = '_billing_phone'");

                            $qry2 = "UPDATE {$wpdb->prefix}postmeta SET
                                meta_value = '{$args['shipment']['destination_direction_1']}'
                                WHERE post_id = '{$order_id}' AND meta_key = '_billing_address_1'";
                            $states2 = $wpdb->get_results($qry2);

                            $wpdb->get_results("UPDATE {$wpdb->prefix}postmeta SET
                                meta_value = '{$args['shipment']['destination_direction_2']}'
                                WHERE post_id = '{$order_id}' AND meta_key = '_billing_address_2'");

                            $wpdb->get_results("UPDATE {$wpdb->prefix}postmeta SET
                                meta_value = '{$args['shipment']['destination_country_code']}'
                                WHERE post_id = '{$order_id}' AND meta_key = '_billing_country'");

                            $wpdb->get_results("UPDATE {$wpdb->prefix}postmeta SET
                                meta_value = '{$args['shipment']['destination_postal_code']}'
                                WHERE post_id = '{$order_id}' AND meta_key = '_billing_postcode'");

                            $wpdb->get_results("UPDATE {$wpdb->prefix}postmeta SET
                                meta_value = '{$args['shipment']['destination_city']}'
                                WHERE post_id = '{$order_id}' AND meta_key = '_billing_city'");

                            $wpdb->get_results("UPDATE {$wpdb->prefix}postmeta SET
                                meta_value = '{$args['shipment']['destination_state_code']}'
                                WHERE post_id = '{$order_id}' AND meta_key = '_billing_state'");

                            $full_name = $args['shipment']['destination_full_name'];
                            $arr = explode(" ", $full_name);

                            $wpdb->get_results("UPDATE {$wpdb->prefix}postmeta SET
                                meta_value = '{$arr[0]}'
                                WHERE post_id = '{$order_id}' AND meta_key = '_billing_first_name'");


                            $arr[0] = '';
                            $full_name = join(' ', $arr);

                            $wpdb->get_results("UPDATE {$wpdb->prefix}postmeta SET
                                meta_value = '{$full_name}'
                                WHERE post_id = '{$order_id}' AND meta_key = '_billing_last_name'");

                            $wpdb->get_results("UPDATE {$wpdb->prefix}postmeta SET
                                meta_value = '{$args['shipment']['destination_email']}'
                                WHERE post_id = '{$order_id}' AND meta_key = '_billing_email'");

                            print_r('{"status":200, "messages":"' . EYHelper::i18n('destination_address_successfuly_updated') . '"}');
                        } catch (Exception $e) {
                            echo EYHelper::i18n('exception'),  $e->getMessage(), "\n";
                        }
                        break;

                    case 'origin_update':
                        try {
                            $config1 = get_option('woocommerce_enviaya_settings');
                            $config = json_decode(str_replace('||', '"', $config1['origin_address']));

                            $config->country_code = $args['shipment']['origin_country_code'];
                            $config->state_code = $args['shipment']['origin_state_code'];
                            $config->postal_code = $args['shipment']['origin_postal_code'];
                            $config->city = $args['shipment']['origin_city'];
                            $config->neighborhood = $args['shipment']['origin_neighborhood'];
                            $config->direction_1 = $args['shipment']['origin_direction_1'];
                            $config->direction_2 = $args['shipment']['origin_direction_2'];
                            $config->full_name = $args['shipment']['origin_full_name'];
                            $config->company = $args['shipment']['origin_company'];
                            $config->phone = $args['shipment']['origin_phone'];
                            $config->email = $args['shipment']['origin_email'];

                            $config2 = str_replace('"', '||', json_encode($config));
                            $config1['origin_address'] = $config2;

                            update_option('woocommerce_enviaya_settings', $config1);

                            print_r('{"status":200, "messages":"' . EYHelper::i18n('the_origin_was_updated_successfully') . '"}');
                        } catch (Exception $e) {
                            echo EYHelper::i18n('exception'), $e->getMessage(), "\n";
                        }
                        break;

                    default:
                        print_r('{"status":400, "messages":"' . EYHelper::i18n('an_error_ocurred') . '"}');

                        break;
                }
            } else {
                echo EYHelper::i18n('unsuccessful');
            }
        }
    }

    //dokan
    function prefix_add_enviaya_tab($menu_items)
    {
        $menu_items['enviaya'] = [
            'title' => __('EnvíaYa'),
            'icon' => '<img src="/wp-content/plugins/enviaya-for-woocommerce/public/img/dokan_enviaya_menu.png" style="margin-right: 15px;width: 17px;height: 17px; float:left"></span>',
            'url' => dokan_get_navigation_url('settings/enviaya'),
            'pos' => 200,
            'permission' => 'dokan_view_store_settings_menu',
        ];
        return $menu_items;
    }

    add_filter('dokan_get_dashboard_settings_nav', 'prefix_add_enviaya_tab');


    function prefix_set_enviaya_tab_title($title, $tab)
    {
        if ('enviaya' === $tab) {
            $title = __('EnvíaYa');
        }
        return $title;
    }

    add_filter('dokan_dashboard_settings_heading_title', 'prefix_set_enviaya_tab_title', 10, 2);
    /**
     * Sets the help text for the 'About' settings tab.
     *
     * @param string $help_text
     * @param string $tab
     *
     * @return string Help text for tab with slug $tab
     */
    function prefix_set_enviaya_tab_help_text($help_text, $tab)
    {
        if ('enviaya' === $tab) {
            $help_text = EYHelper::i18n('personalize');
        }
        return $help_text;
    }

    //add_filter('dokan_dashboard_settings_helper_text', 'prefix_set_enviaya_tab_help_text', 10, 2);


    function setup_dokan_form()
    {
        $setup_form = [];

        $setup_form['use_enviaya'] = array(
            'title'       => EYHelper::i18n('use_enviaya'),
            'label'       => ' ',
            'type'        => 'checkbox',
            'name'        => 'dokan_enviaya_use',
            'description' => EYHelper::i18n('use_enviaya_help'),
            'desc_tip'    => true,

        );

        $setup_form['api_key_production'] = array(
            'title'       => EYHelper::i18n('api_key'),
            'type'        => 'text',
            'name'        => 'dokan_enviaya_api_key_production',
            'description' => EYHelper::i18n('api_key_help'),
            'default'     => '',
            'desc_tip'    => true,
        );

        $setup_form['api_key_test'] = array(
            'title'       => EYHelper::i18n('test_api_key'),
            'type'        => 'text',
            'name'        => 'dokan_enviaya_api_key_test',
            'description' => EYHelper::i18n('api_key_help'),
            'default'     => '',
            'desc_tip'    => true,
        );

        $setup_form['timeout'] = array(
            'title'        => EYHelper::i18n('timeout'),
            'type'         => 'text',
            'name'         => 'dokan_enviaya_timeout',
            'description'  => EYHelper::i18n('timeout_help'),
            'default'      => '30',
            'desc_tip'     => true,
        );

        $setup_form['enabled_test_mode'] = array(
            'title'        => EYHelper::i18n('enable_test_mode'),
            'label'        => ' ',
            'default'      => EYHelper::i18n('no'),
            'type'         => 'checkbox',
            'name'         => 'dokan_enviaya_enabled_test_mode',
            'description'  => EYHelper::i18n('test_mode_help'),
            'desc_tip'     => true,
        );

        $setup_form['enviaya_account'] = array(
            'title'       => EYHelper::i18n('account'),
            'type'        => 'select',
            'name'         => 'dokan_enviaya_account',
            'class'    => 'wc-enhanced-select',
            'css'      => 'min-width:300px;',
            'description' => '',
            'default'     => '',
            'desc_tip'    => true,
        );

        $setup_form['sender_address'] = array(
            'title'       => EYHelper::i18n('sender_address'),
            'type'        => 'select',
            'name'         => 'dokan_sender_address',
            'class'    => 'wc-enhanced-select',
            'css'      => 'min-width:300px;',
            'description' => '',
            'default'     => '',
            'desc_tip'    => true,
        );

        return $setup_form;
    }


    function prefix_output_help_tab_content($query_vars)
    {
        if (isset($query_vars['settings']) && 'enviaya' === $query_vars['settings']) {
            if (!current_user_can('dokan_view_store_settings_menu')) {
                dokan_get_template_part('global/dokan-error', '', [
                    'deleted' => false,
                    'message' => EYHelper::i18n('no_access_permissions')
                ]);
            } else {
                $vendor_id = get_current_user_id();
                $url = 'https://' . EYHelper::i18n('api_domain') . '/api/v1/get_accounts?api_key=';
                $value = [];
                foreach (setup_dokan_form() as $item) {
                    $value["{$item['name']}"] = get_user_meta($vendor_id, $item['name'], true);
                }

                $url_sender_address = 'https://' . EYHelper::i18n('api_domain') . '/api/v1/directions?api_key=';

                ?>

                <form method="post" id="settings-form" action="" class="dokan-form-horizontal">
                    <?php wp_nonce_field( 'dokan_enviaya_settings_nonce' ); ?>

                    <input type="hidden" name="enviaya_url" value="<?php echo $url; ?>">
                    <input type="hidden" name="enviaya_url_sender_address" value="<?php echo $url_sender_address; ?>">
                    <?php
                    foreach (setup_dokan_form() as $item) {
                        if ($item['type'] == 'checkbox') {
                            $checked = $value[$item['name']] == 1 ? 'checked' : '';
                            echo "<div class='dokan-form-group'>
                                    <label class='dokan-w3 dokan-control-label' for='{$item['name']}'>{$item['title']}</label>
                                    <div class='dokan-w5 dokan-text-left'>
                                        <div class='checkbox'>
                                            <label>
                                                <input type='hidden' name='{$item['name']}' value='0'>
                                                <input name='{$item['name']}' value='1' id='{$item['name']}' type='{$item['type']}' {$checked}>
                                            </label>
                                        </div>
                                    </div>
                                  </div>";
                        } elseif ($item['type'] == 'select') {
                            echo "<div class='dokan-form-group'>
                                    <label class='dokan-w3 dokan-control-label' for='{$item['name']}'>
                                        {$item['title']}
                                        <span class='dokan-tooltips-help tips' data-placement='bottom' data-original-title='{$item['description']}'>
                                            <i class='fa fa-question-circle'></i>
                                        </span>
                                    </label>
                                    <div class='dokan-w5'>
                                        <select name='{$item['name']}' id='{$item['name']}' class='dokan-form-control'></select>
                                    </div>
                                </div>";
                        } else {
                            echo "<div class='dokan-form-group'>
                                    <label class='dokan-w3 dokan-control-label' for='{$item['name']}'>
                                        {$item['title']}
                                        <span class='dokan-tooltips-help tips' data-placement='bottom' data-original-title='{$item['description']}'>
                                            <i class='fa fa-question-circle'></i>
                                        </span>
                                    </label>
                                    <div class='dokan-w5'>
                                        <input class='dokan-form-control' name='{$item['name']}' value='{$value[$item['name']]}' id='{$item['name']}' type='{$item['type']}'>
                                    </div>
                                </div>";
                        }
                    }
                    ?>

                    <div class="dokan-form-group">
                        <div class="dokan-w4 ajax_prev dokan-text-left" style="margin-left: 25%">
                            <input type="submit" name="dokan_update_enviaya_settings" class="dokan-btn dokan-btn-danger dokan-btn-theme" value="<?php esc_attr_e(EYHelper::i18n('update_settings')); ?>">
                        </div>
                    </div>
                </form>

                <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>

                <script>
                    $(document).ready(function() {

                        function getApiKey(){
                            var dokan_enviaya_api_key_production = $("input[name='dokan_enviaya_api_key_production']").val();
                            var dokan_enviaya_api_key_test = $("input[name='dokan_enviaya_api_key_test']").val();
                            var api_key = dokan_enviaya_api_key_test ? dokan_enviaya_api_key_test : dokan_enviaya_api_key_production;

                            return api_key;
                        }

                        function enviayaAccounts() {
                            var enviaya_url = $("input[name='enviaya_url']").val();


                            $.ajax({
                                url: enviaya_url + getApiKey(),
                                type: 'GET',
                                success: function(res) {
                                    var mySelect = $("#dokan_enviaya_account");
                                    var selectValues = $.makeArray(JSON.stringify(res['enviaya_accounts']));

                                    $.each(selectValues, function(index, value) {
                                        var account = $.parseJSON(value)[0].account
                                        var alias = $.parseJSON(value)[0].alias

                                        mySelect.empty();
                                        mySelect.append($('<option>', {
                                            value: account,
                                            text: alias
                                        }));
                                    });
                                },
                                error: function() {
                                    var mySelect = $("#dokan_enviaya_account");
                                    mySelect.empty();
                                }
                            });
                        };

                        function ajaxDirection() {
                            var enviaya_url = $("input[name='enviaya_url_sender_address']").val();

                            $.ajax({
                                url: enviaya_url + getApiKey(),
                                success: function (html) {
                                    $('#dokan_sender_address').empty();
                                    var json = '';
                                    html.directions.forEach(function (element) {
                                        element.id = element.id.toString();
                                        var em = new Object();
                                        em.full_name = element.full_name
                                        em.company = element.company
                                        em.phone = element.phone
                                        em.email = element.email
                                        em.direction_1 = element.direction_1
                                        em.direction_2 = element.direction_2
                                        em.neighborhood = element.neighborhood
                                        em.district = element.district
                                        em.postal_code = element.postal_code
                                        em.city = element.city
                                        em.state_code = element.state_code
                                        em.country_code = element.country_code
                                        json = JSON.stringify(em);
                                        json = json.normalize();
                                        json = toASCII(json);
                                        $('#dokan_sender_address').append('<option value=' + btoa(json) + '>' + element.full_name + '</option>');
                                    });
                                },
                                error: function () {
                                    $('#dokan_sender_address').empty();
                                }
                            });
                        }

                        function toASCII(string) {
                            var toFind = ['á', 'é', 'í', 'ó', 'ú', 'ñ', 'Á', 'É', 'Í', 'Ó', 'Ú', 'Ñ'];
                            var toRepl = ['a', 'e', 'i', 'o', 'u', 'n', 'A', 'E', 'I', 'O', 'U', 'N'];

                            for (var i = 0; i < toFind.length; i++) {
                                var arr = string.split(toFind[i]);
                                string = arr.join(toRepl[i]);
                            }

                            var arr = string.split('null');
                            string = arr.join('\"\"');
                            return string;
                        }

                        enviayaAccounts();
                        ajaxDirection();
                        $("input").keyup(function() {
                            enviayaAccounts();
                            ajaxDirection();
                        });
                    });


                </script>

                <style>
                    #settings-form p.help-block {
                        margin-bottom: 0;
                    }
                </style>
                <?php
            }
        }
    }

    add_action('dokan_render_settings_content', 'prefix_output_help_tab_content');

    /*
    function prefix_save_enviaya_settings($user_id)
    {
        // Bail if another settings tab is being saved
        foreach (setup_dokan_form() as $item) {
            update_user_meta($user_id, $item['name'], sanitize_text_field($_POST["{$item['name']}"]));
        }
    }

    add_action('dokan_store_profile_saved', 'prefix_save_enviaya_settings');
    */

    function prefix_save_about_settings() {
      $vendor_id   = dokan_get_current_user_id();
      $post_data = wp_unslash( $_POST );
      $nonce     = isset( $post_data['_wpnonce'] ) ? $post_data['_wpnonce'] : '';

      // Bail if another settings tab is being saved
      if ( ! wp_verify_nonce( $nonce, 'dokan_enviaya_settings_nonce' ) ) {
          return;
      }

      foreach (setup_dokan_form() as $item) {

        update_user_meta($vendor_id, $item['name'], sanitize_text_field($post_data["{$item['name']}"]));

      }

      wp_send_json_success( array(
        'msg' => __( 'Your information has been saved successfully' ),
      ) );



    }

    //Hooked with priority 5 to run before WeDevs\Dokan\Dashboard\Templates::ajax_settings()
    add_action( 'wp_ajax_dokan_settings', 'prefix_save_about_settings', 5 );

    add_filter('woocommerce_billing_fields', 'remove_enviaya_billing_phone_field', 20);
    function remove_enviaya_billing_phone_field($fields)
    {
        $fields['billing_phone']['required'] = true; // To be sure "NOT required"

        return $fields;
    }


    add_action('rest_api_init', function () {
        register_rest_route('enviaya/v1', '/webhook', array(
            'methods' => 'POST',
            'callback' => 'my_enviaya_func',
            'permission_callback' => '__return_true'
        ));
    });

    add_filter('woocommerce_cart_shipping_method_full_label', 'enviaya_shipping_service_design_advanced_label', 10, 2);
    function enviaya_shipping_service_design_advanced_label($label, $method)
    {

        $meta_data = $method->get_meta_data();
        $shipping_carrier_name = get_option('woocommerce_enviaya_settings')['shipping_carrier_name'];

        if (isset($meta_data['carrier_name'])) {
            if ($shipping_carrier_name === "1") {
                $label = $meta_data['carrier_name'] . " - " . $label;
            }
        }

        return $label;
    }

    add_filter( 'woocommerce_cart_totals_before_shipping', function() {
        if(is_cart())
        {
            $settings = EyHelper::settings();
            if(!empty($settings['title_rating_configuration']))
            {
                echo '<label>'.$settings['title_rating_configuration'].'</label>';
            }


        }//end
    });

    function setMessageCheckout() {
        if(is_checkout())
        {
            //
            if ( ! defined( 'ABSPATH' ) ) {
                exit;
            }//end

            //only run normal pages,
            if ( ! is_ajax() ) {
                $settings = EyHelper::settings();
                if(!empty($settings['title_rating_configuration']))
                {
                    echo '<label>'.$settings['title_rating_configuration'].'</label>';
                }//end
            }
        }//end
    }//end
    add_filter( 'woocommerce_review_order_after_cart_contents', "setMessageCheckout");

    //Add functionality for check if order is pay
    add_action('woocommerce_order_status_completed','insert_points', 10, 1);

    function insert_points($order_id)
    {
        global $wpdb;
        $order    = get_post();
        $settings = EYHelper::settings();

        if($settings["automatic_shipment_booking"] === "yes")
        {
            if (isset($settings['origin_address']->country_code) && isset($settings['origin_address']->postal_code))
            {
                $props = [
                    'get_post'              => isset($order)? $order : $order_id ,
                    'wc_get_order'          => wc_get_order(),
                    'auto_shipment_booking' => true
                ];
                //Snippet for build shipment
                $params_request = EYHelper::create_shipment($props);

                if(!$params_request)
                {
                    return false;
                }

                $result    = EYHelper::libAPI()->create($params_request);
                $response2 = $result['response'];

                /* error_log("NEW ORDER 1 REQUEST: " . json_encode($result['request']));
                error_log("NEW ORDER 1 RESPONSE: " . json_encode($response2)); */

                $states_rate = $wpdb->get_results(
                    "SELECT * FROM {$wpdb->prefix}" . PREFIX . "_rates WHERE order_id = {$order_id} AND
                        carrier_service_code = '{$result['request']['carrier_service_code']}' AND
                        carrier = '{$result['request']['carrier']}';"
                );

                $rate_id = $states_rate[0]->rate_id;
                $states0 = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}" . PREFIX . "_rates WHERE
                            order_id = {$order_id} AND rate_id = {$rate_id};");

                if (
                    isset($states0[0]) && isset($response2->enviaya_shipment_number)
                    && isset($response2->carrier_shipment_number)
                ) {
                    $wpdb->query("INSERT INTO {$wpdb->prefix}" . PREFIX . "_shipment (
                        rate_id, order_id, carrier, carrier_logo_url, estimated_delivery, carrier_service_name,
                        carrier_service_code, total_amount, net_total_amount, currency, enviaya_shipment_number,
                        carrier_shipment_number, label_url, shipment_status, webhook_status
                        ) VALUES (
                            '{$rate_id}', '{$order_id}', '{$states0[0]->carrier}', '{$states0[0]->carrier_logo_url}',
                            '{$states0[0]->estimated_delivery}', '{$states0[0]->carrier_service_name}',
                            '{$states0[0]->carrier_service_code}', '{$states0[0]->total_amount}',
                            '{$states0[0]->net_total_amount}', '{$states0[0]->currency}',
                            '{$response2->enviaya_shipment_number}', '{$response2->carrier_shipment_number}',
                            '{$response2->label_share_link}', 'Waiting', 'empty' )");
                }

                EYHelper::updateSetting("eya_notice_show", "yes");
                EYHelper::updateSetting("eya_notice_class", "notice-success");

                $success_message_existing = str_replace(
                        ['{#carrier_tracking_number#}', '{#carrier#}', '{#service_name#}', '{#label_share_link#}'],
                        [ $response2->carrier_shipment_number, $states0[0]->carrier, $states0[0]->carrier_service_name, $response2->label_share_link],
                        EYHelper::i18n('automatic_booking_success_message')
                    );

                EYHelper::updateSetting("eya_notice_message", $success_message_existing);
                EYHelper::updateSetting("eya_public_pdf_shipment", $response2->label_share_link);
            }//end if
        }//end if
    }//end function order complete

    function general_admin_notice(){
        global $pagenow;
        $settings = EYHelper::settings();
        $pages    = ["post.php"];

        if ( $settings["eya_notice_show"] === "yes" )
        {
            if(in_array( $pagenow, $pages )){
                /* notice-error; notice-success; notice-info; notice-warning  */
                echo '<div class="notice '.$settings["eya_notice_class"].' is-dismissible"><p>'.$settings["eya_notice_message"].'</p></div>';

                EYHelper::updateSetting("eya_notice_show", "no");
                EYHelper::updateSetting("eya_notice_class", "notice-info");
                EYHelper::updateSetting("eya_notice_message", "");
            }//end
        }//end
    }
    add_action('admin_notices', 'general_admin_notice' , 10, 0 );




} else {

    require_once __DIR__ . "/admin/helpers/EYHelper.php";

    printf('<div class="error"><p>' . EYHelper::getReplacingKeyi18n('{#brand_name#}', 'brand_name', 'woocommerce_disabled_message') . '</p></div>');
    deactivate_plugins('enviaya-for-woocommerce/enviaya-for-woocommerce.php');
}

/**
 * Write log into file if logging is enabled
 * @param string Message which will be written into the file
 * @param string type of log, different types writes into different files
 *
 * @return bool
 */

function logAPI ($message, $type){
    if(get_option('woocommerce_enviaya_settings')['enable_api_logging'] != 'yes'){
        return null;
    }

    $logger = wc_get_logger();
    $logger->info( $type. " => ". $message, array( 'source' => 'enviaya-rating-logger' ) );

    return true;
}

function log_it( $message ) {
   if( WP_DEBUG === true ){
     if( is_array( $message ) || is_object( $message ) ){
       //error_log will be located according to server configuration
       //you can specify a custom location if needed like this
       //error_log( $var, 0, "full-path-to/error_log.txt")
       error_log( print_r( $message, true ) );
     } else {
       error_log( $message );
     }
   }
}


?>
