<?php
session_start();

require_once('admin/production/class/connectdb.php');
$conn = new DbConnect;
$con = $conn->connect();

if(isset($_SESSION['user_id'])){
   $user_id = $_SESSION['user_id'];	
}

if(isset($_POST['query_cart'])){
	$query = $_POST['query'];
    $product_id = $_POST['product_id'];
    $product_name = $_POST['product_name'];
    $product_image = $_POST['product_image'];
    $price = $_POST['price'];
    $qty = $_POST['quantity'];
    $action = $_POST['action'];
	
	$itemArray = array($product_id=>array('qty'=>$qty, 'price'=>$price, 'pid'=>$product_id, 'name'=>$product_name, 'image'=>$product_image));
	
	switch ($query) {
		case "add":
			if(!empty($_SESSION["cart_item"])){
				if(in_array($product_id, array_keys($_SESSION['cart_item']))) {
					foreach($_SESSION["cart_item"] as $k => $v){
							if($product_id == $k){
								if(empty($_SESSION["cart_item"][$k]["qty"])) {
									$_SESSION["cart_item"][$k]["qty"] = 0;
								}
								$_SESSION["cart_item"][$k]["qty"] += $qty;
							}
					}
				} else {
					$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"], $itemArray);
				}
			}else {
				$_SESSION["cart_item"] = $itemArray;
			}
			break;
		case "replace":
		    if(!empty($_SESSION["cart_item"])){
				if(in_array($product_id, array_keys($_SESSION['cart_item']))) {
					foreach($_SESSION["cart_item"] as $k => $v){
							if($product_id == $k){
								if(empty($_SESSION["cart_item"][$k]["qty"])) {
									$_SESSION["cart_item"][$k]["qty"] = 0;
								}
								$_SESSION["cart_item"][$k]["qty"] = $qty;
							}
					}
				} else {
					$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"], $itemArray);
				}
			}else {
				$_SESSION["cart_item"] = $itemArray;
			}
		    break; 	
		case "remove":
		            unset($_SESSION["cart_item"][$product_id]);
	}	
}

if(isset($_POST['place_order'])){
	
	$order_id = $_POST['order_id'];
	$name     = $_POST['name'];
	$email    = $_POST['email'];
	$message  = $_POST['message'];
	
	foreach($_SESSION['cart_item'] as $key => $val){ 
	    $product_id = $_SESSION['cart_item'][$key]['pid'];
	    $quantity = $_SESSION['cart_item'][$key]['qty'];
        $price = $_SESSION['cart_item'][$key]['price'];
	
	    $query = mysqli_query($con, "INSERT INTO cart (product_id,quantity,price,order_id,user_id,order_information) 
		             VALUES ('$product_id', '$quantity', '$price', '$order_id','$user_id','$message')");
	}
	sendOrderConfirmationEmail($email, $name, $order_id);
	if($query == true){
		unset($_SESSION['cart_item']);
	}
}

function sendOrderConfirmationEmail($email, $name, $order_id){
	
	    require 'class/class.phpmailer.php'; // Phpmail package already on server

        $mail = new PHPMailer;
		$mail->IsSMTP();								//Sets Mailer to send message using SMTP
		$mail->Host = 'just118.justhost.com';		//Sets the SMTP hosts of your Email hosting, this for Godaddy
		$mail->Port = '465';								//Sets the default SMTP server port
		$mail->SMTPAuth = true;							//Sets SMTP authentication. Utilizes the Username and Password variables
		$mail->Username = 'info@trusteepharmacy.com';					//Sets SMTP username
		$mail->Password = 'lJ,0(O:&QurQ6]';					//Sets SMTP password
		$mail->SMTPSecure = 'ssl';							//Sets connection prefix. Options are "", "ssl" or "tls"
		$mail->From = 'info@trusteepharmacy.com';			//Sets the From email address for the message
		$mail->FromName = 'Trustee Pharmacy and Supermarket';					//Sets the From name of the message
		$mail->AddAddress($email, $name);	//Adds a "To" address, i.e recipient detail.
		$mail->WordWrap = 50;							//Sets word wrapping on the body of the message to a given number of characters
		$mail->IsHTML(true);							//Sets message type to HTML
		$mail->Subject = 'Your order has been received.'; //Sets the Subject of the message
		//An HTML or plain text message body
		$mail->Body = '
			Dear Customer,
		   <p>Your order has been received.</p>
		   <p>Order ID is ' . $order_id . '.</p>
		   <p>You will be contacted shortly.</p>
		   <p>Thank you</p>
		';
        $mail->AltBody = '';
		$result = $mail->Send();
}

if(isset($_POST['get_product'])){
	$offset = $_POST['offset'];
	$limit  = $_POST['limit'];
	
	if($_POST['keyword'] != ''){
		$keyword = $_POST['keyword'];
		$searchType  = $_POST['searchType'];
	    if($searchType == 'subcategory'){
		    $sql = mysqli_query($con, "SELECT * FROM product WHERE sub_category_id = $keyword  LIMIT $limit OFFSET $offset ");
		}elseif($searchType == 'search'){
			$sql = mysqli_query($con, "SELECT * FROM product WHERE 
										   product_name LIKE '%" . $keyword . "%' 
										   OR product_info LIKE '%" . $keyword ."%'
										LIMIT $limit OFFSET $offset ");
	    }
    }else{
	  $sql = mysqli_query($con, "SELECT * FROM product WHERE availability_status = 1 LIMIT $limit OFFSET $offset  ");
    };
					   
	while($row = mysqli_fetch_array($sql)):
	$image = $row['main_image_url'];
	
	$product_name = $row['product_name'];
	$product_name = substr($product_name, 0, 23);
	$product_id = $row['product_id'];
	
	$src = "uploads/" .  $image;
	
	$price = $row['price'];
	$price = number_format($price);
	
	echo " 
		<div class='col-6 col-md-4 col-xl-2'>
			<div class='product'>
				<figure class='product-image-container'>
					<a href='product?pid=$product_id' class='product-image'>
						<img src='$src' alt='product'>
					</a>
					<a href='ajax/product-quick-view?pid=$product_id' class='btn-quickview'>Quick View</a>
				</figure>
				<div class='product-details'>
					<h2 class='product-title'>
						<a data-toggle='tooltip' title='$product_name' href='product?pid=$product_id'>$product_name</a>
					</h2>
					<div class='price-box'>
						<span class='product-price'>₦$price</span>
					</div><!-- End .price-box -->
					<div class='product-action'>
						<a onclick=\"addToCart('$product_id',$price,'$product_name', '$src')\" class='paction add-cart' title='Add to Cart'>
							<span class='pointer'>Add to Cart</span>
						</a>
					</div>
				</div>
			</div>
		</div>
	";
	endwhile;
}

?>

