<?php

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}

show_admin_bar(false);

function salesloo_encrypt($string, $length = 16)
{
    $secret_key = AUTH_KEY;
    $secret_iv = AUTH_SALT;

    $encrypt_method = "AES-256-CBC";
    $key = hash('sha256', $secret_key);
    $iv = substr(hash('sha256', $secret_iv), 0, $length);

    return base64_encode(openssl_encrypt($string, $encrypt_method, $key, 0, $iv));
}
function salesloo_decrypt($string, $length = 16)
{
    $secret_key = AUTH_KEY;
    $secret_iv = AUTH_SALT;

    $encrypt_method = "AES-256-CBC";
    $key = hash('sha256', $secret_key);
    $iv = substr(hash('sha256', $secret_iv), 0, $length);

    return openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
}

/**
 * get salesloo global data
 *
 * @param  string $key
 * @return mixed
 */
function salesloo_data($key = false)
{
    global $salesloo_data;

    if (isset($salesloo_data[$key])) {
        return $salesloo_data[$key];
    }

    if (false === $key) {
        return $salesloo_data;
    }

    return false;
}

/**
 * get salesloo global data
 *
 * @param  string $key
 * @return mixed
 */
function ___salesloo($key = false)
{
    global $___salesloo;

    if (isset($___salesloo[$key])) {
        return $___salesloo[$key];
    }

    if (false === $key) {
        return $___salesloo;
    }

    return false;
}

/**
 * check if current page is salesloo page
 *
 * @return mixed
 */
function __is_salesloo_page()
{
    global $wp;

    if (isset($wp->query_vars['__salesloo_page'])) {
        return sanitize_text_field($wp->query_vars['__salesloo_page']);
    }

    return false;
}


/**
 * get salesloo url variable
 *
 * @param  string $key
 * @return mixed
 */
function salesloo_vars($key = false)
{
    global $wp;

    if (false === $key) {
        return $wp->query_vars;
    }

    if (isset($wp->query_vars[$key]))
        return sanitize_text_field($wp->query_vars[$key]);

    return false;
}


function salesloo_url_dashboard()
{
    $url = site_url() . '/dashboard/';

    return esc_url($url);
}
function salesloo_url_profile($page = false)
{
    $url = site_url() . '/profile/' . $page;

    return esc_url($url);
}
function salesloo_url_affiliate($page = false)
{
    $url = site_url()  . '/affiliate/' . $page;

    return $url;
}

function salesloo_url_transaction($page = false)
{
    $url = site_url() . '/transaction/' . $page;

    return esc_url($url);
}

/**
 * url access
 *
 * @param  string $page
 * @return string
 */
function salesloo_url_access($page = false)
{
    _deprecated_function(__FUNCTION__, '0.8.3', 'salesloo_url_dashboard');

    $url = site_url() . '/dashboard/' . $page;

    return esc_url($url);
}

function salesloo_url_order($order_id = false)
{

    $url = site_url() . '/order/' . $order_id;

    return esc_url($url);
}

function salesloo_url_product($page = false)
{
    $url = site_url() . '/product/' . $page;

    return esc_url($url);
}

function salesloo_url_login($redirect = false)
{
    $url = site_url() . '/' . salesloo_get_option('login_slug') . '/';

    if ($redirect) {
        $url = add_query_arg('redirect', sanitize_text_field($redirect), $url);
    }

    return esc_url($url);
}

function salesloo_url_register()
{
    $site = site_url();

    return esc_url($site . '/' . salesloo_get_option('register_slug') . '/');
}

function salesloo_url_checkout($param = '')
{
    $url = site_url() . '/checkout/' . $param;

    return esc_url($url);
}

function salesloo_url_renew($param = '')
{
    $url = site_url() . '/renew/' . $param;

    return esc_url($url);
}

function salesloo_url_payment($param)
{
    $url = site_url() . '/payment/' . $param;

    return esc_url($url);
}

function salesloo_url_thanks($param = false)
{
    $site = site_url() . '/thanks/' . $param;

    return $site;
}


