<?php 

	include ('includes/db1config.php');
	include ('../includes/mysql_connect.php');
	// echo "<pre>";print_r($_POST);die('here');

	if( isset($_POST['is_last_record']) && $_POST['is_last_record'] == 1 ){

		// Update master record
		$query = "DELETE FROM customer_invoices WHERE recordkey =".$_POST['record_id'];
		mysql_query($query);   // query executed
		echo mysql_error();

		//Delete old invoices and insert new one
		for ($i=0; $i < count($_POST['oldinvoiceid']) ; $i++) { 
			$invoice = "DELETE FROM customer_invoices WHERE recordkey =".$_POST['oldinvoiceid'][$i];
			mysql_query($invoice); // query executed
			echo mysql_error();
		}

	} else {
	
		// Update master record
		$query = "UPDATE customer_invoices SET invoice_date='".mysql_escape_string($_POST['invoice_date'])."',due_date='".mysql_escape_string($_POST['due_date'])."',paid='".mysql_escape_string($_POST['paid'])."',invoice_total=".$_POST['invoice_total'].",invoice_number='".mysql_escape_string($_POST['invoice_number'])."',recurring='".mysql_escape_string($_POST['recurring'])."' WHERE recordkey =".$_POST['record_id'];
		mysql_query($query);   // query executed
		echo mysql_error();
		
		//Delete old invoices and insert new one
		for ($i=0; $i < count($_POST['oldinvoiceid']) ; $i++) { 
			$invoice = "DELETE FROM customer_invoices WHERE recordkey =".$_POST['oldinvoiceid'][$i];
			mysql_query($invoice); // query executed
			echo mysql_error();
		}

		// Insert new invoices 
		if( isset($_POST) ){
			for ($i=0; $i < count($_POST['itemdesc']) ; $i++) { 
		    	$storeNew = "INSERT INTO customer_invoices (customer_id,invoice_number,item_description,quantity,item_charge,extended_charge,master_record,paid,recurring) VALUES ('".mysql_escape_string($_POST['customer_id'])."','".mysql_escape_string($_POST['invoice_number'])."','".mysql_escape_string($_POST['itemdesc'][$i])."','".mysql_escape_string($_POST['quantity'][$i])."','".mysql_escape_string($_POST['itemcharge'][$i])."','".mysql_escape_string($_POST['extendedcharge'][$i])."','0','".mysql_escape_string($_POST['paid'])."','".$_POST['recurring']."')";
		    	mysql_query($storeNew) or die(mysql_error());
			}
		}
	}

?>	