<?php 
session_start();
require_once 'includes/database.php';
require_once 'includes/funcs.php';
if (!isset($_SESSION['reusername'])) { echo 'Sorry You Dont Have permissions to View this Page!'; exit();}
else {$user = $_SESSION['reusername'];}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <script type="text/javascript" src="js/jquery-1.10.2.js"></script>
        <script type="text/javascript" src="js/jquery-ui-1.10.4.custom.js"></script>
        <link rel="stylesheet" href="css/allcss.css" type="text/css" />
        <link rel="stylesheet" href="css/jquery-ui-1.10.4.custom.css" type="text/css" />
        <style>
            html, body {margin:0; padding:0; height:100%; width:100%; min-width:100%; min-height:100%; overflow:scroll;}
#payform {
text-align: left;
width:90%;
margin: 5px; padding-left:5px; padding-right:5px;
border: 1px solid #666; 
background: #AAD4FF;
box-shadow: 0px 0px 5px rgba(0,0,0,0.5); 
font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;
font-weight:bold;
font-size:14px;
color:#2C2C57; 
z-index: 100;
text-wrap: none;
}
        </style>
<script>   
function suminvams() {                      // on selecting
    var tot = 0; 	var ina = "";  	var paya = "";
    var tp = document.getElementsByName('topay');
	var ip = document.getElementsByName('billno');
    for(var i=0;i<tp.length;i++){ 
        var avwc = tp[i].value;
        var av1 = avwc.replace(/[+-][^0-9.]/g,'');   
        var aa = parseFloat(av1);
        if(aa>0) { tot += aa;
				   paya += tp[i].value + ">";
				   ina += ip[i].value + ">";	
		 }  
        else { tp[i].value = 0;
				paya += tp[i].value + ">";
				ina += ip[i].value + ">";
			 }	
     };   
     document.getElementById('am').value = tot;
	 document.getElementById('payarr').value = paya;
	 document.getElementById('invarr').value = ina;
 };
      
 $(document).ready(function() { 
$('#chks').hide();
$('#repono').hide();
$('#ecatbx').hide();
document.getElementById('rtype').value="INSURANCE";
document.getElementById('supselbut').value="1";
document.getElementById('ordselbut').value="0";
$('#sname').autocomplete({ source: <?php echo allsuppliers(); ?>, minLength: 2  });
$('#ecat').autocomplete({ source: <?php echo allexpcats(); ?>, minLength: 2  });
$('#repono').autocomplete({ source: <?php echo allreponos(); ?>, minLength: 2  });

$("#btnaddpay").click(function(e) {
e.preventDefault();
var ttt = $("#pmode :selected").val();

if( $('#pdate').val()===""){
        $(".validateTips3").html("<font size='2' color='red'><center>Date Cannot Be Blank!</center></font>");
        } 
else if( $('#am').val()===""){
        $(".validateTips3").html("<font size='2' color='red'><center>Amount Cannot Be Blank!</center></font>");
        } 		
else if( $('#bacc').val()===""){
        $(".validateTips3").html("<font size='2' color='red'><center>Bank Cannot Be Blank!</center></font>");
        } 	
else if( (ttt === "CHEQUE") && ( $("#chqno").val()=== null) ){
        $(".validateTips3").html("<font size='2' color='red'><center>Cheque No.is Required!</center></font>");
        } 
else { 
    if($("#am").val()==="") { var ramount = 0;}  else {  var ramount = $("#am").val();}
    if($("#bacc").val()!== null) { var bacc = $("#bacc").val();} else {  var bacc = ".";}
    if($("#rmks").val()!== null) { var vrmk = $("#rmks").val();} else {  var vrmk = ".";}
    if($("#chqno").val()!== null) { var chequeno = $("#chqno").val();} else {  var chequeno = "-";}
    var repono = $('#repono').val(); 
	var myno = 0;
	if(repono !== '0') {  myno = repono.slice(0, (repono.indexOf("-"))-1); }
    var jqxhrposts = $.get("paysav.php?pdate="+$("#pdate").val()+"&payno="+$("#payno").val()+"&pmode="+ttt+"&am="+ramount+"&chqno="+chequeno+"&rmks="+vrmk+"&rtype="+$('#rtype').val()+"&bacc="+bacc+"&supp="+$('#supp').val()+"&ina="+$('#invarr').val()+"&pya="+$('#payarr').val()+"&repono="+myno+"&ecat="+$('#ecat').val(), function(data) {
					if (data.trim() ==="nothing"){ $(".validateTips3").html("<font size='2' color='red'><center>Error in creating Payment!</center></font>"); }
                    else { $(".validateTips3").html("<font size='2' font-weight:bold color='green'><center>Successfully Created!</center></font>");
                         window.location.replace('payprint.php?p='+data.trim()+'&pd='+$("#pdate").val()+'&am='+ramount+'&rtype='+$('#rtype').val()+'&chk='+chequeno+' - '+bacc+'&pmode='+ttt+'&rmks='+vrmk+'&supp='+$('#supp').val()+'&repono='+myno+'&ecat='+$('#ecat').val());    
                          }
                          });
                          
    }                    
});
 });
