<?php
session_start();
require_once("class/connectdb.php");
$con = new DbConnect;
$con = $con->connect();

$user_id = $_SESSION['user']; 

class item{
		private $name;
		private $price;
		private $nairaSign;
		public function __construct($name = '', $price = '', $nairaSign = false)
		{
			$this->name = $name;
			$this->price = $price;
			$this->nairaSign = $nairaSign;
		}
		public function __toString()
		{
			$rightCols = 10;
			$leftCols = 38;
			if ($this->nairaSign) {
				$leftCols = $leftCols / 2 - $rightCols / 2;
			}
			$left = str_pad($this->name, $leftCols);
			$sign = $this->nairaSign ? 'N ' : '';
			$right = str_pad($sign . $this->price, $rightCols, ' ', STR_PAD_LEFT);
			return "{$left}{$right}\n";
		}
	}

if(isset($_POST['attend_test_sale'])){
	$query = $_POST['query'];
	$product_name  = $_POST['test_name'];
	$price  = $_POST['price'];
	$qty  = $_POST['qty'];
	$product_id  = $_POST['test_id'];
	$customer_id = 1;
	$till = 3;
	$action = $_POST['action'];
	
	$itemArray = array($product_name=>array('qty'=>$qty, 'price'=>$price, 'tid'=>$product_id, 'test_name'=>$product_name,  'customer_id'=>$customer_id, 'till'=>$till));
	
	switch ($query) {
		case "add":
			if(!empty($_SESSION["cart_item"])){
				if(in_array($product_name, array_keys($_SESSION['cart_item']))) { //check if item is already in array
					foreach($_SESSION["cart_item"] as $k => $v){  //for each key and value in array
							if($product_name == $k){    //Where key is the current product
								if(empty($_SESSION["cart_item"][$k]["qty"])) {  //if qty at this key is empty set it to 0
									$_SESSION["cart_item"][$k]["qty"] = 0;
								}
								$_SESSION["cart_item"][$k]["qty"] += $qty;  //else increase it
							}
					}
				} else {                                               //If item is not in array, add this item
					$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"], $itemArray);
				}
			}else {
				$_SESSION["cart_item"] = $itemArray;     //if cart is empty, add first item to array
			}
			break;
		case "replace":
		    if(!empty($_SESSION["cart_item"])){
				if(in_array($product_name, array_keys($_SESSION['cart_item']))) {
					foreach($_SESSION["cart_item"] as $k => $v){
							if($product_name == $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_name]);
	}	
}

if(isset($_POST['send_to_cashier'])){
	$items = [];
	$net_qty_price = 0;

	//this will be copied to the printing script
	$transaction_id = $_POST['transaction_id'];
	$loyalty_id = $_POST['customer_id'];
	$user_id = $_SESSION['user'];
	$date = date("Y-m-d");

	foreach($_SESSION['cart_item'] as $key => $val){
		//Remember to add the test_id to this table when saving to database
		$test_name  = $_SESSION['cart_item'][$key]['test_name'];
		//$test_name = substr($test_name, 0, 29);
		$price  = $_SESSION['cart_item'][$key]['price'];
		$test_id  = $_SESSION['cart_item'][$key]['tid'];
		$qty  = $_SESSION['cart_item'][$key]['qty'];
		$till = 3;
		$item = new item($test_name . ' X' . $qty, $price * $qty);
		$qty_price = $price * $qty;
		$net_qty_price += $qty_price;
		array_push($items, $item);
		
		$query = mysqli_query($con, "INSERT INTO labtesttill (test_name, test_id, price, qty, till, loyalty_id, transaction_id, user_id, date)  
					   VALUES ('$test_name', '$test_id', '$price', '$qty', '$till', '$loyalty_id', '$transaction_id', '$user_id', '$date')");
	}

	if($query){
		$output['error'] = false;
		$output['status'] = "Test sent to cashier";
		$_SESSION["cart_item"] = [];   //Empty the cart
	}else{
		$output['error'] = true;
		$output['status'] = "Failed to create table";
	}

	echo json_encode($output);
}

if(isset($_POST['update_qty'])){
	$newqty  = $_POST['newqty'];
	$labtesttill_id  = $_POST['labtesttill_id'];
	
	$sql = mysqli_query($con, "UPDATE labtesttill SET qty = '$newqty' WHERE labtesttill_id = $labtesttill_id ");	
}

if(isset($_POST['cancel_till_sale'])){
	$labtesttill_id  = $_POST['labtesttill_id'];
	$sql = mysqli_query($con, "DELETE FROM labtesttill WHERE labtesttill_id = $labtesttill_id ");
}


//this will be copied to the printing script
if(isset($_POST['submit_and_print'])){
	$transaction_id = $_POST['transaction_id'];
	$payment_type = $_POST['payment_type'];
	$loyalty_id = $_POST['customer_id'];
	$user_id = $_SESSION['user'];
	$date = date("Y-m-d");
	
	foreach($_SESSION['cart_item'] as $key => $val){
		$test_name  = $_SESSION['cart_item'][$key]['test_name'];
		$price  = $_SESSION['cart_item'][$key]['price'];
		$qty  = $_SESSION['cart_item'][$key]['qty'];
		$till = 3;
		
		$query = mysqli_query($con, "INSERT INTO labtesttill (test_name, price, qty, till, payment_type, loyalty_id, transaction_id, user_id, date)  
		               VALUES ('$test_name', '$price', '$qty', '$till', '$payment_type', '$loyalty_id', '$transaction_id', '$user_id', '$date')");
	}
	if($query){
		$output['error'] = false;
		$output['status'] = "Test created on till";
		$_SESSION["cart_item"] = [];   //Empty the cart
	}else{
		$output['error'] = true;
		$output['status'] = "Failed to create table";
	}
	
	echo json_encode($output);
}

if(isset($_POST['search_test'])){
	$search_value = $_POST['search_value'];
	
	$sql = mysqli_query($con, "SELECT * FROM labtest WHERE test_name LIKE '%" . $search_value . "%' LIMIT 44 ");
	while($row = mysqli_fetch_array($sql)){
		$test_id = $row['test_id'];
		$test_name = $row['test_name'];
		$f_test_name = substr($row['test_name'],0, 120);
		$price = $row['price'];
		$f_price = number_format($price);
		
		echo "
	        <div class='animated flipInY col-lg-3 col-md-3 col-sm-6 col-xs-12 pointer' style='color:white;'>
				<div class='tile-stats' style='height: 90px; background-color: blue' onclick='addLabTest($test_id)'>
					 <div class='count' style='font-size: 15px' id='price-$test_id' testprice='$price'> $f_price </div>
					 <p><span id='test_name-$test_id' testname='$test_name'><b>$f_test_name.</b></span></p>
				</div>
			</div>
	    ";
	}
	
}

if(isset($_POST['table_data'])){

	$data['total_price'] = 0;
	$sql =  mysqli_query($con, "SELECT * FROM labtesttill "); 
			while($row = mysqli_fetch_array($sql)){
				$test_name = $row['test_name'];
				$transaction_id = $row['transaction_id'];
				$price = $row['price'];
				$date = $row['date'];
				$data['total_price'] += $row['price'];
				echo "<tr>
						<td>$test_name </td>
						<td>$transaction_id</td>
						<td>$price </td>
						<td>$date</td>
						<td>
						  <div class='btn-group'>
							 <a href='transaction-detail?trid=$transaction_id' class='btn btn-primary'><span class='glyphicon glyphicon-pencil'></span></a> 
						  </div>
						</td>
					</tr>";
			}
	
   
}

if(isset($_POST['update-transaction'])){
  $test_id = $_POST['test_id'];
  $labtest_till_id = $_POST['labtest_till_id'];
  $qty = $_POST['qty'];
  
  $query = mysqli_query($con, "UPDATE labtesttill SET test_id = '$test_id' , qty = '$qty' WHERE labtesttill_id = $labtest_till_id ");
  
  echo $query;
}




?>