<?php
if(basename($_SERVER['PHP_SELF']) == 'bulkpay.php') 
  $fn=" class='current'";
$custo=$conde=$condi='';
include'connection.php';
$dato=$datos=$Date;
$dati=$Date;
$p=$i=0;

include'header.php';

// Search for data by date
if(isset($_POST['search']))
		{
			$dato=$_POST['dato'];
			$datos=$_POST['datos'];
			$custo=$_POST['custo'];
				$p=1;
		}

// call to pay all by vehicle selection
if(isset($_POST['payall']))
		{
			$dato=$_POST['dato'];
			$datos=$_POST['datos'];
			$custo=$_POST['custo'];
			$p=$_POST['p'];
			$n=$_POST['n'];
	$den=mysqli_query($conn, "UPDATE `services` SET `Checked`='0' WHERE `Checked`!='0' ORDER BY `Number` ASC LIMIT 10");
	
	while($n>0){
	    if($_POST["sel$n"]){
	$den=mysqli_query($conn, "UPDATE `services` SET `Checked`='1' WHERE `Number`='".$_POST["pay$n"]."' ORDER BY `Number` ASC LIMIT 1");
	            $j++;
	    }
	
	        $n--;
	        }
		}

    // Add a payment to supplier
if(isset($_POST['addpall']))
		{
			$dato=$_POST['dato'];
			$datos=$_POST['datos'];
			$custo=$_POST['custo'];
			$date=$_POST['dati'];
			$amo=$_POST['amo'];
			$amo=str_replace(',', '', $_POST['amo']);
			$pline=$_POST['pline'];
			$invo=$_POST['invo'];
			$currency=$_POST['currency'];
			$count=$_POST['count'];
			$naso=$_POST['naso'];
			$accu=$_POST['accu'];
			$dest=$_POST['dest'];
			$p=$_POST['p'];
			$j=$_POST['j'];
			$last_id=0;
			$s=1;

		$doi=mysqli_query($conn, "SELECT `Rate` FROM `currency` WHERE `Code`='$currency' ORDER BY `Number` DESC");
			$roi=mysqli_fetch_assoc($doi);
				$rate=$roi['Rate'];

			$pieces = explode("-", $pline);
				$pline = $pieces[0]; // piece1
				$cheno=$bank='';
				$pdate=$_POST['dati'];

	$temp1 = explode(".", $_FILES["file1"]["name"]);
$newfilename1 = round(microtime(true)) . '.' . end($temp1);
move_uploaded_file($_FILES["file1"]["tmp_name"], "files/" . $newfilename1);
	if(!end($temp1))
	    $newfilename1='';
			
		if($pline=='CHEQUE'){
			$cheno=$_POST['cheno'];
			$bank=$_POST['bank'];
			$pdate=$_POST['pda'];
			$classe=$_POST['classec'];
		}
		if($pline=='TRANSFER'){
			$cheno=$_POST['slino'];
			$bank=$_POST['bacco'];
			$pdate=$_POST['tda'];
			$classe=$_POST['classet'];
		}
		
		if($pline=='CHEQUE' OR $pline=='TRANSFER'){
	$doi=mysqli_query($conn, "SELECT `Number`, `Rate` FROM `baccount` WHERE `Account`='$bank' ORDER BY `Number` ASC");
				$roi=mysqli_fetch_assoc($doi);
					$acco=$roi['Number'];
					$dra=$roi['Rate'];
                        $ope="WITHDRAWAL";
                            $bra=0;
                        $source=$pline;
                $purpo="Service Provider Payment";
                        $depo=$amo;
					
$and=mysqli_query($conn, "INSERT INTO `deposit` (`Number`, `Date`, `Time`, `User`, `Item`, `Refer`, `Amount`, `Customer`, `Operation`, `Status`, `Valid`, `Account`, `Descri`, `Client`, `Voucher`, `Source`, `Record`, `Branche`, `Bank`, `Rate`) VALUES (NULL, '$pdate', '$Time', '$loge', 'PAYMENT', 'x2', '$depo', '$dest', '$ope', '0', '0', '$acco', '$purpo', '0', '$naso', '$source', '0', '$bra', '$bank', '$dra')");
    $last_id = mysqli_insert_id($conn);

    if($classe)
$cl=mysqli_query($conn, "INSERT INTO `expenses` (`Date`, `Time`, `User`, `Type`, `Purpose`, `Amount`, `Store`, `Payment`, `Payto`, `Status`, `Invoice`, `Classfy`, `Expense`, `Service`, `External`, `Rate`) VALUES ('$date', '$Time', '$loge', 'PAYMENT', '$purpo', '$depo', 'REMERA', '$pline', '$dest', '0', '$invo', 'EXPENSE', '$classe', '$naso', '1', '$rate')");
		}
		
		if($pline=='PAYOUT'){
			$payout=$_POST['payout'];
			$classe=$_POST['classe'];
			
	$sso=mysqli_query($conn, "UPDATE `expenses` SET `Classfy`='EXPENSE', `Invoice`='$invo', `Payto`='$dest', `Expense`='$classe', `Service`='$naso' WHERE `Number`='$payout'");
		}
		
		$purpo="Supplier bulk payment";
		
		$dok=mysqli_query($conn, "SELECT `Number`, `Amount`, `Rate`, `Paid` FROM `services` WHERE `Status`='0' AND `Date` BETWEEN '$dato' AND '$datos' AND `Supplier`='$custo' ORDER BY `Date` ASC");
		while($rok=mysqli_fetch_assoc($dok)){
		    $naso=$rok['Number'];
		    $am=($rok['Amount']*$rok['Rate'])-$rok['Paid'];
        if($am<($amo*$rate))
            $ami=($am/$rate);
        else
            $ami=$amo;
		
	$so=mysqli_query($conn, "INSERT INTO `payment` (`Date`, `Time`, `User`, `Amount`, `Pline`, `Invoice`, `Status`, `Customer`, `Action`, `Descri`, `Destin`, `Cheno`, `Bname`, `Pdate`, `Container`, `Currency`, `Rate`, `Files`, `Linked`) VALUES ('$date', '$Time', '$loge', '$ami', '$pline', '$naso', '0', '$dest', 'SUPPLIER', '', '', '$cheno', '$bank', '$pdate', '', '$currency', '$rate', '$newfilename1', '$last_id')");
	                if($am>($amo*$rate))
	                   break;
	                   
	        $amo-=($am/$rate);
		}
		}


        if($dato==$datos)
			$mpri="ON $dato";
		else
			$mpri="FROM $dato TO $datos";
			
			$af="CREATE A NEW SERVICE";
		
		    
		    if($j)
		$conds="AND `Checked`='1'";
