<?php
include("../include/session.php");

	
	$d = date("d");
	$m = date("m");
	$y = date("Y");
	
	
	$mm = date("m");
	$yy = date("y");
	
	$user_id = $_SESSION['username'];
	date_default_timezone_set('Africa/Gaborone');
    $entryDate = date("Y-m-d H:i:s",time()); 
	
	$table_name = $_SESSION['db_prefix']."_quotations";
	$id_query = "SELECT quote_no  FROM $table_name ORDER BY quote_id DESC LIMIT 1 ";
	$id_query;
	$id_result = mySQL_query($id_query);
	$id_result_num = mysql_num_rows($id_result);
	if ($id_result_num!=0) {
	$quote_no = mysql_result($id_result, 0, "quote_no");
	}else {
		$quote_no='';
	}
		
	
	if ( substr($quote_no, 2, 2)!=$mm ) {
	  $number="000";
	}
	else {
	  $number = substr($quote_no, 4, 3);
	}
	
	$quote_no = $yy.$mm.$number+1;
		
	
	
	$table_name = $_SESSION['db_prefix']."_qbill_lines_temp";
	$temp_query = "SELECT * FROM $table_name WHERE user_name = '".$_SESSION['username']."' ";
	$temp_result = mySQL_query($temp_query);
	$temp_num = mysql_num_rows($temp_result);
	$i=0;
	while ($i<$temp_num) {
	$cust_id = mysql_result($temp_result, $i, "cust_id");
	$reference = mysql_result($temp_result, $i, "reference");
	$amount = mysql_result($temp_result, $i, "amount"); 
	
	if ($i==0) {$value = $amount;}
		
	$table_name2 = $_SESSION['db_prefix']."_qbill_lines";
    $copy_query = "INSERT INTO $table_name2 (quote_no, cust_id,  reference, amount) VALUES('".$quote_no."', '".$cust_id."', '".$reference."', '".$amount."') " ;
	execsql($copy_query);
	$i++;
	}
	
	$table_name = $_SESSION['db_prefix']."_quotations";
	$qbill_query = "INSERT INTO $table_name (quote_no, seller, status, re_title, project, project_no, project_area, project_place, project_description, quotation_date, value ) VALUES ('".$quote_no."', '".$_SESSION['seller']."', 'quoted', '".$_SESSION['title']."', '".$_SESSION['project']."', '".$_SESSION['project_no']."', '".$_SESSION['project_area']."', '".$_SESSION['project_place']."', '".$_SESSION['description']."', '".$_SESSION['receive_date']."', '".$value."' ) ";
	execsql($qbill_query);
	
				
	$table_name = $_SESSION['db_prefix']."_tracking_sales";
   $trackingQuery = "INSERT INTO $table_name (entry_date, user_name, action, details_1, details_2, details_3, details_4) VALUES ('".$entryDate."' ,'".$_SESSION['username']."', '66', '".$quote_no ."' ,'".$amount."','".$_SESSION['project']."', '".$_SESSION['title']."' )";
   $trackingResult = mySQL_query($trackingQuery);
	
		$_SESSION['receive_date']  = '';
		$_SESSION['title'] = '';
		$_SESSION['project']  = '';
		$_SESSION['project_no']  = '';
		$_SESSION['project_area']  = '';
		$_SESSION['project_place']  = '';
		$_SESSION['description']  = '';
		$_SESSION['seller']  = '';
	
	if (isset($_GET['new_button']) )
	   {
		 $action='qbill0.php';
	   }
		 
	if (isset($_GET['finish_button']) )
	  {
		$action='sales_main.php?date=0';
	  }
	
		 
?>

<script language="javascript" type="text/javascript">
        
		  window.location="<?php echo $action ?> ";
        
       </script>



