<?php
@session_start();
class OrderModel{
	public $id;
	public $cus_name;
	public $cus_address;
	public $cus_phone;
	public $order_total_price;
	public $status;
	public $created_date;
	public $order_detail = array();
}

class OrderDetailModel{
	public $id;
	public $order_id;
	public $product_id;
	public $product_name;
	public $quantity;
	public $product_price;
	public $product_total_price;
	public $cus_name;
	public $cus_address;
	public $cus_phone;
}

class Orders{
	private $conn = null;
	function __construct(){
		$db = new DB();
		$this->conn = $db->DBConnect();

	}

	public function create_order(OrderModel $order){

		$sql = "INSERT INTO orders(cus_name, cus_address, cus_phone, order_total_price) VALUES ('$order->cus_name','$order->cus_address','$order->cus_phone','$order->order_total_price')";
		if ($this->conn->query($sql) === TRUE) {

		  	$order->id = $this->conn->insert_id;

		  	foreach ($order->order_detail as $key => $value) {
		  		$sql = "INSERT INTO order_detail(order_id,product_id,product_name,quantity, product_price, product_total_price,cus_name, cus_address, cus_phone) VALUES ('$order->id','$value->product_id','$value->product_name','$value->quantity','$value->product_price','$value->product_total_price','$value->cus_name','$value->cus_address','$value->cus_phone')";

		  		$this->conn->query($sql);
		  	}

		  	unset($_SESSION["cart"]);

		  	return $order->id;
		}

		return 0;
	}

	public function get_order($order_id){
		$sql = "select order_detail.* from order_detail where order_id = $order_id";

		$result = $this->conn->query($sql);
		$orders = array();

		while($row = $result->fetch_assoc()) {
			$orderDetailModel = new OrderDetailModel();
			$orderDetailModel->product_id = $row['product_id'];
			$orderDetailModel->product_name = $row['product_name'];
			$orderDetailModel->quantity = $row['quantity'];
			$orderDetailModel->product_price = $row['product_price'];
			$orderDetailModel->product_total_price = $row['product_total_price'];
			$orderDetailModel->cus_name = $row['cus_name'];
			$orderDetailModel->cus_address = $row['cus_address'];
			$orderDetailModel->cus_phone = $row['cus_phone'];

			array_push($orders, $orderDetailModel);
		}
		return $orders;
	}
}
?>