?>


<div class="container-fluid main-content">
        <div class="page-title hidden-print">
          <h3 style='margin-top:-20px; margin-bottom: 5px; color:#ffcc33'>
         Finance
          </h3>
                 </div>
     
        <div class="row">
  <div class="col-lg-2 hidden-print">
   
  <ul class="list-group">   

    <li class="list-group-item">
	  <a href="custrepo.php">
                <p>
                <i class="lnr lnr-menu-circle"></i>&nbsp;Pay on Account
                </p>
              </a></li> 

    <li class="list-group-item">
	  <a href="salesrepo.php">
                <p>
                <i class="lnr lnr-menu-circle"></i>&nbsp;Sales Report
                </p>
              </a></li>   

    <li class="list-group-item">
	  <a href="purchase.php">
                <p>
                <i class="lnr lnr-menu-circle"></i>&nbsp;Purchase Orders
                </p>
              </a></li>   

    <li class="list-group-item active">
	  <a href="trans.php">
                <p>
                <i class="lnr lnr-menu-circle"></i>&nbsp;Service Providers
                </p>
              </a></li> 

    <li class="list-group-item">
	  <a href="experepo.php">
                <p>
                <i class="lnr lnr-menu-circle"></i>&nbsp;Payout/Expenses
                </p>
              </a></li>  

    <li class="list-group-item">
	  <a href="zreport.php">
                <p>
                <i class="lnr lnr-menu-circle"></i>&nbsp;Daily Z-Report
                </p>
              </a></li>  

    <li class="list-group-item">
	  <a href="taxrepo.php">
                <p>
                <i class="lnr lnr-menu-circle"></i>&nbsp;VAT/TAX Report
                </p>
              </a></li>    

    <li class="list-group-item">
	  <a href="assets.php">
                <p>
                <i class="lnr lnr-menu-circle"></i>&nbsp;Assets Report
                </p>
              </a></li>  
                         
            </ul>
  </div>
                    
           
        <div class="col-lg-10">
                  <div class="row">

				  <div class="col-lg-4 text-info text-center" style="font-size:16px; font-weight:bold;"> BULK &nbsp; PAYMENT </div>         
            

        <form action="" method="post" class="form-horizontal ">                  
    <div class="col-lg-8 hidden-print" style="padding-right:50px;">
                           
     <div class="col-lg-4 hidden-print"> 
     
			<select class="form-control" name="custo">
		<option value='' selected='selected'>SELECT A SUPPLIER</option>
			 <?php
