<?php
  include "include/dbcon.php";
  include "include/CORDER.php";
  include "include/CPRODUCT.php";
?>
<?php
//  header('Content-Type: text/html; charset=utf-8');
?>
<?php
  function spaceQtty($pval){
    if($pval<10){
	  $output = " " . $pval;
	}else{
	  $output = $pval;
	}
	return $output;
  }
  
  function spaceProd($pval,$pspace){

    $pstrlen = strlen($pval);

    if( $pstrlen>$pspace){
	  $output = "";
	}else{
	  $strSpace = "";
	  for($i=$pstrlen;$i<$pspace;$i++){
	    $strSpace = $strSpace . " ";
	  }
	  $output = " " . $strSpace;
	}
	return $output;
  }
  
  function spacePrice($pval){
    if($pval<10){
	  $output = "  " . sprintf("%.2f",$pval);
	}else{
	  if($pval<100){
	    $output = " " . sprintf("%.2f",$pval);
	  }else{
	    $output = sprintf("%.2f",$pval);
	  }
	}
	return $output;
  }
?>
<?php
  global $conn;
  
  $ptime = $_POST["ptime"];
  
  $myprod = new PRODUCT();
  $billno = $myprod->getInvoiceNum();
  $arrProduct = $myprod->getProducts(" WHERE id>0");
  $ctimestamp = 0;

?>
<?php

  $mycart = new CART();
  $arrCart = $mycart->getCarts();
  $total = 0;
  
  $checkorder = true;
  $i = 0;
  foreach($arrCart as $tid=>$tcart){
  
    $ctimestamp = $tcart["ctimestamp"];
	
    $total = $total + ($arrProduct[$tcart["productid"]]["price"]*$tcart["qtty"]);

	$q = "INSERT INTO tb_orderitem VALUES(null,'$billno','".$tcart["productid"]."','".$tcart["qtty"]."','".$arrProduct[$tcart["productid"]]["price"]."')";
	
	if( mysqli_query($conn,$q) ){
	
	  $arrTempItemid[$i] = $tcart["productid"];
	  $arrTempQtty[$i] = $tcart["qtty"];
	
	}else{
	  $checkorder = false;
	}
	
    $i++;
  }

  $q2 = "INSERT INTO tb_order VALUES (null,'$ctimestamp','".date("Y-m-d",$ctimestamp)."','$billno','$total')";
//  echo $q2;
  if( mysqli_query($conn,$q2) ){
  }else{
    $checkorder = false;
  }
  
  if( $checkorder ){
	
	foreach($arrTempItemid as $tidx=>$tval){
	  $myprod->setProduct("id",$tval);
	  $myprod->deductProduct($arrTempItemid[$tidx],$arrTempQtty[$tidx]);
	}
	
    $query = "TRUNCATE`tb_cart`";
    mysqli_query($conn,$query);
	
  }else{
    
  }
  

?>
<?php
  header("location: main.php");
?>