function salesloo_navigation()
{
    $menu = [
        'dashboard' => [
            'title' => __('Dashboard', 'salesloo'),
            'icon'  => '<svg class="w-4 h-4 m-auto" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
                              stroke         = "currentColor">
                        <path stroke-linecap = "round" stroke-linejoin = "round" stroke-width = "2"
                              d              = "M4 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2V6zM14 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V6zM4 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2zM14 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z" />
                    </svg>',
            'permalink' => salesloo_url_dashboard(),
            'position'  => 0
        ],
        'products' => [
            'title' => __('Products', 'salesloo'),
            'icon'  => '<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 m-auto" fill="none" viewBox="0 0 24 24" stroke="currentColor">
  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z" />
</svg>',
            'permalink' => salesloo_url_product(),
            'position'  => 20
        ],
        'affiliate' => [
            'title' => __('Affiliate', 'salesloo'),
            'icon'  => '<svg class="w-4 h-4 m-auto" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
  <path stroke-linecap = "round" stroke-linejoin = "round" stroke-width = "2" d = "M11 5.882V19.24a1.76 1.76 0 01-3.417.592l-2.147-6.15M18 13a3 3 0 100-6M5.436 13.683A4.001 4.001 0 017 6h1.832c4.1 0 7.625-1.234 9.168-3v14c-1.543-1.766-5.067-3-9.168-3H7a3.988 3.988 0 01-1.564-.317z" />
</svg>',
            'permalink' => '#',
            'position'  => 40,
            'submenu'   => [
                'affiliate/product' => [
                    'title'     => __('Product', 'salesloo'),
                    'permalink' => salesloo_url_affiliate('product/'),
                ],
                'affiliate/statistic' => [
                    'title'     => __('Statistics', 'salesloo'),
                    'permalink' => salesloo_url_affiliate('statistics/'),
                ],
                'affiliate/commission' => [
                    'title'     => __('Commissions', 'salesloo'),
                    'permalink' => salesloo_url_affiliate('commission/'),
                ],
                'affiliate/withdrawal' => [
                    'title'     => __('Withdrawal', 'salesloo'),
                    'permalink' => salesloo_url_affiliate('withdrawal/'),
                ]
            ]
        ],
        'transaction' => [
            'title' => __('Transactions', 'salesloo'),
            'icon'  => '<svg class="w-4 h-4 m-auto" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
  <path stroke-linecap = "round" stroke-linejoin = "round" stroke-width = "2" d = "M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4" />
</svg>',
            'permalink' => salesloo_url_dashboard(),
            'position'  => 60,
            'submenu'   => [
                'transaction/order' => [
                    'title'     => __('Purchase', 'salesloo'),
                    'permalink' => salesloo_url_transaction('order/'),
                ],
                'transaction/invoice' => [
                    'title'     => __('Invoice', 'salesloo'),
                    'permalink' => salesloo_url_transaction('invoice/'),
                ]
            ]
        ]
    ];

    $menu = apply_filters('salesloo/navigation/menu', $menu);

    $shorted_menu = [];

    foreach ((array) $menu as $key => $m) {

        if (!isset($m['title']) || !isset($m['permalink'])) continue;

        $position = isset($m['position']) ? intval($m['position']) : 88;

        if (isset($shorted_menu["$position"])) {
            $position = $position + substr(base_convert(md5($key . $m['title']), 16, 10), -5) * 0.00001;
        }
        $shorted_menu["$position"] = $m;
    }


    /**
     * short array by position
     */
    ksort($shorted_menu, SORT_NUMERIC);

    return $shorted_menu;
}


function salesloo_convert_money($number, $currency_symbol = false)
{
    $number = floatval($number);

    $number_of_decimal = intval(salesloo_get_option('number_of_decimal'));
    $decimal_sparator  = salesloo_get_option('decimal_separator');
    $thousand_sparator = salesloo_get_option('thousand_separator');

    $money = number_format($number, $number_of_decimal, $decimal_sparator, $thousand_sparator);

    if (false == $currency_symbol) {
        $currency_symbol = salesloo_get_option('currency_symbol');
    }
    $currency_position = salesloo_get_option('currency_position');

    if ('left' == $currency_position) {
        $money = $currency_symbol . ' ' . $money;
    } else {
        $money = $money . ' ' . $currency_symbol;
    }

    return apply_filters('salesloo/convert/money', $money, $number);
}

