<?php

function salesloo_affiliate_link($product = false, $parameter = [], $user = null)
{
    $username = false;

    if (is_object($user) && isset($user->user_login)) :
        $username = sanitize_text_field($user->user_login);
    elseif (is_array($user) && isset($user['user_login'])) :
        $username = intval($product['user_login']);
    elseif (is_int($user) || is_string($user)) :
        $user_id = intval($product);
        $user = get_userdata($user_id);
        if ($user) :
            $username = $user->user_login;
        endif;
    endif;

    if (false === $username) {
        $current_user = wp_get_current_user();
        $username = $current_user->user_login;
    }

    $link = site_url() . '/aff/' . $username . '/';

    if ($product) {

        $product_slug = '';

        if (is_object($product) && $product->slug) :
            $product_slug = sanitize_text_field($product->slug);
        elseif (is_int($product) || is_string($product)) :
            $product_id = intval($product);
            $product = salesloo_get_product($product_id);
            if ($product->slug) :
                $product_slug = $product->slug;
            endif;
        endif;

        $link = $link . $product_slug . '/';
    }

    if ($parameter) {
        if (is_array($parameter)) {
            $param = $parameter;
        } else {
            $param = [
                're' => sanitize_text_field($parameter)
            ];
        }
        $link = add_query_arg($param, $link);
    }

    return $link;
}

function salesloo_print_affiliate_commission($raw_commission)
{
    if (false == $raw_commission) return 0;

    if ('percen' == $raw_commission['type']) {
        return $raw_commission['value'] . '%';
    }

    return salesloo_convert_money($raw_commission['value']);
}


function salesloo_affiliated_by($username = false)
{
    if (false === $username) {
        $username = salesloo_get_current_affiliate_cookie();
    }

    $affiliated_by = sprintf(__('Affiliated By %s', 'salesloo'), $username);
    return $affiliated_by;
}

/**
 * set cookie affiliate
 *
 * @param  mixed $username
 * @return void
 */
function salesloo_set_affiliate_cookie($username)
{
    if (!$username) return false;

    $cookie_day = salesloo_get_option('affiliate_cookie_lifetime');
    $cookie_time = intval($cookie_day) * DAY_IN_SECONDS;
    setcookie('SALESLOO_CHECKOUT_AFFILIATE', $username, time() + $cookie_time, COOKIEPATH, COOKIE_DOMAIN);
}

function salesloo_get_current_affiliate_cookie()
{
    $cookie_name = 'SALESLOO_CHECKOUT_AFFILIATE';

    if (isset($_COOKIE[$cookie_name]) && $_COOKIE[$cookie_name]) {
        return sanitize_text_field($_COOKIE[$cookie_name]);
    }

    return false;
}

function salesloo_delete_current_affiliate_cookie()
{

    $cookie_day = salesloo_get_option('affiliate_cookie_lifetime');
    $cookie_time = intval($cookie_day) * DAY_IN_SECONDS;
    setcookie('SALESLOO_CHECKOUT_AFFILIATE', '', time() - $cookie_time, COOKIEPATH, COOKIE_DOMAIN);
}

/**
 * get affiliate sales summary
 *
 * @param  array $args
 * @return object
 */
function salesloo_get_affiliate_sales_summary($args)
{
    $default_args = [false, false, false, false];

    $new_args = [];

    foreach ($default_args as $key => $arg) {
        $new_args[$key] = isset($args[$key]) ? $args[$key] : $arg;
    }

    [$user_id, $product_id, $date_from, $date_to] = $new_args;

    $sales_case = "CASE WHEN status IN ('active', 'expired')";
    $leads_case = "CASE WHEN status IN ('active', 'expired', 'inactive')";

    if ($product_id) {
        $product = $product_id;

        $sales_case .= " AND product_id IN ('$product')";
        $leads_case .= " AND product_id IN ('$product')";
    }

    if ($date_from && $date_to) {
        $sales_case .= " AND created_at >= '$date_from' AND created_at <= '$date_to'";
        $leads_case .= " AND created_at >= '$date_from' AND created_at <= '$date_to'";
    }

    $sales_case .= " THEN 1 ELSE NULL END";
    $leads_case .= " THEN 1 ELSE NULL END";

    $select = "COUNT($sales_case) AS sales, COUNT($leads_case) AS leads";

    $wheres = [
        'affiliate_id = ' . absint($user_id)
    ];

    $query = '';
    if ($wheres) {
        $ww = implode(' AND ', $wheres);
        $query = "WHERE $ww";
    }

    $orders = \Salesloo\Models\Order::select($select)->query($query)->result();

    return $orders[0];
}

/**
 * get affiliate sales count
 *
 * @param  mixed $args
 * @return void
 */
