<?php
@session_start();

class CartModel{
	public $product_id;
	public $product_name;
	public $product_img;
	public $product_qty;
	public $product_price;
}

class Cart{
	

	public function add_cart($product){

		if(isset($_SESSION['cart'])){
			$carts = json_decode($_SESSION['cart']);
		}else{
			$carts = array();
		}
		$product_exist =false;
		foreach ($carts as $key => $value) {
			if($value->product_id == $product->id){
				$value->product_qty = $value->product_qty + 1;
				$product_exist = true;
				break;
			}
		}
		if(!$product_exist){
			$cart = new CartModel();
			$cart->product_id = $product->id;
			$cart->product_name = $product->product_name;
			$cart->product_img = $product->product_img;
			$cart->product_qty = 1;
			$cart->product_price = str_replace(",","",$product->product_price);

			array_push($carts, $cart);
		}
		

		$_SESSION['cart'] =json_encode( $carts );
		
		return $carts;;

	}

	public function add_qty($pro_id){
		if(isset($_SESSION['cart'])){
			$carts = json_decode($_SESSION['cart']);
		}else{
			return;
		}

		foreach ($carts as $key => $value) {
			if($value->product_id == $pro_id){
				$value->product_qty = $value->product_qty + 1;
				break;
			}
		}

		$_SESSION['cart'] = json_encode( $carts );

		return  $carts;
	}

	public function minus_qty($pro_id){
		if(isset($_SESSION['cart'])){
			$carts = json_decode($_SESSION['cart']);
		}else{
			return;
		}

		foreach ($carts as $key => $value) {
			if($value->product_id == $pro_id){
				if($value->product_qty == 1){
					array_splice($carts, $key, 1);
				}else{
					$value->product_qty = $value->product_qty -1;
				}
				
				break;
			}
		}

		$_SESSION['cart'] = json_encode( $carts );


	}
	public function delete_item($pro_id){
		if(isset($_SESSION['cart'])){
			$carts = json_decode($_SESSION['cart']);
		}else{
			return;
		}

		foreach ($carts as $key => $value) {
			if($value->product_id == $pro_id){
				array_splice($carts, $key, 1);
				
				break;
			}
		}

		$_SESSION['cart'] =json_encode( $carts );
	}


}

?>