$doix=mysqli_query($conn, "SELECT `Supplier` FROM `services` WHERE `Status`='0' AND `Supplier`!='' GROUP BY `Supplier` ORDER BY `Supplier` ASC");
			while($roix=mysqli_fetch_assoc($doix)){
				$desto=$roix['Supplier'];
				if($desto==$custo)
					$sle="selected='selected'";
				else
					$sle='';
			echo"<option value='$desto' $sle> $desto </option>";
			}
			?>    
                            </select>
			</div>      
			
             <div class="col-lg-3"> 
           <div class="input-group date" data-provide="datepicker">
      <input class="form-control form-center" id="from" name="dato" type="text" value="<?php echo $dato ?>" onkeypress='return isNumberKey(event)' required>
	  <span class="input-group-addon"><i class="lnr lnr-calendar-full"></i></span>
			</div></div>


		  <div class="col-lg-3"> 
           <div class="input-group date" data-provide="datepicker">	
      <input class="form-control form-center" id="to" name="datos" type="text" value="<?php echo $datos ?>" onkeypress='return isNumberKey(event)' required>
	  <span class="input-group-addon"><i class="lnr lnr-calendar-full"></i></span>
              </div></div>                     
                       
                       <div class="col-lg-2"><?php echo"<input type='hidden' name='pg' value='$pg'>"; ?>
                        <button class="btn  btn-primary btn-block" type="submit" name="search"><i class="lnr lnr-magnifier"></i> Search</button>
                   
					  </div>
                         </div></form> 
                         
    <script type="text/javascript">