function salesloo_get_affiliate_sales($args)
{
    $default_args = [false, false, false, false];

    $new_args = [];

    foreach ($default_args as $key => $arg) {
        $new_args[$key] = isset($args[$key]) ? $args[$key] : $arg;
    }

    [$user_id, $product_id, $date_from, $date_to] = $new_args;

    $sales_case = <<<SQL
            CASE WHEN status IN ('active', 'expired') 
        SQL;

    $leads_case = <<<SQL
            CASE WHEN status IN ('active', 'expired', 'inactive') 
        SQL;

    if ($product_id) {
        $product = $product_id;

        $sales_case .= <<<SQL
                AND {prefix}product_id IN ("$product")
            SQL;

        $leads_case .= <<<SQL
                AND product_id IN ("$product")
            SQL;
    }

    $sales_case .= <<<SQL
                AND created_at >= "$date_from"
                AND created_at <= "$date_to"
            SQL;

    $leads_case .= <<<SQL
                AND created_at >= "$date_from"
                AND created_at <= "$date_to"
            SQL;

    $sales_case .= <<<SQL
            THEN 1 ELSE NULL END 
        SQL;

    $leads_case .= <<<SQL
            THEN 1 ELSE NULL END 
        SQL;

    $select = <<<SQL
            COUNT($sales_case) AS sales,
            COUNT($leads_case) AS leads,
            DATE(created_at) as date
        SQL;

    $wheres = [
        'affiliate_id = ' . absint($user_id)
    ];

    $query = '';

    if ($wheres) {
        $ww = implode(' AND ', $wheres);
        $query = <<<SQL
                WHERE $ww
            SQL;
    }

    $query .= <<<SQL
            GROUP BY DATE(created_at)
        SQL;

    $orders = \Salesloo\Models\Order::select($select)->query($query)->result();

    $sales = [];
    foreach ((array)$orders as $order) {
        $sales[$order->date] = (object)[
            'leads' => $order->leads,
            'sales' => $order->sales
        ];
    }

    return $sales;
}

/**
 * get affiliate commissions summary
 *
 * @param  array $args
 * @return object
 */
function salesloo_get_affiliate_commissions_summary($args)
{
    $default_args = [false, false, false, false];

    $new_args = [];

    foreach ($default_args as $key => $arg) {
        $new_args[$key] = isset($args[$key]) ? $args[$key] : $arg;
    }

    [$user_id, $product_id, $date_from, $date_to] = $new_args;

    $select = "salesloo_commission.user_id,
            SUM(CASE WHEN status IN ('paid', 'unpaid') THEN amount ELSE 0 END) AS total,
            SUM(CASE WHEN status = 'pending' THEN amount ELSE 0 END) AS pending,
            SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END) AS paid,  
            SUM(CASE WHEN status = 'unpaid' THEN amount ELSE 0 END) AS unpaid,
            SUM(CASE WHEN status = 'cancelled' THEN amount ELSE 0 END) AS cancelled";

    $wheres = [
        'user_id = "' . absint($user_id) . '"',
    ];

    if ($product_id) {
        $wheres[] =  'product_id = ' . absint($product_id);
    }

    if ($date_from && $date_to) {
        $wheres[] =  "created_at >= '$date_from'";
        $wheres[] =  "created_at <= '$date_to'";
    }

    $query = '';

    if ($wheres) {
        $ww = implode(' AND ', $wheres);
        $query = "WHERE $ww";
    }

    $result = \Salesloo\Models\Commission::select($select)->query($query)->result();

    return $result[0];
}


function salesloo_get_affiliate_summary($affiliate_id = false, $filter = [])
{
    global $wpdb;

    if (empty($affiliate_id)) {
        $affiliate_id = get_current_user_id();
    }

    $affiliate_id = intval($affiliate_id);

    $and = '';
    $and2 = '';

    if (isset($filter['products'])) {
        $product_ids = (array)$filter['products'];
        $product_ids = implode(',', $product_ids);

        $and .= "AND product_id IN ($product_ids)";
    }

    if ($filter['daterange']) {

        $form = $filter['daterange']->from;
        $to = $filter['daterange']->to;

        $and = " AND DATE(created_at) >= '$form' AND DATE(created_at) <= '$to'";
        $and2 = " AND DATE(visited_at) >= '$form' AND DATE(visited_at) <= '$to'";
    }

    $q = "SELECT
            COUNT(CASE WHEN status IN ('unpaid', 'paid') {$and} THEN 1 ELSE NULL END) AS sales, 
            COUNT(CASE WHEN status IN ('pending', 'unpaid', 'paid', 'cancelled', 'refunded') {$and} THEN 1 ELSE NULL END) AS leads,
            JSON_OBJECT(
                'total', SUM(CASE WHEN status IN ('paid', 'unpaid') {$and} THEN amount ELSE 0 END),
                'pending', SUM(CASE WHEN status = 'pending' {$and} THEN amount ELSE 0 END),
                'paid', SUM(CASE WHEN status = 'paid' {$and} THEN amount ELSE 0 END),
                'unpaid', SUM(CASE WHEN status = 'unpaid' {$and} THEN amount ELSE 0 END),
                'cancelled', SUM(CASE WHEN status = 'cancelled' {$and} THEN amount ELSE 0 END)
                ) AS commission
        FROM $wpdb->users user
        LEFT JOIN {$wpdb->prefix}salesloo_commission commission ON user.ID = commission.user_id
        WHERE user.ID IN ($affiliate_id)
        GROUP BY user.ID ORDER BY sales DESC, leads DESC";

    $result = $wpdb->get_row($q);
    $result->commission = (object) json_decode($result->commission);

    $q2 = "SELECT
            COUNT(*) AS clicks,
            COUNT(DISTINCT ip) AS uclicks
        FROM {$wpdb->prefix}salesloo_affiliate_click
        WHERE affiliate_id = %d {$and2}";
    $result2 = $wpdb->get_row($wpdb->prepare($q2, $affiliate_id));

    $result->clicks = $result2->clicks;
    $result->uclicks = $result2->uclicks;

    return $result;
}
