<?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;}
#regform {
text-align: left;
width:90%;
margin: 5px; padding-left:5px; padding-right:5px;
border: 1px solid #666; 
background: #FFD47F;
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>        
 $(document).ready(function() { 
$('#chks').hide();
$('#cname').autocomplete({ source: <?php echo allcustomers(); ?>, minLength: 2  });


$("#btnaddrecp").click(function(e) {
e.preventDefault();
var ttt = $("#pmode :selected").val();
var rtype = $("#rtype :selected").val();
if( $('#rdate').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 = "-";}
    if($("#rdate").val()!== null) { var rchequedate = $("#rdate").val();} else {  var rchequedate = "0000-00-00";}
    if($("#chqdet").val()!== null) { var chequedetail = $("#chqdet").val();} else {  var chequedetail = ".";}
   
    var jqxhrposts = $.post("recpsav.php?newreceipt="+$("#recpno").val()+"&rdate="+$('#rdate').val()+"&pmode="+ttt+"&am="+ramount+"&chqno="+chequeno+"&chqdet="+chequedetail+"&rmks="+vrmk+"&rtype="+rtype+"&bacc="+bacc+"&cname="+$('#cname').val()+"&ina="+$('#invarr').val()+"&pya="+$('#payarr').val(), function(data) {
                    if (data.trim() ==="nothing"){ $(".validateTips3").html("<font size='2' color='red'><center>Error in creating Receipt!</center></font>"); }
                    else { $(".validateTips3").html("<font size='2' font-weight:bold color='green'><center>Successfully Created!</center></font>");
                         // window.location.replace('recprint.php?rd='+rchequedate+'&am='+ramount+'&rtype='+rtype+'&chk='+chequeno+' - '+chequedetail+' - '+bacc+'&pmode='+ttt+'&rmks='+vrmk+"&cname="+$('#cname').val());    
						 if($("#recpno").val() ==='0') { alert('Saved with Receipt No.'+data); }
						 window.close();
                          }
                          
                          });
                          
    }                    
});
 });
 
 function suminvams() {                     			 // on selecting
    var tot = 0; 	var ina = "";  	var paya = "";
    var tp = document.getElementsByName('topay');
	var ip = document.getElementsByName('invno');
    for(var i=0;i<tp.length;i++){ 
        var avwc = tp[i].value;
        var aa = parseFloat(avwc);
        if(aa !== 0) { tot += aa;
				   paya += tp[i].value + ">";
				   ina += ip[i].value + ">";	
		 }  
        
     };   
     document.getElementById('am').value = tot;
	 document.getElementById('payarr').value = paya;
	 document.getElementById('invarr').value = ina;
 };
    

