<?php

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

/**
 * generate prodct slug
 */
function salesloo_generate_coupon_code()
{
    $code = '';
    $loop = true;

    while ($loop == true) {
        $code = substr(base_convert(sha1(uniqid(microtime(true))), 16, 36), 0, 10);
        $check = Salesloo\Models\Coupon_Code::query('WHERE code = %s', $code)->first();

        if ($check->code_id <= 0) {
            $loop = false;
        }
    }

    return strtoupper($code);
}

/**
 * insert coupon
 *
 * @param  array $data
 * @return mixed
 */
function salesloo_insert_coupon($data = [])
{
    $data = apply_filters('salesloo/coupon/insert/data', $data);

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

    $coupon_args = [
        'status' => isset($data['status']) ? sanitize_text_field($data['status']) : 'draft'
    ];

    $args = $data;

    foreach (Salesloo\Models\Coupon::get_columns() as $key => $type) {
        if ('ID' == $key || 'status' == $key) continue;

        if (isset($args[$key])) {

            if ($key == 'active_end' || $key == 'active_start') {
                $coupon_args[$key] =
                    date('Y-m-d H:i:s', strtotime($args[$key]));
            } else {
                $coupon_args[$key] = $args[$key];
            }

            unset($args[$key]);
        }
    }

    if (!isset($coupon_args['active_start']) || empty($coupon_args['active_start'])) {
        $coupon_args['active_start'] = 'NULL';
    }

    if (!isset($coupon_args['active_end']) || empty($coupon_args['active_end'])) {
        $coupon_args['active_end'] = 'NULL';
    }

    if (!isset($coupon_args['products']) || empty($coupon_args['products'])) {
        $coupon_args['products'] = 'NULL';
    }

    $coupon_id = Salesloo\Models\Coupon::data($coupon_args)->create();

    if (is_wp_error($coupon_id)) {
        return $coupon_id;
    }

    $code = isset($data['code']) && $data['code'] ? sanitize_text_field($data['code']) : salesloo_generate_coupon_code();

    salesloo_insert_coupon_code($coupon_id, $code);

    return $coupon_id;
}

/**
 * update coupon
 *
 * @param  array $data
 * @return mixed
 */
function salesloo_update_coupon($data = [])
{

    $data = apply_filters('salesloo/coupon/update/data', $data);

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

    $coupon_id = isset($data['ID']) ? intval($data['ID']) : 0;
    $coupon = salesloo_get_coupon($coupon_id);

    if (false === $coupon) {
        return salesloo_insert_coupon($data);
    }

    $coupon_args = [];
    $args = $data;

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

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

        if (isset($data[$key])) {

            if ($key == 'active_end' || $key == 'active_start') {

                if ($data[$key]) {
                    $coupon_args[$key] = date('Y-m-d H:i:s', strtotime($args[$key]));
                }
            } else {
                $coupon_args[$key] = $args[$key];
            }

            unset($args[$key]);
        }
    }

    $coupon_args['updated_at'] = date('Y-m-d H:i:s');

    if (!isset($coupon_args['active_start']) || empty($coupon_args['active_start'])) {
        $coupon_args['active_start'] = 'NULL';
    }

    if (!isset($coupon_args['active_end']) || empty($coupon_args['active_end'])) {
        $coupon_args['active_end'] = 'NULL';
    }

    if (!isset($coupon_args['products']) || empty($coupon_args['products'])) {
        $coupon_args['products'] = 'NULL';
    }

    $updated = Salesloo\Models\Coupon::data($coupon_args)
        ->update([
            'ID' => $coupon_id,
        ]);

    if (is_wp_error($updated)) {
        return $updated;
    }

    $code = isset($data['code']) && $data['code'] ? sanitize_text_field($data['code']) : salesloo_generate_coupon_code();

    $check = Salesloo\Models\Coupon_Code::query('WHERE coupon_id = %d AND user_id IS NULL', $coupon_id)->first();

    if ($check->code_id > 0) {
        salesloo_update_coupon_code($check->code_id, $coupon_id, $code);
    } else {
        salesloo_insert_coupon_code($coupon_id, $code);
    }


    return $coupon_id;
}
/**
 * update coupon status
 *
 * @param  mixed $coupon
 * @param  string $new_status
 * @return mixed
 */
function salesloo_update_coupon_status($coupon = 0, $new_status = '')
{

    $coupon = salesloo_get_coupon($coupon);

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

    $new_status = apply_filters('salesloo/coupon/update/status', $new_status, $coupon);

    if (false == salesloo_get_coupon_statuses($new_status)) {
        return new WP_Error('error', sprintf(__('"%s" is Invalid coupon statuses', 'salesloo'), $new_status));
    }

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

    return $updated;
}


/**
 * delete single coupon
 *
 * @param  mixed $coupon
 * @return mixed
 */
function salesloo_delete_coupon($coupon)
{
    $coupon = salesloo_get_coupon($coupon);

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

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

    if ($deleted) {
        Salesloo\Models\Coupon_Code::delete(['coupon_id' => $coupon->ID]);
    }

    return $deleted;
}

/**
 * get single coupon
 *
 * @param  mixed $coupon
 * @return mixed
 */
function salesloo_get_coupon($coupon = null)
{

    if (is_object($coupon) && isset($coupon->ID)) :
        $coupon_id = intval($coupon->ID);
    elseif (is_array($coupon) && isset($coupon['ID'])) :
        $coupon_id = intval($coupon['ID']);
    elseif (is_int($coupon) || is_string($coupon)) :
        $coupon_id = intval($coupon);
    else :
        return false;
    endif;

    $coupon = Salesloo\Models\Coupon::query('WHERE ID = %d', $coupon_id)->first();

    if ($coupon->ID <= 0) return false;

    return $coupon;
}

