<?php

namespace Salesloo;

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

use Salesloo\Models\Product;

/**
 * Cart classes
 */
class Cart
{
    private static $is_single =  false;

    /**
     * prepare cart on checkout;
     * 
     * @return mixed
     */
    public static function prepare()
    {
        $vars = salesloo_vars();

        if (isset($vars['__product']) && $vars['__product']) {
            self::$is_single = sanitize_text_field($vars['__product']);
        }

        return new self;
    }


    /**
     * get_items
     * 
     * get current cart items
     *
     * @return mixed
     */
    public function get_items()
    {
        if (self::$is_single) {
            $product = Product::query("WHERE slug = %s", self::$is_single)->get();

            return $product->found() > 0 ? $product : false;
        } else {
            $user = wp_get_current_user()->user_login;

            $query = "WHERE user = '$user' AND status = 'active' AND on_checkout IS NOT NULL";
            $products = Product::rightJoin('salesloo_cart', ['salesloo_product.ID', 'salesloo_cart.product_id'])
                ->select(
                    [
                        'salesloo_product.*',
                        'salesloo_cart.on_checkout',
                        'salesloo_cart.user'
                    ]
                )
                ->query($query)
                ->get();

            return $products->found() > 0 ? $products : array();
        }
    }
}