</script>
<?php  
if($_REQUEST['e'] === "0"){
	$cname = '';
	$rdate = date("d-m-Y");
	$pmode = '';
	$chqno = '';
	$chqdet = '';
	$am = '0';
	$rmks = '';
    $bacc = '';
	$rtype = '';
	$recpno = 0;
}
else {
	$recpno = $_REQUEST['recpno'];
	require_once 'includes/database.php';

	$db=new MySQLDatabase();
	$db->open_connection();
	$query = "SELECT * FROM recptrans WHERE recpno = '$recpno';";
	$result = mysqli_query($db->connection, $query) or die(mysqli_error($db->connection) );
	if ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
		$cname = $row['cname'];
		$rdate = substr($row['rdate'],8,2)."-".substr($row['rdate'],5,2)."-".substr($row['rdate'] ,0,4);
		$pmode = $row['pmode'];
		$chqno = $row['chqno'];
		$chqdet = $row['chqdet'];
		$am =$row['amount'];
		$rmks = $row['rmks'];
        $bacc = $row['bacc'];
		$rtype = $row['rtype'];
	}
	else { echo '<script type="text/javascript"> window.close();</script>';}
	$db->close_connection();
}
?>   
</head><body>
<p class="titletr"> <?php echo ($_REQUEST['e'] !== "0") ? 'Edit Receipt No.'.$recpno : 'New Receipt'; echo str_repeat('&nbsp;', 60); ?><a href="#"><img src="images/close.png" onclick="window.close();"> </a></p>       
<form id="regform" method="post" onkeypress="return event.keyCode!=13" action="#" >
                    <center>
                    <p id="validaterecp" class="validateTips3">  All fields are required!</p>    
                    <table cellspacing="5px" id="lladdbox">
                    <tr><td align="left"><label for="rdate"> Receipt Date &nbsp;</label></td>
                    <td><input type="text" id="rdate" name="rdate" value="<?php echo $rdate; ?>" size="20"required="required"/> <input type="hidden" id="recpno" name="recpno" value= "<?php echo $recpno; ?>"> </td>
                    </tr>     
                    <tr><td align="left"><label for="cname">Customer Name &nbsp; </label></td>
                    <td><select id="cname" name="cname" <?php if ($_REQUEST['e'] === '1') { echo 'disabled="disabled"';} ?> ><?php echo '<option value="'.$cname.'" selected>'.$cname.'</option>'; echo selcus(); ?></select>  </td>
                    </tr>    
					<tr><td align="left"><label for="rtype"> Type &nbsp;</label></td>
                    <td><select id="rtype" name="rtype" onchange="recpdets();" <?php if ($_REQUEST['e'] === '1') { echo 'disabled="disabled"';} ?> style="width:160px; height:20px;" required="required" ><?php echo '<option value="'.$rtype.'" selected>'.$rtype.'</option>'; ?> <option value="INSURANCE">INSURANCE</option> <option value="OTHERS">OTHERS</option> <option value="REPOSESSION">REPOSESSION</option> <option value="TRACKER">TRACKER</option> </select></td>
                    </tr>
					<tr><td colspan="2"> <div id="recpdetbx"> 
					<?php if ($_REQUEST['e'] === '1') {
							$db=new MySQLDatabase();
							$db->open_connection();
							if( $rtype === "INSURANCE"){ $qrystr = "SELECT insinvoices.idate, insinvoices.invno, CONCAT(insrecs.insno,'- ',insrecs.regno,'-',insrecs.vehmod,' -',insrecs.insurer) as nar, insinvoices.amount, insinvoices.paidamount FROM insinvoices, insrecs WHERE insinvoices.insno = insrecs.insno AND insinvoices.cname = '$cname' AND (insinvoices.recpno=0 OR insinvoices.recpno='$recpno') 
							UNION SELECT insinvoices.idate, insinvoices.invno, 'CREDIT' as nar, -1*insinvoices.amount, -1*insinvoices.paidamount FROM insinvoices WHERE insinvoices.invoicecredit=0 AND insinvoices.cname = '$cname' AND (insinvoices.recpno=0 OR insinvoices.recpno='$recpno');"; }
							elseif( $rtype === "TRACKER") { $qrystr = "SELECT trackinvoices.idate, trackinvoices.invno, CONCAT(jcards.jcno,'- ',jcards.regno,'-',jcards.vehmod) as nar, trackinvoices.amount, trackinvoices.paidamount FROM trackinvoices, jcards WHERE trackinvoices.invno = jcards.invno AND trackinvoices.cname = '$cname' AND (trackinvoices.recpno=0 OR trackinvoices.recpno='$recpno') 
							UNION SELECT trackinvoices.idate, trackinvoices.invno, 'CREDIT' as nar, -1*trackinvoices.amount, -1*trackinvoices.paidamount FROM trackinvoices WHERE trackinvoices.invoicecredit=0 AND trackinvoices.cname = '$cname' AND (trackinvoices.recpno=0 OR trackinvoices.recpno='$recpno');"; }
							elseif( $rtype === "REPOSESSION") { $qrystr = "SELECT repoinvoices.idate, repoinvoices.invno, repoinvoices.nar as nar, repoinvoices.amount, repoinvoices.paidamount FROM repoinvoices WHERE repoinvoices.cname = '$cname' AND (repoinvoices.recpno=0 OR repoinvoices.recpno='$recpno')
							UNION SELECT repoinvoices.idate, repoinvoices.invno, 'CREDIT' as nar, repoinvoices.amount, repoinvoices.paidamount FROM repoinvoices WHERE repoinvoices.invoicecredit=0 AND repoinvoices.cname = '$cname' AND (repoinvoices.recpno=0 OR repoinvoices.recpno='$recpno');"; }	
							elseif( $rtype === "OTHERS") { $qrystr = "SELECT othinvoices.idate, othinvoices.invno, othinvoices.nar as nar, othinvoices.amount, othinvoices.paidamount FROM othinvoices WHERE othinvoices.cname = '$cname' AND (othinvoices.recpno=0 OR othinvoices.recpno='$recpno')
							UNION SELECT othinvoices.idate, othinvoices.invno, 'CREDIT' as nar, othinvoices.amount, othinvoices.paidamount FROM othinvoices WHERE othinvoices.invoicecredit=0 AND othinvoices.cname = '$cname' AND (othinvoices.recpno=0 OR othinvoices.recpno='$recpno');"; }
							$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['invno']."</td> <td>".$nd." <input type='hidden' id='invno' name='invno' value='".$row['invno']."'/></td> <td align='left'>".$row['nar']."</td> <td>".$row['amount']."</td> <td><input class='pdamsjust' type='text' id='topay' name='topay' onchange='suminvams();' size='5' value='".$row['paidamount']."'/></td> </tr>";
							}
							echo "</table>";
							$db->close_connection();
							}
							
						?>   
					</div></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.'" selected>'.$pmode.'</option>'; ?> <option value="CASH">CASH</option><option value="CHEQUE">CHEQUE</option><option value="MPESA">MPESA</option></select></td>
                    </tr>

                    <tr><td colspan="2" id="chks" align="left"><label for="chqno"> Cheque No. &nbsp;</label> &nbsp;<input type="text" id="chqno" name="chqno" value="<?php echo $chqno; ?>" size="5"> &nbsp; &nbsp;<label for="chqdet"> Cheque Details. &nbsp;</label> &nbsp;<input type="text" id="chqdet" name="chqdet" value="<?php echo $chqdet; ?>" size="10"></td>
                    </tr>    
                    <tr><td align="left"><label for="am"> Amount &nbsp;</label></td>
                    <td><input type="text" id="am" <?php if ($_REQUEST['e'] === '1') { echo 'disabled="disabled"';} ?> name="am" value="<?php echo $am; ?>" size="20" required="required"/></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"> Banked at &nbsp;</label></td>
                    <td><select id="bacc" style="width:200px;" name="bacc"> <?php echo '<option value="'.$bacc.'" selected>'.$bacc.'</option>'; echo selallbanks(); ?> </select></td>
                    </tr>
                    <br />
                    <tr><td colspan=2 align="center"><input type="submit" id="btnaddrecp" name="btnaddrecp"  class="text ui-widget-content ui-corner-all" value=" Save Receipt " style="width:160px;font-weight:bold; "/></td>
                    </td></tr>
                    </table></center>
                    </form>
    </body>
</html>

<script type="text/javascript">
$("#rdate").datepicker({ changeMonth: true, changeYear: true, dateFormat: "dd-mm-yy"});     
                                                               // 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 recpdets(){
if( $("#recpdetstab").length !== 0) { $("#recpdetstab").remove(); };
var ttt = $.get("recpdets.php?c="+$('#cname').val()+"&r="+$('#rtype').val(), function(data) {
                   $("#recpdetbx").html(data);
                });			
};
</script>



