<?php
require_once 'includes/database.php';
require_once 'includes/funcs.php';
session_start();
$user = $_SESSION['reusername'];
$db=new MySQLDatabase();
$db->open_connection();
if (isset($_REQUEST['pdate'])){
			$amount = mysqli_real_escape_string($db->connection, $_REQUEST['am']); 
            $pmode = mysqli_real_escape_string($db->connection, $_REQUEST['pmode']); 
            $rmks = mysqli_real_escape_string($db->connection, $_REQUEST['rmks']); 
            $rtype = mysqli_real_escape_string($db->connection, $_REQUEST['rtype']);
			$supp = mysqli_real_escape_string($db->connection, $_REQUEST['supp']);
			$repono = mysqli_real_escape_string($db->connection, $_REQUEST['repono']);
			$ecat = mysqli_real_escape_string($db->connection, $_REQUEST['ecat']);
            if($ecat !== "") { $ecat = strtoupper($ecat); }
            $ts = date("Y-m-d H:i:s");
            $bacc = mysqli_real_escape_string($db->connection, $_REQUEST['bacc']);
            $chqno = mysqli_real_escape_string($db->connection, $_REQUEST['chqno']); 
			$invarr = explode(">", mysqli_real_escape_string($db->connection, $_REQUEST['ina'])); 
			$payarr = explode(">", mysqli_real_escape_string($db->connection, $_REQUEST['pya']));
            $pdate = substr($_REQUEST['pdate'],6,4)."-".substr($_REQUEST['pdate'],3,2)."-".substr($_REQUEST['pdate'] ,0,2); 
			$payno = mysqli_real_escape_string($db->connection, $_REQUEST['payno']);
			if($payno === '0'){ $payno = getnewno('payno');
				$query="INSERT INTO paytrans (payno, supp, pmode, pdate, rtype, repono, ecat, amount, rmks, chqno, bacc, us, ts) VALUES ('".$payno."', ".$supp.", '".$pmode."', '".$pdate."', '".$rtype."', ".$repono.", '".$ecat."', ".$amount.", '".$rmks."', '".$chqno."', '".$bacc."', '".$user."', '".$ts."')"; 
				}
			else { $query="UPDATE paytrans SET pmode = '$pmode', pdate = '$pdate', repono = '$repono', ecat = '$ecat', amount = '$amount', rmks = '$rmks', chqno = '$chqno', bacc = '$bacc', us = '$user', ts = '$ts' WHERE payno = ".$payno.";"; }
            
            $sql = mysqli_query($db->connection, $query) or die(mysqli_error($db->connection) );
			if($repono === '0'){
				$i=0;
				while ($invarr[$i] !==''){
					$ivalu = $payarr[$i];
					if(intval($ivalu) > 0){	$query="UPDATE insbills SET payno = '".$payno."', paidamount = ".$ivalu." WHERE billno = ".$invarr[$i]; }
					else { $query="UPDATE insbills SET payno = 0, paidamount = 0 WHERE billno = ".$invarr[$i]; }
					$sql = mysqli_query($db->connection, $query) or die(mysqli_error($db->connection) );
					$i++;
				}
			}
			if(!$sql){
                echo 'nothing';  
             }else{   
                echo $payno;
                   }                                                                                  
    $db->close_connection();
}   
?>	