<?php 
//use Dompdf\Dompdf;
//use PHPMailer\PHPMailer\PHPMailer;
//use PHPMailer\PHPMailer\Exception;
//require __DIR__.'/vendor/autoload.php';	
session_start();	
require_once '../../Server/connection.php';
if($_POST){
  $client_id = $_POST['client_id'];
  $currency_id = $_POST['currency_id'];
  $payment_mode_id = $_POST['payment_mode_id'];
  $InvoiceDate = date('Y-m-d', strtotime($_POST['InvoiceDate']));
  $dueDate = date('Y-m-d', strtotime($_POST['dueDate']));
  $inv_status = 0;
  $orderNo = $_POST['orderNo'];
  //$message = addslashes($_POST['message']);
  
  $subTotalValue  = $_POST['subTotalValue'];
  
   $year = date("Y");
  
  $sql8123 = "SELECT * FROM invoices where year='$year'";
  $result8123 = $conn->query($sql8123);
  $num22 = mysqli_num_rows($result8123);
  //$invo_no = $count + 1;
  
  if($num22>=0 && $num22<9){
  $invo_no = $num22 + 1;
  $y = date("Y");
  //$InvNo = "INVBRVSN"."/".$y."/".'000'.$invo_no;  
  $InvNo = "INV"."/"."LUP"."/".$y."/".'000'.$invo_no;  
    }else if($num22>=9 && $num22<99){
   $invo_no = $num22 + 1;
   $y = date("Y");
  //$InvNo = "INVBRVSN"."/".$y."/".'00'.$invo_no; 
  $InvNo = "INV"."/"."LUP"."/".$y."/".'000'.$invo_no;    
	 }else if($num22>=99 && $num22<999){
   $invo_no = $num22 + 1;
   $y = date("Y");
  //$InvNo = "INVBRVSN"."/".$y."/".'0'.$invo_no;
  $InvNo = "INV"."/"."LUP"."/".$y."/".'000'.$invo_no;    
	 }else{
	$invo_no = $num22 + 1;
	$y = date("Y");
  //$InvNo = "INVBRVSN"."/".$y."/".$invo_no;  
  $InvNo = "INV"."/"."LUP"."/".$y."/".'000'.$invo_no;    
	 }
				
				
  
  
  $sql812 = "SELECT vat_settings.rate FROM vat_settings";

				$result812 = $conn->query($sql812);
				//$data81 = $result81->fetch_row();
				
				while($data812 = mysqli_fetch_array($result812))
							{
							$vat_rate = $data812['rate'];
							}
  
  
  $vat = $vat_rate/100 * $subTotalValue;
  $grand_total_Value = $subTotalValue + $vat;
 
	
	$sql = "INSERT INTO invoices (inv_no,client_id,currency_id,payment_mode_id,inv_date,due_date,orderNo,total_amount,vat,grand_total_amount,vat_rate) VALUES ('$InvNo','$client_id','$currency_id','$payment_mode_id','$InvoiceDate','$dueDate','$orderNo','$subTotalValue','$vat','$grand_total_Value','$vat_rate')";			
	$result = $conn->query($sql);
	
	if($result){
		$inv_id = $conn->insert_id;
		
		
		for($x = 0; $x < count($_POST['serv_desc']); $x++) {			
		

				// add into order_item
				$invSql = "INSERT INTO invoices_items (inv_id,services_desc,measure_id,qty, unit_price, amount) 
				VALUES ('$inv_id','".$_POST['serv_desc'][$x]."','".$_POST['measure_id'][$x]."','".$_POST['quantity'][$x]."', '".$_POST['rate'][$x]."', '".$_POST['totalValue'][$x]."')";

				$result1=$conn->query($invSql);		

		
	           }
		
		//if($result1){

  
  $_SESSION['success_message'] = "Invoice has been Created Successfully";
  header("Location: ../createInvoice.php");
  exit();
  
  
		
		//}
		
		
		
	   }

} 