<?php
session_start();
require_once 'includes/database.php';
include 'includes/funcs.php';
$db=new MySQLDatabase();
$db->open_connection();
$user = $_SESSION['reusername'];

if(isset($_REQUEST['insno'])){
$insno = $_REQUEST['insno'];		
$proval = $_REQUEST['proval'];	
$prem = $_REQUEST['proprem'];	
$rate = $_REQUEST['prorate'];
$pno = $_REQUEST['pno'];	
$cc = $_REQUEST['cname'];
$idate = substr($_REQUEST['idate'],6,4)."-".substr($_REQUEST['idate'],3,2)."-".substr($_REQUEST['idate'] ,0,2);
$supp = $_REQUEST['supp'];	
$expdate = substr($_REQUEST['expdate'],6,4)."-".substr($_REQUEST['expdate'],3,2)."-".substr($_REQUEST['expdate'] ,0,2);
$iam = $_REQUEST['iam'];
$bam = $_REQUEST['bam'];
$levy = $_REQUEST['clevy'];
$sduty = $_REQUEST['csduty'];
$wtax = $_REQUEST['cwtax'];
$levy = $_REQUEST['plevy'];
$sduty = $_REQUEST['psduty'];
$wtax = $_REQUEST['pwtax'];
$comm = $_REQUEST['comm'];
$rmks = $_REQUEST['rmks'];
$invno = getnewno("invno");
$billno = getnewno("billno");
$query = "UPDATE insrecs SET proprem = '$prem', prorate = '$rate', proval = '$proval', pno = '$pno', expdate = '$expdate', payam = '$bam', amount = '$iam', invno = '$invno', billno = '$billno', rmks = '$rmks', comm = '$comm', cwtax = '$cwtax', clevy = '$clevy', csduty = '$csduty', pwtax = '$pwtax', plevy = '$plevy', psduty = '$psduty' WHERE insno = '$insno'"; 
$result = mysqli_query($db->connection, $query) or die(mysqli_error($db->connection) ); 
$query = "SELECT * FROM insinvoices WHERE insno = '$insno'";
$result = mysqli_query($db->connection, $query) or die(mysqli_error($db->connection) );
$cnt = 0;
if ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){ $cnt++;}; 
if($cnt){ $query = "UPDATE insinvoices SET amount = '$iam', supp = '$supp', us = '$user', ts = '".date("Y-m-d H:i:s")."' WHERE insno = '$insno';";
	$result = mysqli_query($db->connection, $query) or die(mysqli_error($db->connection) );
	$query = "UPDATE insbills SET amount = '$bam', supp = '$supp', us = '$user', ts = '".date("Y-m-d H:i:s")."' WHERE insno = '$insno';";
	$result = mysqli_query($db->connection, $query) or die(mysqli_error($db->connection) );
	}
else {
	$query = "INSERT INTO insinvoices (cname, insno, idate, invno, amount, invoicecredit, supp, us, ts) VALUES ('".$cc."', ".$insno.", '".$idate."', ".$invno.", ".$iam.", 1, ".$supp.", '".$user."', '".date("Y-m-d H:i:s")."');";
	$result = mysqli_query($db->connection, $query) or die(mysqli_error($db->connection) );
	$query = "INSERT INTO insbills (cname, insno, idate, billno, amount, invoicecredit, supp, us, ts) VALUES ('".$cc."', ".$insno.", '".$idate."', ".$billno.", ".$bam.", 1, ".$supp.", '".$user."', '".date("Y-m-d H:i:s")."');";
	$result = mysqli_query($db->connection, $query) or die(mysqli_error($db->connection) );
}
$db->close_connection();
echo 'OK';  
}


?>