<?php

class Product_visualized
{
    private $config;
    private $db;
    private $data = array();

    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['product_visualized']) || !is_array($this->session->data['product_visualized'])) {
            $this->session->data['product_visualized'] = array();
        }
    }

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

    public function getProducts($dataFilter)
    {
        $products_id = "";
        foreach ($this->session->data['product_visualized'] as $product_id) {
            $products_id .= $product_id . ',';
        }

        if ($products_id) {
            $dataFilter['product_ids'] = substr($products_id, 0, -1);
            $this->load->model('catalog/product');
            return $this->model_catalog_product->getProducts($dataFilter);
        } else {
            return array();
        }

    }

    public function getTotalProducts()
    {
        return count($this->session->data['product_visualized']);
    }

    public function add($product_id, $grid_id = 0, $quantity = 1)
    {

        if ($quantity > 0) {
            if (!in_array($product_id, $this->session->data['product_visualized'])) {
                if ($grid_id > 0) {
                    if (!array_key_exists($grid_id, $this->session->data['product_visualized'])) {
                        $this->session->data['product_visualized'][$grid_id] = $product_id;
                    }
                } else {
                    $this->session->data['product_visualized'][$product_id] = $product_id;
                }
            }
        }

    }

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

        $this->data = array();
    }


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

        $this->data = array();
    }
}