/**
 * insert new coupon code
 *
 * @param  int $coupon_id
 * @param  string $code
 * @param  int $user_id
 * @return mixed
 */
function salesloo_insert_coupon_code($coupon_id, $code, $user_id = null)
{

    if (!is_numeric($coupon_id) || !$code) {
        return false;
    }

    $args = [
        'coupon_id' => intval($coupon_id),
        'user_id' => $user_id,
        'code' => wp_unslash($code)
    ];

    $coupon_code_id = Salesloo\Models\Coupon_Code::data($args)->create();

    return $coupon_code_id;
}

/**
 * update coupon code
 *
 * @param  int $code_id
 * @param  int $coupon_id
 * @param  string $code
 * @param  mixed $user_id
 * @return mixed
 */
function salesloo_update_coupon_code($code_id, $coupon_id, $code, $user_id = null)
{

    $args = [
        'coupon_id' => intval($coupon_id),
        'user_id'   => null == $user_id ? 'NULL' : intval($user_id),
        'code'      => wp_unslash($code)
    ];

    $coupon_id = intval($coupon_id);
    $user_id = intval($user_id);

    $query = "WHERE coupon_id = '$coupon_id' AND user_id IS NULL";

    if ($user_id) {
        $query = "WHERE coupon_id = '$coupon_id' AND user_id ='$user_id'";
    }

    $check_code = Salesloo\Models\Coupon_Code::query($query)->first();

    if ($check_code->code_id > 0) {

        Salesloo\Models\Coupon_Code::data($args)->update([
            'code_id' => $check_code->code_id
        ]);
        $code_id = $check_code->code_id;
    } else {
        $code_id = Salesloo\Models\Coupon_Code::data($args)->create();
    }

    return $code_id;
}

/**
 * delete single coupon code
 *
 * @param  int $code_id
 * @return mixed
 */
function salesloo_delete_coupon_code($code_id)
{
    if (!is_numeric($code_id)) {
        return false;
    }

    return Salesloo\Models\Coupon_code::delete(['code_id' => intval($code_id)]);
}

/**
 * get single coupon code
 *
 * @param  int $coupon_id
 * @param  mixed $user_id
 * @return mixed
 */
function salesloo_get_coupon_code($coupon_id, $user_id = null)
{

    if (!is_numeric($coupon_id)) {
        return false;
    }

    if (null === $user_id || !$user_id) {
        $query = Salesloo\Models\Coupon_Code::query('WHERE coupon_id = %d AND user_id IS NULL', $coupon_id)->first();
    } else {
        $query = Salesloo\Models\Coupon_Code::query('WHERE coupon_id = %d AND user_id = %d', $coupon_id, $user_id)->first();
    }

    if ($query->code_id <= 0) return false;

    return $query->code;
}

/**
 * get coupon statuses
 *
 * @param  string $status
 * @return array
 */
function salesloo_get_coupon_statuses($status = false)
{
    $statuses = [
        'draft'     => __('Draft', 'salesloo'),
        'active'    => __('Active', 'salesloo'),
        'inactive'  => __('Inactive', 'salesloo'),
    ];

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

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

    return $statuses;
}

/**
 * insert coupon usage
 *
 * @param  int $coupon_id
 * @param  int $code_id
 * @param  int $invoice_id
 * @return mixed
 */
function salesloo_insert_coupon_usage($coupon_id, $code_id, $invoice_id)
{
    $args = [
        'coupon_id'  => intval($coupon_id),
        'code_id'    => intval($code_id),
        'invoice_id' => intval($invoice_id)
    ];

    $coupon_code_id = Salesloo\Models\Coupon_Usage::data($args)->create();

    return $coupon_code_id;
}

function salesloo_set_current_coupon_cookie($coupon_code)
{

    $cookie_day = salesloo_get_option('affiliate_cookie_lifetime');
    $cookie_time = intval($cookie_day) * DAY_IN_SECONDS;

    setcookie('SALESLOO_CHECKOUT_COUPON', $coupon_code, time() + $cookie_time, COOKIEPATH, COOKIE_DOMAIN);
}


function salesloo_get_current_coupon_cookie()
{
    $cookie_name = 'SALESLOO_CHECKOUT_COUPON';

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

    return false;
}


/**
 * delete cookie coupon
 * 
 * @return void
 */
function salesloo_delete_current_coupon_cookie()
{
    $cookie_day = salesloo_get_option('affiliate_cookie_lifetime');
    $cookie_time = intval($cookie_day) * DAY_IN_SECONDS;
    setcookie('SALESLOO_CHECKOUT_COUPON', '', time() - $cookie_time, COOKIEPATH, COOKIE_DOMAIN);
}


/**
 * salesloo_check_coupon
 *
 * @param  string $coupon_code
 * @param  int $product_id
 * @return mixed
 */
function salesloo_check_coupon($coupon_code, $product_id)
{
    $coupon_code = sanitize_text_field($coupon_code);
    $product_id = intval($product_id);

    $query = "WHERE status = 'active' AND code = '$coupon_code' AND products IS NOT NULL AND products LIKE '%\"$product_id\"%'";
    $query .= " OR status = 'active' AND code = '$coupon_code' AND products IS NULL";

    $coupon = Salesloo\Models\Coupon::join('right', 'salesloo_coupon_code', ['ID', 'coupon_id', '='])
        ->query($query)->first();

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