function salesloo_convert_price($price)
{
    $converted_price = floatval($price);

    if (intval(salesloo_get_option('number_of_decimal')) == 0) {
        $converted_price = round($converted_price);
    }

    return apply_filters('salesloo/convert/price', $converted_price, $price);
}


function salesloo_current_query_args($args = array())
{
    $current_args = $_GET;

    unset($current_args['q']);

    $args = wp_parse_args($args, $current_args);

    return add_query_arg($args, '');
}


/**
 * get current salesloo url
 */
function salesloo_current_url()
{
    global $wp;
    return site_url('/' . $wp->request . '/');
}


function salesloo_get_payment_methods($class_name = false)
{

    _deprecated_function(__FUNCTION__, '1.0.0', 'Checkout::payment_methods');

    $array_classes = [
        'Salesloo\Payment_Method\Bacs',
        'Salesloo\Payment_Method\Paypal'
    ];

    $array_classes = apply_filters('salesloo/payment_method/classes', $array_classes);

    $classes = [];
    foreach ($array_classes as $class) {

        $class = new $class;
        if (empty($class->get_id())) continue;

        $classes[$class->get_id()] = $class;
    }

    if (false === $class_name) {
        return $classes;
    }

    if (!isset($classes[$class_name])) {
        list($method_class) = array_values($classes);
        return $method_class;
    }

    return $classes[$class_name];
}

function salesloo_currencies()
{
    $currencies = [
        'IDR' => __('Indonesian Rupiah (IDR)', 'salesloo'),
        'USD' => __('US Dollar (USD)', 'salesloo'),
        'GBP' => __('UK Pound (GBP)', 'salesloo'),
        'MYR' => __('Malaysian Ringgit (MYR)', 'salesloo'),
        'THB' => __('Thai Bath (THB)', 'salesloo'),
        'INR' => __('Indian Rupee (INR)', 'salesloo'),
    ];

    return (array) apply_filters('salesloo/currencies', $currencies);
}

// function salesloo_currencies_symbols()
// {
//     $currencies = [
//         'Rp' => __('Indonesian Rupiah (Rp)', 'salesloo'),
//         '$'  => __('US Dollar ($)', 'salesloo'),
//         '£'  => __('UK Pound (£)', 'salesloo'),
//         'RM' => __('Malaysian Ringgit (RM)', 'salesloo'),
//         '฿'  => __('Thai Bath (฿)', 'salesloo'),
//         '₹'  => __('Indian Rupee (₹)', 'salesloo'),
//     ];

//     return $currencies;
// }


function salesloo_generate_unique_number()
{
    if (!salesloo_get_option('unique_number')) return false;

    $max     = intval(salesloo_get_option('unique_number_max'));
    $current = get_option('salesloo_current_unique_number');

    if ($current) {
        $current_max = intval($current);
        $max = $current_max > 2 ? $current_max : $max;
    }

    $unique = $max - 1;
    update_option(
        'salesloo_current_unique_number',
        $unique
    );

    return $unique;
}

/**
 * create nonce
 */
function salesloo_create_nonce()
{
    $nonce = salesloo_encrypt(strtotime('now'));

    return sanitize_text_field($nonce);
}

/**
 * salesloo nonce field
 */
function salesloo_nonce_field($name, $echo = true)
{
    $field = '<input type="hidden" name="' . $name . '" value="' . salesloo_create_nonce() . '">';

    if (false === $echo) return $field;

    echo $field;
}

/**
 * verify nonce
 */
function salesloo_verify_nonce($nonce)
{
    if (!isset($_COOKIE['wp_salesloo'])) return false;

    $cookie = salesloo_decrypt(sanitize_text_field($_COOKIE['wp_salesloo']));
    $nonce  = salesloo_decrypt(sanitize_text_field($nonce));
    $args   = json_decode($cookie, true);

    if (\Salesloo\Libraries\User_Info::get_ip() != $args['ip']) return false;

    if (strtotime('- 6 hours') > $nonce) return false;

    return true;
}