</script>
<?php  
if($_REQUEST['e'] === "0"){
	$supp = '0';
	$pdate = date("d-m-Y");
	$pmode = '';
	$chqno = '';
	$chqdet = '';
	$am = '0';
	$rmks = '';
    $bacc = '';
	$ecat = '';
	$payno = 0;
	$rtype='';
	$repono = '0';
}
else {
	$payno = $_REQUEST['payno'];
	require_once 'includes/database.php';

	$db=new MySQLDatabase();
	$db->open_connection();
	$query = "SELECT * FROM paytrans WHERE payno = '$payno';";
	$result = mysqli_query($db->connection, $query) or die(mysqli_error($db->connection) );
	if ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
		$supp = $row['supp'];
		$repono = $row['repono'];
		$pdate = substr($row['pdate'],8,2)."-".substr($row['pdate'],5,2)."-".substr($row['pdate'] ,0,4);
		$pmode = $row['pmode'];
		$chqno = $row['chqno'];
		$chqdet = $row['chqdet'];
		$am = $row['amount'];
		$rmks = $row['rmks'];
        $bacc = $row['bacc'];
		$rtype = $row['rtype'];
		$ecat = $row['ecat'];
	}
	else { echo '<script type="text/javascript"> window.close();</script>';}
	$db->close_connection();
}
?>      
</head><body>
<p class="titletr"><?php echo (($_REQUEST['e'] !== "0") ? 'Edit Payment No.'.$payno : 'New Payment'); ?> <a href="#"><img src="images/close.png" onclick="window.close();"> </a></p>       
<form id="payform" method="post" onkeypress="return event.keyCode!=13" action="payadd.php" >
                    <center>
                    <p id="validatepay" class="validateTips3">  All fields are required!</p>    
                    <table cellspacing="5px" id="lladdbox">
                    <tr><td align="left"><label for="rdate"> Payment Date &nbsp;</label></td>
                    <td><input type="text" id="pdate" name="pdate" value="<?php echo date('d-m-Y'); ?>" size="20" required="required"/> <input type="hidden" id="payno" name="payno" value="<?php echo $payno; ?>"/></td>
                    </tr>    
					<tr><td colspan="2" align="left" style="border:1px solid #666;padding:4px;"> <input type="radio" id="supselbut" <?php if(intval($supp) > 0) { echo 'checked value="1"'; } else { echo ' value="0"'; } ?> name="payselbut" onclick="setsupp();" /> <b>Supplier</b>&nbsp;&nbsp; <select id="supp" onchange="paydets();" name="supp"> <?php if(intval($supp) > 0) { echo 'checked <option value="'.$supp.'">'.getsupplier($supp).'</option>'; } else { echo '<option value="0"></option>'; } echo selsupplier(); ?> </select> 
																								 <input type="radio" id="ordselbut" <?php if(intval($repono) > 0) { echo 'checked value="1"'; } else { echo ' value="0"'; }?> name="payselbut" onclick="setord();" value="0"/> <b>Order No.</b> <input type="text" id="repono" name="repono" <?php if($repono !== '0') { echo ' value="'.$repono.'"';} else { echo ' value="0"'; } ?> style="width:250px;" /> <input type="hidden" id="rtype" name="rtype"/>  </td>
                    </tr>  
					<tr id="ecatbx"><td align="left"><label for="ecat"> Expense Category&nbsp;</label></td>
                    <td><input type="text" id="ecat" name="ecat" value="<?php echo $ecat; ?>" size="20"/></td>
                    </tr>
					<tr><td colspan="2"> <div id="paydetbx"> 
					
					<?php if (($_REQUEST['e'] === '1') && intval($supp)>0) {
							$db=new MySQLDatabase();
							$db->open_connection();
							if( $rtype === "INSURANCE"){ $qrystr = "SELECT insbills.idate, insbills.billno, CONCAT(insrecs.insno,'- ',insrecs.regno,'-',insrecs.vehmod,' -',insrecs.cname) as nar, insbills.paidamount, insbills.amount FROM insbills, insrecs WHERE insbills.insno = insrecs.insno AND insbills.supp = '$supp' AND (insbills.payno=0 OR insbills.payno='$payno') ORDER BY insbills.billno";  
								$res = mysqli_query($db->connection, $qrystr) or die (mysqli_error($db->connection) );
								echo "<table id='paydetstab' cellspacing='4px' align='center'>";
								echo "<th>Invoice No.</th> <th>Date</th> <th>Naration</th> <th>Amount</th> <th>To Pay</th>";
								echo '<tr><td></td></tr>';
								while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)){
									$sd = $row['idate']; $nd = substr($sd,8,2)."-".substr($sd,5,2)."-".substr($sd,0,4);
									echo "<tr><td>".$row['billno']."</td> <td>".$nd." <input type='hidden' id='billno' name='billno' value='".$row['billno']."'/></td> <td align='left'>".$row['nar']."</td> <td>".$row['amount']."</td> <td><input class='pdamsjust' type='text' id='topay' name='topay' onchange='suminvams();' value='".$row['paidamount']."' size='8'/></td> </tr>";
								}
								echo "</table>";
							}	
							$db->close_connection();
							}
							
						?>  
					</div></td></tr>
					<tr><td align="left"><label for="am"> Amount &nbsp;</label></td>
                    <td><input type="text" id="am" name="am" value="<?php echo $am; ?>" size="10" required="required"/></td>
                    </tr>
                    <tr><td align="left"><label for="pmode"> Payment Mode &nbsp;</label></td>
                    <td><select id="pmode" name="pmode" style="width:100px; height:20px;" onchange="getpaymoddet();"> <?php echo '<option value="'.$pmode.'">'.$pmode.'</option>'; ?> <option value="CASH" selected>CASH</option><option value="CHEQUE">CHEQUE</option><option value="MPESA">MPESA</option></select></td>
                    </tr>
                    <tr id="chks"><td align="left"><label for="chqno"> Cheque No. &nbsp;</label> </td>
						<td><input type="text" id="chqno" name="chqno" value="<?php echo $chqno; ?>" size="5"> </td>
                    </tr>    
                    <tr><td align="left"><label for="rmks"> Remarks &nbsp;</label></td>
                    <td><input type="text" id="rmks" name="rmks" value="<?php echo $rmks; ?>" size="40"> <input type="hidden" id="invarr" name="invarr"/><input type="hidden" id="payarr" name="payarr"/></td>
                    </tr>
                    <tr><td align="left"><label for="bacc"> From Bank &nbsp;</label></td>
                    <td><select id="bacc" style="width:200px;" name="bacc"> <?php echo '<option value="'.$bacc.'">'.$bacc.'</option>'; echo selallbanks(); ?> </select></td>
                    </tr>
                    <br />
                    <tr><td colspan=2 align="center"><input type="submit" id="btnaddpay" name="btnaddpay"  class="text ui-widget-content ui-corner-all" value=" Save Payment " style="width:160px;font-weight:bold; "/></td>
                    </td></tr>
                    </table></center>
                    </form>
    </body>
