<?php

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

/**
 * salesloo_update_cart
 *
 * @param  int $product_id
 * @param  int $on_checkout
 * @param  string $username
 * @return mixed
 */
function salesloo_update_cart($product_id, $username, $on_checkout = 1)
{
    if (empty($product_id) || false === $username) {
        return new WP_Error('error', __('username can\'t be empty', 'salesloo'));
    }

    $on_checkout = intval($on_checkout);
    $on_checkout = $on_checkout ? $on_checkout : 'NULL';

    $args = [
        'user'        => sanitize_text_field($username),
        'product_id'  => intval($product_id),
        'on_checkout' => $on_checkout
    ];

    $check = Salesloo\Models\Cart::query("WHERE user = %s AND product_id = %d", $username, $product_id)->first();

    if ($check->ID > 0) {
        $updated = Salesloo\Models\Cart::data($args)->update([
            'ID' => $check->ID,
        ]);

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

        $cart_id = $check->ID;
    } else {
        $cart_id = Salesloo\Models\Cart::data($args)->create();
    }
    return $cart_id;
}



/**
 * salesloo_delete_cart
 *
 * @param  string $username
 * @param  int $product_id
 * @return mixed
 */
function salesloo_delete_cart($cart_id)
{
    $deleted = Salesloo\Models\Cart::delete(['ID' => intval($cart_id)]);
    return $deleted;
}


/**
 * salesloo_add_to_cart
 *
 * @param  string $username
 * @param  int $product_id
 * @return mixed
 */
function salesloo_add_to_cart($product_id, $username = '')
{
    if (empty($username)) {
        if (is_user_logged_in()) {
            $username = wp_get_current_user()->user_login;
        } else {
            $username = salesloo_get_guest_checkout_user();
        }
    }

    $cart_id = salesloo_update_cart($product_id, $username, 1);

    return $cart_id;
}