function salesloo_welcome()
{
    date_default_timezone_set(get_option('timezone_string', 'Asia/Jakarta'));
    $say = '';

    if (date('H') < 12) {
        $say = __('Good morning', 'salesloo');
    } elseif (date('H') > 11 && date('H') < 18) {
        $say = __('Good afternoon', 'salesloo');
    } elseif (date('H') > 17) {
        $say = __('Good evening', 'salesloo');
    }

    return $say;
}

/**
 * salesloo_make_json
 *
 * @param  mixed $data
 * @param  mixed $echo
 * @return void
 */
function salesloo_make_json($data, $echo = true)
{
    $json = json_encode((object)$data);
    $json = htmlentities2($json, ENT_QUOTES);
    if (false == $echo) return $json;

    echo $json;
}

/**
 * salesloo_on_plugins_updated
 *
 * @return void
 */
function salesloo_on_plugins_updated()
{
    Salesloo\Plugin::instance()->license->periodic_check();
}

add_action('wp_update_plugins', 'salesloo_on_plugins_updated');


/**
 * salesloo sub menu
 * 
 * register salesloo core submenu
 *
 * @param  array $submenu
 * @return array
 */
function salesloo_sub_menu($submenu)
{
    $submenu[] = Salesloo\Plugin::instance()->license->register_menu();

    return $submenu;
}

add_filter('salesloo/admin/submenu', 'salesloo_sub_menu', 10, 1);

/**
 * salesloo_admin_init_action
 *
 * @return void
 */
function salesloo_admin_init_action()
{
    Salesloo\Plugin::instance()->license->on_save_action();
}
add_action('admin_init', 'salesloo_admin_init_action', 10);

/**
 * get current pagination paged
 *
 * @return integer
 */
function salesloo_get_current_paged()
{
    $paged = 1;

    if (isset($_GET['pg'])) {
        $paged = intval($_GET['pg']);
    }

    if ($paged < 1) {
        $paged = 1;
    }

    return $paged;
}

/**
 * get current search key
 *
 * @return mixed
 */
function salesloo_get_current_search()
{
    return isset($_GET['s']) ? sanitize_text_field($_GET['s']) : '';
}


/**
 * get input request
 *
 * @return void
 */
function salesloo_get_input_request()
{
    $input = file_get_contents("php://input");
    $request = json_decode($input, true);

    if (isset($request['nonce']) && salesloo_verify_nonce($request['nonce'])) {

        return (object)$request;
    }

    return false;
}

/**
 * split daterange
 *
 * @param string $daterange
 * @return object
 */
function salesloo_split_daterange($daterange)
{
    $daterange = str_replace(' - ', ' to ', $daterange);
    $date      = sanitize_text_field($daterange);
    $dates     = explode(' to ', $date);
    $end       = isset($dates[1]) ? $dates[1] : date('Y-m-d');
    $start     = date('Y-m-d', strtotime($dates[0]));
    $end       = date('Y-m-d', strtotime($end));

    $result = (object) [
        'from' => $start,
        'to'   => $end,
        'date' => $start . ' to ' . $end
    ];

    return $result;
}

/**
 * salesloo cron
 *
 * @param  mixed $schedules
 * @return void
 */
function salesloo_cron($schedules)
{
    $schedules['salesloo_every_minute'] = array(
        'interval'  => 60,
        'display'   => __('Once Minute', 'salesloo')
    );

    return $schedules;
}
add_filter('cron_schedules', 'salesloo_cron');

/**
 * salesloo_this_host
 *
 * @return void
 */
function salesloo_this_host()
{
    return preg_replace("(^https?://)", "", site_url());
}

/**
 * salesloo_set_cookie
 *
 * @param  mixed $cookie_name
 * @param  mixed $cookie_value
 * @return void
 */
function salesloo_set_cookie($cookie_name, $cookie_value)
{
    $cookie_day = salesloo_get_option('affiliate_cookie_lifetime');
    $cookie_time = intval($cookie_day) * DAY_IN_SECONDS;

    setcookie($cookie_name, $cookie_value, time() + $cookie_time, COOKIEPATH, COOKIE_DOMAIN);
}


function salesloo_query_pagination($collection, $url)
{
    $pagination = $collection->pagination($url);
    if ($pagination->show) :
?>
        <div x-data="<?php salesloo_make_json($pagination); ?>">
            <?php salesloo_template_section('parts/pagination.php'); ?>
        </div>
<?php
    endif;
}


