<?php
require_once 'includes/database.php';
require_once 'includes/funcs.php';
session_start();
$us = $_SESSION['reusername'];
$db=new MySQLDatabase();
$db->open_connection();
if (isset($_REQUEST['newdoc'])){
            $rmks = mysqli_real_escape_string($db->connection, $_REQUEST['rmks']); 
            $insno = mysqli_real_escape_string($db->connection, $_REQUEST['insno']);
            $am = mysqli_real_escape_string($db->connection, $_REQUEST['am']);
            $prem = mysqli_real_escape_string($db->connection, $_REQUEST['prem']);
            $sduty = mysqli_real_escape_string($db->connection, $_REQUEST['sduty']);
            $levy = mysqli_real_escape_string($db->connection, $_REQUEST['levy']);
	    $ts = date("Y-m-d H:i:s");				
            $idate = substr($_REQUEST['idate'],6,4)."-".substr($_REQUEST['idate'],3,2)."-".substr($_REQUEST['idate'] ,0,2);  
			$invno = $_REQUEST['c'];
			$sql = mysqli_query($db->connection, "SELECT * FROM insrecs WHERE insno = '$insno';") or die (mysqli_error($db->connection) );
			if ($row = mysqli_fetch_array($sql, MYSQLI_ASSOC)){ $cname = $row['cname']; $supp = $row['supp'];}
			if($invno == ""){
				$invno = getnewno("credno");
				$query = "INSERT INTO insinvoices (invno, idate, insno, cname, supp, amount, invoicecredit, prem, sduty, levy, rmks, us, ts) VALUES (".$invno.", '".$idate."', ".$insno.", '".$cname."', ".$supp.", ".$am.", 0, ".($prem == "" ? 0 : $prem).", ".($sduty == "" ? 0 : $sduty).", ".($levy =="" ? 0: $levy).", '".$rmks."', '".$us."', '".$ts."');"; 
			}
			else { $query = "UPDATE insinvoices SET idate = '$idate', cname='$cname', supp='$supp', rmks='$rmks', prem='$prem', levy='$levy', sduty='$sduty', amount='$am', us='$us', ts='$ts' WHERE invno = '$invno'; ";
			}
			// echo $query;
            if(!mysqli_query($db->connection, $query)){
                echo 'nothing';  
             }else{   
                echo 'Saved Credit Note No.'.$invno;
                   }                                                                                  
    $db->close_connection();
}   
?>	