<?php

class Cart {


	private $config;
	private $db;
	private $data = array();
	private $data_recurring = array();
	private $flag = true;

	const CARRINHOST_ATIVO    = 0;
	const CARRINHOST_INATIVO  = 1;


  	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->tax = $registry->get('tax');
		$this->weight = $registry->get('weight');
		$this->futuracalcularst = $registry->get('futuracalcularst');

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

    	}

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

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

	public function getCarrinhoStAtivo(){
	    return self::CARRINHOST_ATIVO;
	}

	public function getCarrinhoStInativo(){
	    return self::CARRINHOST_INATIVO;
	}

	//função que retorna se existe um id de produto no carrinho... byMatheus
	public function getProductOnCart($productfind){

	  foreach ($this->session->data['cart'] as $key => $quantity) {
        $product = explode(':', $key);

		$product_id = $product[0];

		if($productfind == $product_id){
		  return true;

		}

      }
      return false;
	}
    //fim da funcao

    public function atualizaSessionCart(){
        if(!$this->customer->isLogged()){
          return $this->session->data['cart'];
        }

        $qrcli = $this->db->query("select "
                                . " (p.product_id)  product_id,"
                                . " (c.customer_id) customer_id,"
                                . " (pc.quantity)   quantity"
                                . " from oc_product_cart pc"
                                . " inner join oc_product p  on (p.id_futura = pc.futura_produto_id)"
                                . " inner join oc_customer c on (c.id_futura = pc.futura_cadastro_id)"
                                . " where (c.customer_id = ".$this->session->data['customer_id'].") and ((pc.status = " . Cart::CARRINHOST_ATIVO . ") or (pc.status is null))");

        $this->session->data['cart'] = array();

        foreach ($qrcli->rows as $result) {
          $key = $result['product_id'] . "::";
          $this->session->data['cart'][$key] =  $result['quantity'];

		}

        $this->data = array();
    }



  	public function getProducts() {

		if (time() > $this->session->data['cart_time'] ) {
			$this->session->data['cart_time'] = time() + 180;
			$this->atualizaSessionCart();
		}

		if (!$this->data) {
			foreach ($this->session->data['cart'] as $key => $quantity) {
				$product = explode(':', $key);
				$product_id = $product[0];
				$stock = true;

				// Options
				if (!empty($product[1])) {
					$options = unserialize(base64_decode($product[1]));
				} else {
					$options = array();
				}

                // Profile

                if (!empty($product[2])) {
                    $profile_id = $product[2];
                } else {
                    $profile_id = 0;
                }

                $empresaid = $this->config->get('futura_empresaid');

				$product_query = $this->db->query("SELECT
					p.*,
					pd.name AS name,
					m.name AS manufacturer,
					cd.name AS category,
					coalesce((select sum(quantity)
										from oc_product_cart pc
										where (pc.futura_produto_id = p.id_futura) and ( (pc.status = " . Cart::CARRINHOST_ATIVO . ") or (pc.status is null) )  ), 0) as est_cart
					FROM " . DB_PREFIX . "product p
					LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id)
					LEFT JOIN " . DB_PREFIX . "manufacturer m ON (p.manufacturer_id = m.manufacturer_id)
					LEFT JOIN " . DB_PREFIX . "product_to_category  pc ON (pc.product_id = p.product_id)
					LEFT JOIN " . DB_PREFIX . "category c ON (c.category_id = pc.category_id) and (c.tipo_grupo_subgrupo = 1)
					LEFT JOIN " . DB_PREFIX . "category_description cd ON (cd.category_id = c.category_id)
					WHERE p.product_id = '" . (int)$product_id . "' AND pd.language_id = '" . (int)$this->config->get('config_language_id') . "' AND p.date_available <= NOW() AND p.status = '1'");


                if ($product_query->num_rows) {
					$option_price = 0;
					$option_points = 0;
					$option_weight = 0;

					$option_data = array();

					foreach ($options as $product_option_id => $option_value) {
						$option_query = $this->db->query("SELECT po.product_option_id, po.option_id, od.name, o.type FROM " . DB_PREFIX . "product_option po LEFT JOIN `" . DB_PREFIX . "option` o ON (po.option_id = o.option_id) LEFT JOIN " . DB_PREFIX . "option_description od ON (o.option_id = od.option_id) WHERE po.product_option_id = '" . (int)$product_option_id . "' AND po.product_id = '" . (int)$product_id . "' AND od.language_id = '" . (int)$this->config->get('config_language_id') . "'");

						if ($option_query->num_rows) {
							if ($option_query->row['type'] == 'select' || $option_query->row['type'] == 'radio' || $option_query->row['type'] == 'image') {
								$option_value_query = $this->db->query("SELECT pov.option_value_id, ovd.name, pov.quantity, pov.subtract, pov.price, pov.price_prefix, pov.points, pov.points_prefix, pov.weight, pov.weight_prefix FROM " . DB_PREFIX . "product_option_value pov LEFT JOIN " . DB_PREFIX . "option_value ov ON (pov.option_value_id = ov.option_value_id) LEFT JOIN " . DB_PREFIX . "option_value_description ovd ON (ov.option_value_id = ovd.option_value_id) WHERE pov.product_option_value_id = '" . (int)$option_value . "' AND pov.product_option_id = '" . (int)$product_option_id . "' AND ovd.language_id = '" . (int)$this->config->get('config_language_id') . "'");

								if ($option_value_query->num_rows) {
									if ($option_value_query->row['price_prefix'] == '+') {
										$option_price += $option_value_query->row['price'];
									} elseif ($option_value_query->row['price_prefix'] == '-') {
										$option_price -= $option_value_query->row['price'];
									}

									if ($option_value_query->row['points_prefix'] == '+') {
										$option_points += $option_value_query->row['points'];
									} elseif ($option_value_query->row['points_prefix'] == '-') {
										$option_points -= $option_value_query->row['points'];
									}

									if ($option_value_query->row['weight_prefix'] == '+') {
										$option_weight += $option_value_query->row['weight'];
									} elseif ($option_value_query->row['weight_prefix'] == '-') {
										$option_weight -= $option_value_query->row['weight'];
									}



									if ($option_value_query->row['subtract'] && (!$option_value_query->row['quantity'] || (($option_value_query->row['quantity'] - $product_query->row['est_cart']) < 0))) {
										$stock = false;
									}

									$option_data[] = array(
										'product_option_id'       => $product_option_id,
										'product_option_value_id' => $option_value,
										'option_id'               => $option_query->row['option_id'],
										'option_value_id'         => $option_value_query->row['option_value_id'],
										'name'                    => $option_query->row['name'],
										'option_value'            => $option_value_query->row['name'],
										'type'                    => $option_query->row['type'],
										'quantity'                => $option_value_query->row['quantity'],
										'subtract'                => $option_value_query->row['subtract'],
										'price'                   => $option_value_query->row['price'],
										'price_prefix'            => $option_value_query->row['price_prefix'],
										'points'                  => $option_value_query->row['points'],
										'points_prefix'           => $option_value_query->row['points_prefix'],
										'weight'                  => $option_value_query->row['weight'],
										'weight_prefix'           => $option_value_query->row['weight_prefix']
									);
								}
							} elseif ($option_query->row['type'] == 'checkbox' && is_array($option_value)) {
								foreach ($option_value as $product_option_value_id) {
									$option_value_query = $this->db->query("SELECT pov.option_value_id, ovd.name, pov.quantity, pov.subtract, pov.price, pov.price_prefix, pov.points, pov.points_prefix, pov.weight, pov.weight_prefix FROM " . DB_PREFIX . "product_option_value pov LEFT JOIN " . DB_PREFIX . "option_value ov ON (pov.option_value_id = ov.option_value_id) LEFT JOIN " . DB_PREFIX . "option_value_description ovd ON (ov.option_value_id = ovd.option_value_id) WHERE pov.product_option_value_id = '" . (int)$product_option_value_id . "' AND pov.product_option_id = '" . (int)$product_option_id . "' AND ovd.language_id = '" . (int)$this->config->get('config_language_id') . "'");

									if ($option_value_query->num_rows) {
										if ($option_value_query->row['price_prefix'] == '+') {
											$option_price += $option_value_query->row['price'];
										} elseif ($option_value_query->row['price_prefix'] == '-') {
											$option_price -= $option_value_query->row['price'];
										}

										if ($option_value_query->row['points_prefix'] == '+') {
											$option_points += $option_value_query->row['points'];
										} elseif ($option_value_query->row['points_prefix'] == '-') {
											$option_points -= $option_value_query->row['points'];
										}

										if ($option_value_query->row['weight_prefix'] == '+') {
											$option_weight += $option_value_query->row['weight'];
										} elseif ($option_value_query->row['weight_prefix'] == '-') {
											$option_weight -= $option_value_query->row['weight'];
										}

										if ($option_value_query->row['subtract'] && (!$option_value_query->row['quantity'] || (($option_value_query->row['quantity']-$product_query->row['est_cart']) < 0))) {
											$stock = false;
										}

										$option_data[] = array(
											'product_option_id'       => $product_option_id,
											'product_option_value_id' => $product_option_value_id,
											'option_id'               => $option_query->row['option_id'],
											'option_value_id'         => $option_value_query->row['option_value_id'],
											'name'                    => $option_query->row['name'],
											'option_value'            => $option_value_query->row['name'],
											'type'                    => $option_query->row['type'],
											'quantity'                => $option_value_query->row['quantity'],
											'subtract'                => $option_value_query->row['subtract'],
											'price'                   => $option_value_query->row['price'],
											'price_prefix'            => $option_value_query->row['price_prefix'],
											'points'                  => $option_value_query->row['points'],
											'points_prefix'           => $option_value_query->row['points_prefix'],
											'weight'                  => $option_value_query->row['weight'],
											'weight_prefix'           => $option_value_query->row['weight_prefix']
										);
									}
								}
							} elseif ($option_query->row['type'] == 'text' || $option_query->row['type'] == 'textarea' || $option_query->row['type'] == 'file' || $option_query->row['type'] == 'date' || $option_query->row['type'] == 'datetime' || $option_query->row['type'] == 'time') {
								$option_data[] = array(
									'product_option_id'       => $product_option_id,
									'product_option_value_id' => '',
									'option_id'               => $option_query->row['option_id'],
									'option_value_id'         => '',
									'name'                    => $option_query->row['name'],
									'option_value'            => $option_value,
									'type'                    => $option_query->row['type'],
									'quantity'                => '',
									'subtract'                => '',
									'price'                   => '',
									'price_prefix'            => '',
									'points'                  => '',
									'points_prefix'           => '',
									'weight'                  => '',
									'weight_prefix'           => ''
								);
							}
						}
					}

					if ($this->customer->isLogged()) {
						$customer_group_id = $this->customer->getCustomerGroupId();
					} else {
						$customer_group_id = $this->config->get('config_customer_group_id');
					}

					$price = $product_query->row['price'];

					// Product Discounts
					$discount_quantity = 0;

					foreach ($this->session->data['cart'] as $key_2 => $quantity_2) {
						$product_2 = explode(':', $key_2);

						if ($product_2[0] == $product_id) {
							$discount_quantity += $quantity_2;
						}
					}



					$product_discount_query = $this->db->query("SELECT price FROM " . DB_PREFIX . "product_discount WHERE product_id = '" . (int)$product_id . "' AND customer_group_id = '" . (int)$customer_group_id . "' AND quantity <= '" . (int)$discount_quantity . "' AND (quantity <> 0) AND ((date_start = '0000-00-00' OR date_start < NOW()) AND (date_end = '0000-00-00' OR date_end > NOW())) ORDER BY quantity DESC, priority ASC, price ASC LIMIT 1");

					if ($product_discount_query->num_rows) {
						$price = $product_discount_query->row['price'];
					}

                                        /* tirei porque nao trabalha com isso no ecommerce e pra dar mais desempenho. By Matheus

					// Product Specials
					$product_special_query = $this->db->query("SELECT price FROM " . DB_PREFIX . "product_special WHERE product_id = '" . (int)$product_id . "' AND customer_group_id = '" . (int)$customer_group_id . "' AND ((date_start = '0000-00-00' OR date_start < NOW()) AND (date_end = '0000-00-00' OR date_end > NOW())) ORDER BY priority ASC, price ASC LIMIT 1");

					if ($product_special_query->num_rows) {
						$price = $product_special_query->row['price'];
					}

					// Reward Points
					$product_reward_query = $this->db->query("SELECT points FROM " . DB_PREFIX . "product_reward WHERE product_id = '" . (int)$product_id . "' AND customer_group_id = '" . (int)$customer_group_id . "'");

					if ($product_reward_query->num_rows) {
						$reward = $product_reward_query->row['points'];
					} else {
						$reward = 0;
					}*/

					//se voltar o codigo comentado a cima comente a linha abaixo. ByMatheus.
					$reward = 0;

					// Downloads
					$download_data = array();

					$download_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_to_download p2d LEFT JOIN " . DB_PREFIX . "download d ON (p2d.download_id = d.download_id) LEFT JOIN " . DB_PREFIX . "download_description dd ON (d.download_id = dd.download_id) WHERE p2d.product_id = '" . (int)$product_id . "' AND dd.language_id = '" . (int)$this->config->get('config_language_id') . "'");

					foreach ($download_query->rows as $download) {
						$download_data[] = array(
							'download_id' => $download['download_id'],
							'name'        => $download['name'],
							'filename'    => $download['filename'],
							'mask'        => $download['mask'],
							'remaining'   => $download['remaining']
						);
					}

					// Stock
					if (!$product_query->row['quantity'] || (($product_query->row['quantity']-$product_query->row['est_cart']) < 0)) {
						$stock = false;
					}

					//Hugo-Imprimir msg produto indisponivel logo abaixo '***' no carrinho
					$qtde=  ($quantity -  $product_query->row['est_cart']) +  $product_query->row['quantity'];
		            $prod_id=$product_query->row['product_id'];

                    if(isset($this->session->data['cart_old'][$prod_id.'::'])){
						$qtde_sessao_old =$this->session->data['cart_old'][$prod_id.'::'];
					}else{
						$qtde_sessao_old =$quantity;
					}

			        $verify='';

					if($qtde<=0){
						$verify=' Produto Indisponível';
				    }elseif(($product_query->row['quantity']>50) && (($qtde_sessao_old > $qtde)) ){
						$verify=' Quantidade Informada: '.$qtde_sessao_old.' Indisponível !';
					}elseif(($product_query->row['quantity']<=50) && (($qtde_sessao_old > $qtde) ) ){
						$verify='Quantidade Disponível : '.$qtde;
				    }
				    //Hugo-Fim


                    $recurring = false;
                    $recurring_frequency = 0;
                    $recurring_price = 0;
                    $recurring_cycle = 0;
                    $recurring_duration = 0;
                    $recurring_trial_status = 0;
                    $recurring_trial_price = 0;
                    $recurring_trial_cycle = 0;
                    $recurring_trial_duration = 0;
                    $recurring_trial_frequency = 0;
                    $profile_name = '';

                    if ($profile_id) {
                        $profile_info = $this->db->query("SELECT * FROM `" . DB_PREFIX . "profile` `p` JOIN `" . DB_PREFIX . "product_profile` `pp` ON `pp`.`profile_id` = `p`.`profile_id` AND `pp`.`product_id` = " . (int) $product_query->row['product_id'] . " JOIN `" . DB_PREFIX . "profile_description` `pd` ON `pd`.`profile_id` = `p`.`profile_id` AND `pd`.`language_id` = " . (int) $this->config->get('config_language_id') . " WHERE `pp`.`profile_id` = " . (int) $profile_id . " AND `status` = 1 AND `pp`.`customer_group_id` = " . (int) $customer_group_id)->row;

                        if ($profile_info) {
                            $profile_name = $profile_info['name'];

                            $recurring = true;
                            $recurring_frequency = $profile_info['frequency'];
                            $recurring_price = $profile_info['price'];
                            $recurring_cycle = $profile_info['cycle'];
                            $recurring_duration = $profile_info['duration'];
                            $recurring_trial_frequency = $profile_info['trial_frequency'];
                            $recurring_trial_status = $profile_info['trial_status'];
                            $recurring_trial_price = $profile_info['trial_price'];
                            $recurring_trial_cycle = $profile_info['trial_cycle'];
                            $recurring_trial_duration = $profile_info['trial_duration'];
                        }
                    }

					$this->data[$key] = array(
						'key'                       => $key,
						'product_id'                => $product_query->row['product_id'],
						'ipi_valor'                 => 'N',//inicialmente com valor zerado, precisa calcular
						'st_valor'                  => 'N',//inicialmente com valor zerado, precisa calcular
						'fcpst_valor'	                  => 'N',//inicialmente com valor zerado, precisa calcular
						'id_futura'                 => $product_query->row['id_futura'],
						'name'                      => $product_query->row['name'],
						'model'                     => $product_query->row['model'],
						'shipping'                  => $product_query->row['shipping'],
						'image'                     => $product_query->row['image'],
						'option'                    => $option_data,
						'download'                  => $download_data,
						'quantity'                  => intval($quantity),
						'minimum'                   => $product_query->row['minimum'],
						'subtract'                  => $product_query->row['subtract'],
						'stock'                     => $stock,
						'verify'                    => $verify,
						'price'                     => ($price + $option_price),
						'total'                     => ($price + $option_price) * $quantity,
						'reward'                    => $reward * $quantity,
						'points'                    => ($product_query->row['points'] ? ($product_query->row['points'] + $option_points) * $quantity : 0),
						'tax_class_id'              => $product_query->row['tax_class_id'],
						'weight'                    => ($product_query->row['weight'] + $option_weight) * $quantity,
						'weight_class_id'           => $product_query->row['weight_class_id'],
						'length'                    => $product_query->row['length'],
						'width'                     => $product_query->row['width'],
						'height'                    => $product_query->row['height'],
						'length_class_id'           => $product_query->row['length_class_id'],
						'comp_progressiva'          => $product_query->row['comp_progressiva'],
						'larg_progressiva'          => $product_query->row['larg_progressiva'],
						'alt_progressiva'           => $product_query->row['alt_progressiva'],						
            'profile_id'                => $profile_id,
            'profile_name'              => $profile_name,
            'recurring'                 => $recurring,
            'recurring_frequency'       => $recurring_frequency,
            'recurring_price'           => $recurring_price,
            'recurring_cycle'           => $recurring_cycle,
            'recurring_duration'        => $recurring_duration,
            'recurring_trial'           => $recurring_trial_status,
            'recurring_trial_frequency' => $recurring_trial_frequency,
            'recurring_trial_price'     => $recurring_trial_price,
            'recurring_trial_cycle'     => $recurring_trial_cycle,
            'recurring_trial_duration'  => $recurring_trial_duration,
						'manufacturer'     					=> $product_query->row['manufacturer'],
						'category'									=> $product_query->row['category'],
						'price_format2'   					=> number_format(($price + $option_price),2)
					);
				} else {
					$this->remove($key);
				}
			}
		}

		try{
		$modulostconf = $this->futuracalcularst->getconfiguracoes();

		if(($this->customer->isLogged()) && ($this->customer->getTipo_pessoa() == 'J') && ($modulostconf['futuracalcularst_status']) && ($this->flag)){
				$this->flag = false;
			$productCalc = null;

			foreach ($this->data as $product){
				$productCalc[] = array(
				'id_futura' => $product['id_futura'],
				'quantity'  => $product['quantity'],
				'price'     => $product['price'],
				'total'     => $product['total']
				);
			}

			$totaldesconto = $this->futuracalcularst->getDesconto();

			$prodslist = $this->futuracalcularst->getJsonCalculaST($productCalc, $this->customer->getID_Futura(), $totaldesconto);

			$x = 0;
			foreach($this->data as $produto){
				$this->data[$produto['key']]['st_valor']   = $this->futuracalcularst->getSTFromArray($this->data[$produto['key']]['id_futura'], $prodslist);
				$this->data[$produto['key']]['ipi_valor']  = $this->futuracalcularst->getIPIFromArray($this->data[$produto['key']]['id_futura'], $prodslist);
				$this->data[$produto['key']]['fcpst_valor']     = $this->futuracalcularst->getFCPSTFromArray($this->data[$produto['key']]['id_futura'], $prodslist);
				$x ++;
			}

			$this->flag = true;
		}
	 }catch(Exception $e){
			$this->flag = true;
			throw $e;
	 }

	 return $this->data;
  }

    public function getRecurringProducts(){
        $recurring_products = array();

        foreach ($this->getProducts() as $key => $value) {
            if ($value['recurring']) {
                $recurring_products[$key] = $value;
            }
        }

        return $recurring_products;
    }


	//procedure que verifica a lista de produtos e atualiza a tabela que guardar o carrinho byMatheus
	private function setControlCart($key, $isDeleting = false){

        if(!$this->customer->isLogged()){
          return;
        }

	    $prod = explode(':', $key);
        $product_id = $prod[0];

		$querypro = $this->db->query("select id_futura from " . DB_PREFIX . "product where product_id = $product_id");

        $empresaid = $this->config->get('futura_empresaid');
		$profuturaid = $querypro->row['id_futura'];

        $querycustomer = $this->db->query("select id_futura from oc_customer c where c.customer_id = ".$this->session->data['customer_id']);

		$customer_id_futura = $querycustomer->row['id_futura'];
		$quantidade = $this->session->data['cart'][$key];


        if($isDeleting){
               $exec = $this->db->query("delete from oc_product_cart"
                                      . "  where futura_produto_id  = $profuturaid"
                                      . "    and futura_cadastro_id = $customer_id_futura"
                                      . "    and futura_empresa_id  = $empresaid");
               return;
        }

		$qrestoque = $this->db->query("select product_cart_id from oc_product_cart"
                                     ." where futura_cadastro_id = $customer_id_futura"
                                     ." and   futura_produto_id  = $profuturaid"
                                     ." and   futura_empresa_id  = $empresaid");

       $regexists = false;
       if($qrestoque->num_rows > 0){
          $regexists = true;
       }

		if(!$regexists){
          $qrmax = $this->db->query("select (coalesce(max(product_cart_id), 0) +1)retorno from oc_product_cart");
          $newid = $qrmax->row['retorno'];

          $exec = $this->db->query("insert into oc_product_cart(product_cart_id, futura_cadastro_id, futura_produto_id, futura_empresa_id, quantity, status, data_add)"
                                 . " values( $newid, $customer_id_futura, $profuturaid, $empresaid, '$quantidade', " . Cart::CARRINHOST_ATIVO . " ,CURRENT_TIMESTAMP());");

		} else{

          if($quantidade <= 0){
               $idreg = $qrestoque->row['product_cart_id'];
               $exec = $this->db->query("delete from oc_product_cart"
                                      . "  where product_cart_id    = $idreg");

          } else{

    		  $idreg = $qrestoque->row['product_cart_id'];

              $exec = $this->db->query("update oc_product_cart set"
                                     . " futura_cadastro_id = $customer_id_futura,"
                                     . " futura_produto_id  = $profuturaid,"
                                     . " futura_empresa_id  = $empresaid,"
                                     . " quantity           = '$quantidade',"
                                     . " data_add           = current_timestamp,"
                                     . " status             = " . Cart::CARRINHOST_ATIVO
                                     . " where product_cart_id    = $idreg");
          }


		}

	}

    //deleta todos os itens do carrinho de um determinado usuario...
    private function deleteCart(){
        if(!$this->customer->isLogged()){
          return;
        }

        $empresaid = $this->config->get('futura_empresaid');
        $customer_id_futura = $this->customer->getIdFutura();

        $exec = $this->db->query("delete from oc_product_cart"
                                ." where futura_cadastro_id = $customer_id_futura"
                                ."   and futura_empresa_id  = $empresaid;");


    }

  	public function add($product_id, $qty = 1, $option, $profile_id = '') {
        $key = (int) $product_id . ':';

        if ($option) {
            $key .= base64_encode(serialize($option)) . ':';
        }  else {
            $key .= ':';
        }

        if ($profile_id) {
            $key .= (int) $profile_id;
        }

		//hugo
		$this->session->data['cart_old'][$key] = (int) $qty;

		if ((int) $qty && ((int) $qty > 0)) {
            if (!isset($this->session->data['cart'][$key])) {
                $this->session->data['cart'][$key] = (int) $qty;
            } else {
                $this->session->data['cart'][$key] += (int) $qty;
            }

            $this->setControlCart($key);
        }

        $this->data = array();

		$this->session->data['cart_old'][$key] = $this->session->data['cart'][$key];

		$this->atualizaSessionCart();
		//controle de estoque carrinho - necessário para sempre que incluir algo, atualizar o que possui no carrinho... byMatheus
		$exec = $this->db->query("update " . DB_PREFIX . "customer set cart = '" . $this->db->escape(isset($this->session->data['cart']) ? serialize($this->session->data['cart']) : '') . "' where customer_id = " . (int)$this->customer->getId());


   }

   public function temEstoque($key, $qtd, $valida = false){
     if(!$this->customer->isLogged()){
          return;
      }
      $prod = explode(':', $key);
      $product_id = $prod[0];
      $query = $this->db->query("select quantity - coalesce((select sum(quantity) from oc_product_cart pc where(pc.futura_produto_id = p.id_futura) and ((pc.status = " . $this->getCarrinhoStAtivo() . ") or pc.status is null) ), 0) as retorno from oc_product p where p.product_id = $product_id");

	  if(!$valida){
		return $query->row['retorno'] > 0;
	  }else{
	    return (($query->row['retorno'] + $this->session->data['cart'][$key]) - ($qtd) ) >= 0;
	  }
   }

   public function getEstoqueCart($productid){
      if(!$this->customer->isLogged()){
          return;
      }

      $query = $this->db->query("select quantity - coalesce((select sum(quantity) from oc_product_cart pc where(pc.futura_produto_id = p.id_futura) and ((pc.status = " . $this->getCarrinhoStAtivo() . ")or(pc.status is null))  ), 0) as retorno from oc_product p where p.product_id = $productid");
	  return $query->row['retorno'];

   }

 	public function update($key, $qty) {


 	    $this->session->data['cart_old'][$key] =   (int)$qty;

	    $temestoque = $this->temEstoque($key, $qty, true);


        if($temestoque){
            if ((int)$qty && ((int)$qty > 0)) {

          		$this->session->data['cart'][$key] = (int)$qty;

                $this->setControlCart($key);
           	} else {
       	  		$this->remove($key);
            }
        }


		$this->data = array();


		//controle de estoque carrinho - necessário para sempre que incluir algo, atualizar o que possui no carrinho... byMatheus
    $this->atualizaSessionCart();
		$tempcart = $this->db->escape(isset($this->session->data['cart']) ? serialize($this->session->data['cart']) : '');
		$exec = $this->db->query("update " . DB_PREFIX . "customer set cart = '" . $tempcart . "' where (customer_id = " . (int)$this->customer->getId() . ") and (cart <> '" . $tempcart . "')");

  	}

  	public function remove($key) {


		if (isset($this->session->data['cart'][$key])) {
		    $this->setControlCart($key, true);
     		unset($this->session->data['cart'][$key]);

		}

		if (isset($this->session->data['cart_old'][$key])){

		    unset($this->session->data['cart_old'][$key]);

		}

		$this->data = array();

		//controle de estoque carrinho - necessário para sempre que incluir algo, atualizar o que possui no carrinho... byMatheus
    $this->atualizaSessionCart();
		$setcart = $this->db->escape(isset($this->session->data['cart']) ? serialize($this->session->data['cart']) : '');
		$exec = $this->db->query("update " . DB_PREFIX . "customer set cart = '" . $setcart . "' where (customer_id = " . (int)$this->customer->getId() . ") and ('" . $setcart . "' <> cart)");
	}

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

		//controle de estoque carrinho - necessário para sempre que incluir algo, atualizar o que possui no carrinho... byMatheus
		$exec = $this->db->query("update " . DB_PREFIX . "customer set cart = '' where customer_id = " . (int)$this->customer->getId());
        $this->deleteCart();
  	}

  	public function getWeight() {
		$weight = 0;

    	foreach ($this->getProducts() as $product) {
			if ($product['shipping']) {
      			$weight += $this->weight->convert($product['weight'], $product['weight_class_id'], $this->config->get('config_weight_class_id'));
			}
		}

		return $weight;
	}

  	public function getSubTotal() {
		$total = 0;

		foreach ($this->getProducts() as $product) {
			$total += $product['total'];
		}

		return $total;
  	}

	public function getTaxes() {
		$tax_data = array();

		foreach ($this->getProducts() as $product) {
			if ($product['tax_class_id']) {
				$tax_rates = $this->tax->getRates($product['price'], $product['tax_class_id']);

				foreach ($tax_rates as $tax_rate) {
					if (!isset($tax_data[$tax_rate['tax_rate_id']])) {
						$tax_data[$tax_rate['tax_rate_id']] = ($tax_rate['amount'] * $product['quantity']);
					} else {
						$tax_data[$tax_rate['tax_rate_id']] += ($tax_rate['amount'] * $product['quantity']);
					}
				}
			}
		}

		return $tax_data;
  	}

  	public function getTotal() {
		$total = 0;

		foreach ($this->getProducts() as $product) {
			$total += $this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')) * $product['quantity'];
		}

		return $total;
  	}

  	public function countProducts() {
		$product_total = 0;

		$products = $this->getProducts();

		foreach ($products as $product) {
			$product_total += $product['quantity'];
		}

		return $product_total;
	}

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

    public function hasRecurringProducts(){
        return count($this->getRecurringProducts());
    }

  	public function hasStock() {
		$stock = true;

		foreach ($this->getProducts() as $product) {
			if (!$product['stock']) {
	    		$stock = false;
			}
		}

    	return $stock;
  	}

  	public function hasShipping() {
		$shipping = false;

		foreach ($this->getProducts() as $product) {
	  		if ($product['shipping']) {
	    		$shipping = true;

				break;
	  		}
		}

		return $shipping;
	}

  	public function hasDownload() {
		$download = false;

		foreach ($this->getProducts() as $product) {
	  		if ($product['download']) {
	    		$download = true;

				break;
	  		}
		}

		return $download;
	}

  public function countVariedadeProducts($idProduto = 0) {
          //O $idProduto serve para verificar se já existe o produto na lista
          //Caso ele não exista soma mais um no retorno pois o produto está sendo adicionado.
          $product_total = 0;

  $products = $this->getProducts();
  $produtoListado = false;
  foreach ($products as $product) {
    $product_total += 1;
    if ($product ['product_id'] == $idProduto){
        $produtoListado = true;
    }
  }
  if (!$produtoListado){
    $product_total += 1;
  }
  return $product_total;
}
public function countDistinctProducts() {
  $products = $this->getProducts();
  return  count($products);
}
}
?>