function salesloo_scure_html($string, $allowed_tags = [])
{
    if (empty($allowed_tags)) {
        $allowed_tags = [
            '<p>',
            '<ol>',
            '<ul>',
            '<em>',
            '<strong>',
            '<span>',
            '<h1>',
            '<h2>',
            '<h3>',
            '<h4>',
            '<h5>',
            '<h6>',
            '<pre>',
            '<a>'
        ];
    }

    if (!is_array($allowed_tags)) {
        $allowed_tags = explode(',', $allowed_tags);
    }

    $string = strip_tags($string, implode(',', $allowed_tags));

    $link_pattern = '/<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>/siU';
    $string = preg_replace_callback($link_pattern, 'salesloo_cleanest_link', $string);

    $string = htmlentities($string);
    return $string;
}


function salesloo_cleanest_link($link)
{

    if (!isset($link[2]) || !isset($link[3])) return '';

    $url = esc_url_raw($link[2]);
    $label = sanitize_text_field($link[3]);

    return '<a target="__blank" href="' . $url . '">' . $label . '</a>';
}

function salesloo_handle_external_cronjob()
{
    $enable = salesloo_get_option('extrenal_cronjob');

    if ($enable) {

        if (!defined('DISABLE_WP_CRON')) {
            define('DISABLE_WP_CRON', true);
        }

        // Just in case the constant is already set to true.
        remove_action('init', 'wp_cron');
    }
}

add_action('plugins_loaded', 'salesloo_handle_external_cronjob');

function salesloo_daterange_picker()
{
    /**
     * get yesterdady
     */
    $yesterday = date('Y-m-d', strtotime('-1 day'));

    /**
     * get this week
     */
    if (date('D') == 'Sun') {
        $this_week = date('Y-m-d');
    } else {
        $this_week = date('Y-m-d', strtotime('last sunday')) . ' - ' . date('Y-m-d');
    }

    /**
     * get last week
     */

    $previous_week = strtotime("-1 week +1 day");

    $last_week_start = strtotime("last sunday midnight", $previous_week);
    $last_week_end = strtotime("next saturday", $last_week_start);

    $last_week = date('Y-m-d', $last_week_start) . ' - ' . date('Y-m-d', $last_week_end);

    /**
     * get this month
     */
    $this_month = date('Y-m-01') . ' - ' . date('Y-m-d');

    /**
     * get last 30 day
     */

    $last_30day = date('Y-m-d', strtotime('-30 day')) . ' - ' . date('Y-m-d');

    /**
     * get last month
     */
    $last_month = date('Y-m-01 - Y-m-t', strtotime('previous month'));

    /**
     * get this year
     */
    $current_year = date('Y');
    $this_year = date($current_year . '-01-01') . ' - ' . date('Y-m-d');

    $prev_year = date('Y', strtotime('-1 year'));
    $last_year = date($prev_year . '-01-01') . ' - ' . date($prev_year . '-12-31');

    $ranges = [
        ''          => __('All time', 'salesloo'),
        date('Y-m-d')    => __('Today', 'salesloo'),
        $yesterday  => __('Yesterday', 'salesloo'),
        $this_week  => __('This week', 'salesloo'),
        $last_week  => __('Last Week', 'salesloo'),
        $this_month => __('This month', 'salesloo'),
        $last_30day => __('Last 30 Days', 'salesloo'),
        $last_month => __('Last month', 'salesloo'),
        $this_year  => __('This year', 'salesloo'),
        $last_year  => __('Last Year', 'salesloo'),
        'custom'    => __('Custom range', 'salesloo')
    ];

    return $ranges;
}

function salesloo_expired_notice__error()
{
    $class = 'notice notice-error';

    printf('<div class="%1$s"><p>%2$s</p></div>', esc_attr($class), esc_html(Salesloo\Plugin::instance()->license->message));
}


add_action('admin_init', function () {
    if (Salesloo\Plugin::instance()->license->status && Salesloo\Plugin::instance()->license->status != 200) {
        add_action('admin_notices', 'salesloo_expired_notice__error');
    }
});