</html>

<script type="text/javascript">
$("#pdate").datepicker({ changeMonth: true, changeYear: true, dateFormat: "dd-mm-yy"});  
if($('#supselbut').val() === '1'){
document.getElementById('rtype').value="INSURANCE";
$('#repono').hide();
$('#supp').show();
$('#ecatbx').hide();   
}
else {
document.getElementById('rtype').value="REPOSESSION";
$('#repono').show();
$('#supp').hide();
$('#ecatbx').show();
}
                                                               // setting bank for cash
function getpaymoddet(){ 
 if($('#pmode').val()==="CASH") { 
     document.getElementById('bacc').value="CASH IN HAND"; 
     $('#chks').hide();
 }
 else {
    $('#chks').show();
    document.getElementById('bacc').selectedIndex=1;
    }
 };
 
function setsupp(){  
 $("#paydetbx").html('');
document.getElementById('rtype').value="INSURANCE";
$('#repono').hide();
$('#supp').show();
$('#ecatbx').hide();
document.getElementById('repono').value="0";
document.getElementById('supselbut').value="1";
document.getElementById('ordselbut').value="0";
document.getElementById('ecat').value="";
};

function setord(){  
 $("#paydetbx").html('');
document.getElementById('rtype').value="REPOSESSION";
$('#repono').show();
$('#supp').hide();
$('#ecatbx').show();
document.getElementById('supp').value="0";
document.getElementById('supselbut').value="0";
document.getElementById('ordselbut').value="1";
};
 
function paydets(){
if( $("#paydetstab").length !== 0) { $("#paydetstab").remove(); };
if($('#rtype').val() === "INSURANCE"){
var ttt = $.get( "paydets.php?s="+$('#supp').val()+"&r="+$('#rtype').val(), function(data) {
                   $("#paydetbx").html(data);
                });
	}
else { $("#paydetbx").html(''); }	
};

</script>