var boxcounter;
$(function() {
    boxcounter = 0;
    $(".checkbox").click(function() {
        if(this.checked) {
            counter++;
            if(counter == 1){
                $(".delete").attr("disabled", "");
            }
        } else {
            counter--;
            if(counter == 0){
                $(".delete").attr("disabled", "disabled");
            }
        }
    }
}
        </script>
               
            </div>
            
               <?php
        if($custo)
            $conde="AND `Supplier` = '$custo'";
        
				if($p)
		$dok=mysqli_query($conn, "SELECT *FROM `services` WHERE `Status`='0' AND `Date` BETWEEN '$dato' AND '$datos' $conde $conds ORDER BY `Date` ASC");
				else
		$dok=mysqli_query($conn, "SELECT *FROM (SELECT *FROM `services` WHERE `Status`='0' ORDER BY `Date` DESC LIMIT 15) SUB ORDER BY `Date` ASC");
				if($fo=mysqli_num_rows($dok)){
				?>
					<div class="divFooter"><center><u><b>SUPPLIER PAYMENT REPORT <?php echo"$mpri"; ?></b></u></center></div>
		 <div class="row">
            <div class="col-lg-12">
             <span> &nbsp;&nbsp; Total Records Found : <b><?php echo" $fo " ?></b></span>
			 <span class="pull-right hidden-print">
			 &nbsp;&nbsp;&nbsp;&nbsp;<a href="#" onclick="return window.print()" class="hidden-print" title='Click to print' data-toggle='tooltip' data-placement='top'><i class="lnr lnr-printer"></i></a></span>
			 
			  <span class="pull-right hidden-print">
			 &nbsp;&nbsp;&nbsp;&nbsp;<a href="#" onclick="exportTableToExcel('inco_Data')" class="hidden-print" title='Export to excell' data-toggle='tooltip' data-placement='top'><i class="lnr lnr-line-spacing"></i></a></span>
            <div class="widget-container fluid-height clearfix">
            <div class="widget-content padded clearfix">
    
 <script type="text/javascript">
function UpdateCost() {
  var sum = 0;
  var gn, elem;
  for (i=1; i<=<?php echo $fo ?>; i++) {
    gn = 'sum_m_'+i;
    elem = document.getElementById(gn);
    if (elem.checked == true) { sum += Number(elem.value); }
  }
  document.getElementById('totalcost' ).value = sum.toFixed(0);
}
window.onload=UpdateCost
</script>

			 <table class="table table-striped table-hover" id="inco_Data">     
                         <thead><tr role="row">
                    
            <th width="3%" style='padding:1px; text-align:center'> No </th>
			<th style="adding:1px;"><div align='center'>&nbsp;&nbsp;&nbsp;&nbsp;DATE&nbsp;&nbsp;&nbsp;&nbsp;</th>
	        <th style='padding:1px;'><div align='center'> SUPPLIER </th>
			<th width='10%'><div align='center'> INVOICE </th>
			    <th><div align='center'> PURPOSE </th>
				<th style='padding:1px;'><div align='center'> VAT </th>
				<th style='padding:1px;'><div align='center'> TAX </th>
				<th colspan='2' style='padding:1px;'>
				    <div align='center'> AMOUNT </th>
				<th style='padding:1px;'><div align='center'> PAID </th>
				<th colspan='2' style='padding:1px;'><div align='center'> BALANCE </th><th class="hidden-print text-center" width="1%"> # </th></tr></thead><tbody>
					<?php
			if($custo)
		echo"<form action='' method='post'>";
					
					 $cat=$exp=array();            $s=1;
    $doi=mysqli_query($conn, "SELECT `Type` FROM `expetype` GROUP BY `Type` ORDER BY `Number` ASC");
			while($roi=mysqli_fetch_assoc($doi)){
				$fna=$roi['Type'];
            	$cat[$s]=$fna;  
            	$s++;
	    
	$doe=mysqli_query($conn, "SELECT `Expense` FROM `expetype` WHERE `Type`='$fna' GROUP BY `Expense` ORDER BY `Expense` ASC");
			while($roe=mysqli_fetch_assoc($doe)){
				$expe=$roe['Expense'];
                $exp[$s]=$expe;              $sp=$s;   	            $s++;                
			}
		}
		           
			
				$i++;			$tot=$tpa=$tba=$tva=$tta=0;
		while($rok=mysqli_fetch_assoc($dok)){
				$code=$rok['Number'];
				$dati=$rok['Date'];
				$name=$rok['Supplier'];
			$invo=$rok['Invoice'];
	$amo=($rok['Amount']*$rok['Rate']);			$amoo=number_format($amo, 2);
			$curre=$rok['Currency'];
			$curr=$rok['Currency'];
			$purpo=$rok['Purpose'];
			$tam=number_format($rok['Amount']);
			$vat=$rok['Vat'];                   $vato=number_format($vat, 2);
			$tax=$rok['Holdings'];               $taxo=number_format($tax, 2);
			$dst=$name;
			$us="RWF";
			$pay=0;
if($rok['Checked'])
$chk="checked";
else
$chk="";
					
			// ************************* Paid Amount *************
    $sca=mysqli_query($conn, "SELECT SUM(`Amount`*`Rate`) AS 'Pay' FROM `payment` WHERE (`Invoice` = '$code' AND `Status`='0' AND `Action`='SUPPLIER') OR (`Invoice` = '$code' AND `Status`='0' AND `Action`='SUPPLIER' AND `Voucher`='$vous') ORDER BY `Number` ASC");
				$rca=mysqli_fetch_assoc($sca);
					$pay+=$rca['Pay'];
					
	$sso=mysqli_query($conn, "SELECT SUM(`Amount`) AS `Pas` FROM `expenses` WHERE `Service`='$code' AND `Status`='0' AND `External`='0'");
				$rso=mysqli_fetch_assoc($sso);
					$pay+=$rso['Pas'];
					
					$bal=$amo-$pay-$tax;							
					$btn=$clr="";
					
						if($pay)
						$lin="<a href='#' data-toggle='modal' data-target='#exampleModal$i'>";
					else
						$lin="";

					$balo=number_format($bal, 2);							
					$payo=number_format($pay, 2);
					$stl="padding:1px; font-size:11px;";

	print("<tr><td style='$stl $clr'><div align='right'>&nbsp;$i&nbsp;</td>
	<td style='$stl $clr'><div align='center'> $dati </td>
	<td style='$stl $clr'> $name </td><td style='$stl $clr'> $invo </td>
	<td style='$stl $clr'> $purpo </td>
	<td style='$stl $clr'><div align='right'> $vato </td>
	<td style='$stl $clr'><div align='right'> $taxo </td>
	<td style='$stl $clr'><div align='right'> $amoo </td>
	<td style='$stl $clr'> $us </td>
	<td style='$stl $clr'><div align='right'>$lin $payo </a></td>
	<td style='$stl $clr'><div align='right'> $balo </td><td class='text-right' style='$stn $clr'>");
	
	$doin=mysqli_query($conn, "UPDATE `services` SET `Paid` = '$pay' WHERE `Number` = '$code' ORDER BY `Number` DESC");

    if($_SESSION['Cfr']){
	    $dbutn='submit';
	    $disa='';
	}
	else{
	    $dbutn='button';
	    $disa='disabled';
	}
	
	if($_SESSION['Cpd']){
	    $dbl='';
	}
	else{
	    $dbl='disabled';
	}
	
	$af="EDIT A GIVEN SERVICE";

//	include'addpaid.php';            
//	include'transp.php';        //      include'paymodal.php';
	
	           	
		if($custo)
		    echo"<td align='right' style='width:20px; padding:0px;'><input class='form-control' name='sel$i' type='checkbox' value='$bal' $chk style='margin:1px; width:30px; height:18px;' class='checkbox'  onclick='UpdateCost()' id='sum_m_$i'><input type='hidden' value='$code' name='pay$i'></td>";
		else
			echo"<td align='right' style='width:20px; padding:0px;'><input class='form-control' name='cel$i' type='checkbox' value='0' $chk style='margin:1px; width:30px; height:18px;' class='checkbox'  onclick='UpdateCost()' id='sum_m_$i' disabled readonly></td>";
		
	            print"</tr>";
		$i++;				$tot+=$amo;             $tpa+=$pay;      
		$tba+=$bal;                     $tva+=$vat;             $tta+=$tax;
						}
			$tot=number_format($tot, 2);			
			$tpa=number_format($tpa, 2);					
			$tba=number_format($tba, 2);					
			$tva=number_format($tva, 2);					
			$tta=number_format($tta, 2);
						?>
						
                    </tbody>
					 <thead>
					<tr><th> </th><th colspan='4'><div align='center'> TOTAL AMOUNT </th>
					<th style="padding-right:1px;"><div align='right'><?php echo $tva ?></th>
					<th style="padding-right:1px;"><div align='right'><?php echo $tta ?></th>
					<th style="padding-right:1px;"><div align='right'><?php echo $tot ?></th>
					<th style="padding-right:1px; padding-left:1px;"><?php echo $us ?></th>
					<th style="padding-right:1px;"><div align='right'><?php echo $tpa ?></th>
					<th style="padding-right:1px;"><div align='right'><?php echo $tba ?></th></th>
	    <th class='hidden-print' style='padding:2px' colspan='2'><center> -- </th></tr></thead></table>
	
	<?php
	    if($custo AND $j==0){
	 echo"<input type='hidden' name='dato' value='$dato'>
	  <input type='hidden' name='datos' value='$datos'>
	  <input type='hidden' name='custo' value='$custo'>
	  <input type='hidden' name='n' value='$i'>
	  <input type='hidden' name='p' value='$p'>
 <button type='submit' class='btn btn-sm btn-info pull-right' style='width:180px; height:28px; margin-right:10px; margin-left:10px;' name='payall' class='delete'><i class='lnr lnr-briefcase'></i> &nbsp;&nbsp; PAY&nbsp;SELECTED </button> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input class='form-control text-right pull-right' type='text' name='sen' id='totalcost' value='' onchange='format(this);' style='width:160px; border:0px; font-size:24px; margin-right:10px; margin-left:10px; height:28px;'></form>";
	    }
	    if($j){
        	   echo"<script>
    $('#myModal').modal({ show : true });
                </script>";
                
	   $line="<div><div><div><div style='padding:0px; 
	   margin-top:30px; border:1px solid #D8D7D6; border-radius:5px;'>
      <div class='modal-header' style='margin-bottom:40px; margin-top:0px;'>
        <h5 class='modal-title' id='exampleModalLabel'>ADD A PAYMENT 
    <label class='pull-right'><b>$dst : &nbsp;$tba</b>
            </label></h5>

      </div>
	   
      <div style='text-align:center; height:auto; width:80%;'>
      <form action='' method='post' enctype='multipart/form-data'>";
					include'addpall.php';
		echo"</div>";
	    }
	    ?>
                  
                                      
                
              </div>
            </div></div>
                  </div>                  
                <span class="pull-right hidden-print">
			 &nbsp;&nbsp;&nbsp;&nbsp;<a href="#" onclick="return window.print()" class="hidden-print" title='Click to print' data-toggle='tooltip' data-placement='top'><i class="lnr lnr-printer"></i></a></span>
			 <span class="pull-right hidden-print">
			 &nbsp;&nbsp;&nbsp;&nbsp;<a href="#" onclick="exportTableToExcel('inco_Data')" class="hidden-print" title='Export to excell' data-toggle='tooltip' data-placement='top'><i class="lnr lnr-line-spacing"></i></a></span>
      
   </div></div></div>  
   <?php
				}
    $setri=mysqli_query($conn, "DELETE FROM `income` WHERE `Amount`='0' ORDER BY `Number` ASC LIMIT 2");
    $setri=mysqli_query($conn, "DELETE FROM `payment` WHERE `Amount`='0' ORDER BY `Number` ASC LIMIT 2");
   include'footer.php';
   ?>