<?php

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


/**
 * insert commission
 */
function salesloo_insert_commission($data = [])
{
    $data = apply_filters('salelsoo/commission/insert/data', $data);

    if (empty($data) || !is_array($data)) return false;

    $commission_args = [];

    foreach (Salesloo\Models\Commission::get_columns() as $key => $type) {

        if (isset($data[$key])) {
            $commission_args[$key] = $data[$key];
        }
    }

    $commission_id = Salesloo\Models\Commission::data($commission_args)->create();

    return $commission_id;
}

/**
 * salesloo_update_commission
 *
 * @param  array $data
 * @return mixed
 */
function salesloo_update_commission($data = [])
{
    $data = apply_filters('salelsoo/commission/update/data', $data);

    if (empty($data) || !is_array($data)) return false;

    $commission_id = isset($data['ID']) ? intval($data['ID']) : 0;
    $commission = salesloo_get_commission($commission_id);

    $commission_args = [];
    foreach (Salesloo\Models\Commission::get_columns() as $key => $type) {

        if ('ID' == $key) continue;

        if (isset($data[$key])) {
            $commission_args[$key] = $data[$key];
        }
    }

    if (false === $commission) {
        return salesloo_insert_commission($commission_args);
    }

    $updated = Salesloo\Models\Commission::data($commission_args)->update([
        'ID' => $commission_id,
    ]);

    return $updated;
}

/**
 * update commissions status
 *
 * @param  int $commission_id
 * @param  string $status
 * @return mixed
 */
function salesloo_update_commission_status($commission_id, $status)
{
    $is_status_exists = salesloo_get_commission_statuses($status);
    if (false === $is_status_exists) {
        return new WP_Error('error', __('Invalid invoice status', 'salesloo'));
    }

    $commission = salesloo_get_commission(intval($commission_id));

    if (false === $commission) {
        return new WP_Error('error', __('Invalid commission', 'salesloo'));
    }

    if ($status == $commission->status) {
        return new WP_Error('error', __('Status same', 'salesloo'));
    }

    $commission_args = [
        'status' => $status,
        'updated_at' => date('Y-m-d H:i:s')
    ];
    $updated = Salesloo\Models\Invoice::data($commission_args)->update([
        'ID' => $commission_id,
    ]);

    return $updated;
}

/**
 * delete single commissions
 *
 * @param  mixed $commission
 * @return void
 */
function salesloo_delete_commission($commission)
{
    $commission = salesloo_get_order($commission);

    if (false === $commission) return $commission;

    $deleted = Salesloo\Models\Commission::delete(['ID' => $commission->ID]);

    return $deleted;
}


/**
 * get single commissions
 *
 * @param  mixed $commission
 * @return mixed
 */
function salesloo_get_commission($commission)
{
    if (is_object($commission) && isset($commission->ID)) :
        $commission_id = intval($commission->ID);
    elseif (is_array($commission) && isset($commission['ID'])) :
        $commission_id = intval($commission['ID']);
    elseif (is_int($commission) || is_string($commission)) :
        $commission_id = intval($commission);
    else :
        return false;
    endif;

    $commission = Salesloo\Models\Commission::query('WHERE ID = %d', $commission_id)->first();

    return $commission->ID > 0 ? $commission : false;
}

/**
 * get all commissions statistics
 *
 * @param  array $filter
 * @return mixed
 */
function salesloo_get_commissions_statistics($filter = [])
{
    $select = "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";

    $commission = \Salesloo\Models\Commission::select($select);

    if (isset($filter['products'])) {
        $commission->where('product_id', absint($filter['products']), '=');
    }

    if (isset($filter['daterange'])) {
        $daterange = salesloo_split_daterange($filter['daterange']);
        $commission->andWhere('created_at', $daterange->from, '>=');
        $commission->andWhere('created_at', $daterange->to, '<=');
    }

    $result = $commission->result();

    return $result[0];
}

/**
 * payment method type of withdrawal commissions
 *
 * @return array
 */
function salesloo_commissions_withdrawal_method_types()
{
    _deprecated_function(__FUNCTION__, '1.0.0', 'affiliate::commission_payout_method_types');

    $methods = [
        'paypal' => [
            'title' => __('Paypal', 'salesloo'),
            'example' => 'Type your paypal email eg: yourname@mail.com'
        ],
        'bank_transfer' => [
            'title' => __('Bank Transfer', 'salesloo'),
            'example' => 'Type your bank account number eg: Bank Name | Jhone Doe | 1234567890'
        ]
    ];

    $methods = apply_filters('salesloo/affiliate/widthdrawal/method/types', $methods);

    return $methods;
}

/**
 * payment methods of withdrawal commission
 *
 * @param  int $user_id
 * @return mixed
 */
function salesloo_get_commissions_withdrawal_methods($user_id = false)
{
    global $wpdb;

    _deprecated_function(__FUNCTION__, '1.0.0', 'affiliate::commission_payout_methods');

    $meta_key = 'salesloo_commissions_withdrawal_methods';
    if (false === $user_id)
        $user_id = get_current_user_id();

    $user_id = intval($user_id);

    $query = $wpdb->prepare("SELECT * FROM $wpdb->usermeta WHERE user_id=%d AND meta_key=%s", $user_id, $meta_key);

    $results = $wpdb->get_results($query);

    $new_results = [];
    foreach ($results as $result) {
        $new_results[$result->umeta_id] = maybe_unserialize($result->meta_value);
    }

    return $new_results;
}

/**
 * insert commission wthdrawal
 */
function salesloo_insert_commission_withdrawal($data = [])
{
    $data = apply_filters('salelsoo/commission-withdrawal/insert/data', $data);

    if (empty($data) || !is_array($data)) return false;

    $withdrawal_args = [];

    foreach (Salesloo\Models\Commission_Withdrawal::get_columns() as $key => $type) {

        if (isset($data[$key])) {
            $withdrawal_args[$key] = $data[$key];
        }
    }

    $withdrawal_id = Salesloo\Models\Commission_Withdrawal::data($withdrawal_args)->create();

    return $withdrawal_id;
}

/**
 * get commissions withdrawal by ID
 *
 * @param  mixed $withdrawal
 * @return mixed
 */
function salesloo_get_commission_withdrawal($withdrawal)
{
    if (is_object($withdrawal) && isset($withdrawal->ID)) :
        $withdrawal_id = intval($withdrawal->ID);
    elseif (is_array($withdrawal) && isset($withdrawal['ID'])) :
        $withdrawal_id = intval($withdrawal['ID']);
    elseif (is_int($withdrawal) || is_string($withdrawal)) :
        $withdrawal_id = intval($withdrawal);
    else :
        return false;
    endif;

    $withdrawal = Salesloo\Models\Commission_Withdrawal::query('WHERE ID = %d', $withdrawal_id)->first();

    return $withdrawal->ID > 0 ? $withdrawal : false;
}


/**
 * commissions statuses
 *
 * @param  string $status
 * @return mixed
 */
function salesloo_get_commission_statuses($status = false)
{
    $statuses = [
        'pending'   => __('Pending', 'salesloo'),
        'unpaid'    => __('Unpaid', 'salesloo'),
        'paid'      => __('Paid', 'salesloo'),
        'cancelled' => __('Cancelled', 'salesloo'),
    ];

    $statuses = apply_filters('salesloo/commissions/statuses', $statuses, $status);

    if ($status) {
        return isset($statuses[$status]) ? $statuses[$status] : false;
    }

    return $statuses;
}
