<?php
class Buy_later
{
    private $config;
    private $db;
    private $data = array();
    private $load;
    private $registry;

    public function __construct($registry)
    {
        $this->config = $registry->get('config');
        $this->customer = $registry->get('customer');
        $this->session = $registry->get('session');
        $this->db = $registry->get('db');
        $this->load = $registry->get('load');
        $this->registry = $registry;

        if (!isset($this->session->data['buy_later']) || !is_array($this->session->data['buy_later'])) {
            $this->session->data['buy_later'] = array();
        }
    }

    public function __get($name)
    {
        return $this->registry->get($name);
    }

    public function getProducts()
    {

        if (!$this->data) {
            $this->data = $this->session->data['buy_later'];
        }

        return $this->data;
    }

    public function getProduct($product_id)
    {
        return $this->session->data['buy_later'][$product_id];
    }

    public function setProduct($product_info)
    {
        $this->session->data['buy_later'][$product_info['product_id']] = $product_info;
        $this->data = array();
    }

    public function add($product_id, $qty = 1)
    {
        if ($product_id) {
            if (!(int)$qty || ((int) $qty <= 0)) {
                $qty = 1;
            }

            if (isset($this->session->data['buy_later'][$product_id])) {
                $product_info = $this->getProduct($product_id);
                $qty += $product_info['quantity'];
            }

            $this->setProduct(['product_id' => $product_id, 'quantity' => $qty]);
        }
    }

    public function update($product_id, $qty)
    {
        if ((int)$qty && ((int)$qty > 0)) {
            $this->setProduct(['product_id' => $product_id,'quantity' => (int)$qty]);
        } else {
            $this->remove($product_id);
        }
    }

    public function remove($product_id)
    {
        if (isset($this->session->data['buy_later'][$product_id])) {
            unset($this->session->data['buy_later'][$product_id]);
        }

        $this->data = array();
    }

    public function clear()
    {
        $this->session->data['buy_later'] = array();

        $this->data = array();
    }

    public function countProducts()
    {
        return count($this->getProducts());
    }

    public function getItemQuantity($product_id)
    {
        $product = $this->getProduct($product_id);

        return $product['quantity'] ?? 1;
    }
}