<?php
/**
 * Store Model
 *
 * PHP version 5.6
 *
 * @category  Opencart
 * @package   Opencart
 * @author    Mukesh Pradhan <mukeshp@riaxe.com>
 * @copyright 2019-2020 Riaxe Systems
 * @license   http://www.php.net/license/3_0.txt  PHP License 3.0
 * @link      http://inkxe-v10.inkxe.io/xetool/admin
 */
namespace ComponentStoreSpace\Models;

/**
 * Opencart Model Class
 *
 * @category Opencart
 * @package  Opencart
 * @author   Mukesh Pradhan <mukeshp@riaxe.com>
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @link     http://inkxe-v10.inkxe.io/xetool/admin
 */
class Cart
{
    /**
     * Initialize Constructor
     */
    public function __construct($con, $store, $color, $size)
    {
        $this->con = $con;
        $this->store = $store;
        $this->color = $color;
        $this->size = $size;
    }

    /**
     * date of created 08-07-2020(dd-mm-yy)
     * date of Modified (dd-mm-yy)
     * Add to cart for opencart 3
     *
     * @param (Array)cartData
     * @return boolean
     */
    public function customAddToCart($cartData) {
        $status = false;
        try {
            foreach ($cartData as $cartArray) {
                $data = (object) $cartArray;
                $sessionArr = $this->sessionRead($data->session_id);
                if (isset($sessionArr['customer_id'])) {
                    $customer = $sessionArr['customer_id'];
                } else {
                    $customer = 0;
                }
                $recurring_id = 0;
                $option = array();
                $product_id = (int) $data->id;
                if ($data->options) {
                    $option = $data->options;
                }

                $sql = "SELECT cart_id, COUNT(*) AS total FROM " . DB_PREFIX . "cart WHERE api_id = ? AND customer_id = ? AND session_id = ? AND product_id = ? AND recurring_id = ? AND `option` = ?";
                $sessionArr['data']['api_id'] = isset($sessionArr['data']['api_id']) ? (int) $sessionArr['data']['api_id'] : 0;
                $option = json_encode($option);
                $params = array();
                $params[] = 'ssssss';
                $params[] = &$sessionArr['data']['api_id'];
                $params[] = &$customer;
                $params[] = &$data->session_id;
                $params[] = &$product_id;
                $params[] = &$recurring_id;
                $params[] = &$option;
                $this->con->set_charset("utf8");
                $this->con->query("SET SQL_MODE = ''");
                $stmt = $this->con->prepare($sql);
                call_user_func_array([$stmt, 'bind_param'], $params);
                $stmt->execute();
                $query = $stmt->get_result();
                $row = mysqli_fetch_assoc($query);

                if (!$row['total']) {
                    $sql = "INSERT " . DB_PREFIX . "cart SET api_id = ?, customer_id = ?, session_id = ?, product_id = ?, recurring_id = ?, `option` = ?, quantity = ?, date_added = NOW()";
                    $sessionArr['data']['api_id'] = isset($sessionArr['data']['api_id']) ? (int) $sessionArr['data']['api_id'] : 0;
                    $params = array();
                    $params[] = 'ssssssi';
                    $params[] = &$sessionArr['data']['api_id'];
                    $params[] = &$customer;
                    $params[] = &$data->session_id;
                    $params[] = &$product_id;
                    $params[] = &$recurring_id;
                    $params[] = &$option;
                    $params[] = &$data->qty;
                    $stmt = $this->con->prepare($sql);
                    call_user_func_array([$stmt, 'bind_param'], $params);
                    $status = $stmt->execute();
                    $stmt->get_result();
                    $cart_id = mysqli_insert_id($this->con);
                } else {
                    $sql = "UPDATE " . DB_PREFIX . "cart SET quantity = (quantity + ?) WHERE api_id = ? AND customer_id = ? AND session_id = ? AND product_id = ? AND recurring_id = ? AND `option` = ?";
                    $sessionArr['data']['api_id'] = isset($sessionArr['data']['api_id']) ? (int) $sessionArr['data']['api_id'] : 0;
                    $params = array();
                    $params[] = 'issssss';
                    $params[] = &$data->qty;
                    $params[] = &$sessionArr['data']['api_id'];
                    $params[] = &$customer;
                    $params[] = &$data->session_id;
                    $params[] = &$product_id;
                    $params[] = &$recurring_id;
                    $params[] = &$option;
                    $stmt = $this->con->prepare($sql);
                    call_user_func_array([$stmt, 'bind_param'], $params);
                    $status = $stmt->execute();
                    $stmt->get_result();
                    $cart_id = $row['cart_id'];
                }
                if (isset($data->extra_price)) {
                    $sessionArr['cart-design'][$cart_id]['extra-price'] = $data->extra_price;
                }
                if (isset($data->total_qty) && $data->total_qty > 0) {
                    $sessionArr['cart-design'][$cart_id]['total_qty'] = $data->total_qty;
                }
                if (isset($data->is_variable_decoration)) {
                    $sessionArr['cart-design'][$cart_id]['is_variable_decoration'] = $data->is_variable_decoration;
                }
                if (isset($data->refid)) {
                    $sessionArr['cart-design'][$cart_id]['refid'] = $data->refid;
                }
                $this->sessionWrite($data->session_id, $sessionArr);
            }
            if ($status) {
                return true;
            }
        } catch (\Exception $e) {
            return $msg = $e->getMessage();
        }
    }

    /**
     * date of created 08-07-2020(dd-mm-yy)
     * date of Modified (dd-mm-yy)
     * Get all session value
     *
     * @param (int)session_id
     * @return array session details
     */
    public function sessionRead($session_id) {

        $sql = "SELECT `data` FROM `" . DB_PREFIX . "session` WHERE session_id = ? AND expire > " . (int)time();
        $params = array();
        $params[] = 's';
        $params[] = &$session_id;
        $this->con->set_charset("utf8");
        $this->con->query("SET SQL_MODE = ''");
        $stmt = $this->con->prepare($sql);
        call_user_func_array([$stmt, 'bind_param'], $params);
        $stmt->execute();
        $query = $stmt->get_result();
        $row = mysqli_fetch_assoc($query);
        if (!empty($row['data'])) {
            return json_decode($row['data'], true);
        } else {
            return false;
        }
    }

    /**
     * date of created 08-07-2020(dd-mm-yy)
     * date of Modified (dd-mm-yy)
     * Write all session value
     *
     * @param (int)session_id
     * @param (String)data
     * @return boolean
     */
    public function sessionWrite($session_id, $data) {
        if ($session_id) {
            $expire = ini_get('session.gc_maxlifetime');
            $encodData = json_encode($data);
            $date = date('Y-m-d H:i:s', time() + $expire);
            $sql = "REPLACE INTO `" . DB_PREFIX . "session` SET session_id = ?, `data` = ?, expire = ?";
                    
            $params = array();
            $params[] = 'sss';
            $params[] = &$session_id;
            $params[] = &$encodData;
            $params[] = &$date;
            $stmt = $this->con->prepare($sql);
            call_user_func_array([$stmt, 'bind_param'], $params);
            $status = $stmt->execute();
            $stmt->get_result();
        }
        
        return true;
    }

    public function removeCartItem($cart_id) {
        if ($cart_id) {
            $sql = "DELETE FROM " . DB_PREFIX . "cart WHERE cart_id = ?";
            $params = array();
            $params[] = 'i';
            $params[] = &$cart_id;
            $stmt = $this->con->prepare($sql);
            call_user_func_array([$stmt, 'bind_param'], $params);
            $stmt->execute();
            $stmt->get_result();
        }
    }
}