<?php
session_start();
error_reporting(0);
@ini_set('display_errors', 0);
$id_user=$_SESSION['id'];
$branch=$_SESSION['branch_id'];
$business=$_SESSION['business_id'];
?>
<!DOCTYPE html>
<html>
    
    <head><meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		     <?php include("../includes/header-links.php");
$permissions = mysqli_fetch_array(mysqli_query($con,"SELECT * FROM  
  permissions,users WHERE  permissions.role_id = users.role 
  AND users.id='$id_user' AND users.business_id ='$business' AND users.branch_id ='$branch'"));

if($permissions['view_cash_analysis'] != 1){
?>
<script>window.location="../main/dashboard.php"</script>
<?php
}
?>
    <link href="../bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
        <link href="../bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" media="screen">
        <link href="../assets/styles.css" rel="stylesheet" media="screen">
        <link href="../assets/DT_bootstrap.css" rel="stylesheet" media="screen">
        <link rel="stylesheet" href="../data-table-css/bootstrap-table.css">
    <link rel="stylesheet" href="../data-table-css/bootstrap-editable.css">
        <!--[if lte IE 8]><script language="javascript" type="text/javascript" src="vendors/flot/excanvas.min.js"></script><![endif]-->
        <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
        <!--[if lt IE 9]>
            <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
        <script src="../vendors/modernizr-2.6.2-respond-1.1.0.min.js"></script>
    </head>
    
    <body>
        <script type="text/javascript">
    function FormatCurrency(ctrl) {
                  //Check if arrow keys are pressed - we want to allow navigation around textbox using arrow keys
                  if (event.keyCode == 37 || event.keyCode == 38 || event.keyCode == 39 || event.keyCode == 40) {
                      return;
                  }

                  var val = ctrl.value;

                  val = val.replace(/,/g, "")
                  ctrl.value = "";
                  val += '';
                  x = val.split('.');
                  x1 = x[0];
                  x2 = x.length > 1 ? '.' + x[1] : '';

                  var rgx = /(\d+)(\d{3})/;

                  while (rgx.test(x1)) {
                      x1 = x1.replace(rgx, '$1' + ',' + '$2');
                  }

                  ctrl.value = x1 + x2;
              }

              function CheckNumeric() {
                  return event.keyCode >= 48 && event.keyCode <= 57 || event.keyCode == 46;
              }
</script>
        <?php include '../includes/header.php'; 
//if($_SESSION['role']=="Super Admin") {
        //if($branch==0 && $business !=0){
        if($permissions['business_id'] != 0 && $permissions['branch_id']==0){

        $sql_cash = mysqli_query($con,"SELECT sum(total_price)as totalsales,sum(paid)as totalpaid ,(select sum(amount) from cash_out where business_id=$business) as totalcashout,(select sum(amount) from expenses where business_id=$business) as totalexpenses  FROM sales where business_id='$business'");
      }else{
        $sql_cash = mysqli_query($con,"SELECT sum(total_price)as totalsales,sum(paid)as totalpaid ,(select sum(amount) from cash_out where branch_id=$branch) as totalcashout,(select sum(amount) from expenses where branch_id=$branch) as totalexpenses  FROM sales where branch_id='$branch'");
      }
        if (mysqli_num_rows($sql_cash)>0) {
          $row=mysqli_fetch_array($sql_cash);
          $totalsales=$row['totalsales'];
          $totalpaid=$row['totalpaid'];
          $totalcashout=$row['totalcashout'];
          $totalexpenses=$row['totalexpenses'];

        }else{

          $totalsales=0;
          $totalpaid=0;
          $totalcashout=0;
          $totalexpenses=0;
        }
       $totaldebts=$totalsales-$totalpaid;
       $cash_at_hand=$totalsales-($totalexpenses+$totaldebts+$totalcashout);
        ?>
        <div class="container-fluid">
            <div class="row-fluid">
                <?php include '../includes/sidebar.php'; ?>
                <!--/span-->
                <div class="span10" id="content">

                     <div class="row-fluid">
                        <!-- block -->
                        <div class="block">

                            <div class="navbar navbar-inner block-header">
                                    <?php
                        if( $permissions['add_cash_out'] == 1){
                            ?>
                                
                                <div class="muted pull-right" >
                                         <a href="#myModal" data-toggle="modal" class="btn btn-primary"><i class="icon-plus icon-white"></i>&nbsp;Add Cash out</a>
                                      </div>
                                      <?php
                         }
                         ?>

                                      <span>Cash Out Analysis  
                                                 <?php
                        if( $permissions['cash_at_hand'] == 1){
                            ?>
                                      <h2 style="color: blue;">Current Cash At Hand <?php echo number_format($cash_at_hand); ?></h2>
                                      <?php
                                    }
                                      ?>
                                    </span>
                            </div>
                            <div class="block-content collapse in">
                                <div class="span12">

                                      <!--Model begins here -->
                                      <div id="myModal" class="modal hide">
											<div class="modal-header" style="background: #08c; color: white; text-align: center;">
												<button data-dismiss="modal" class="close" type="button">&times;</button>
												<h3>Add New Cash out</h3>
											</div>
											<div class="modal-body">
												<form action="" method="POST">
												<label style=" font-size: 20px; ">Date</label>
												<input type="date" name="date" class="form-control" value="<?php echo date('Y-m-d');?>" required style="width: 
                        95%; height: 30px; font-size: 20px;">
                         <label style=" font-size: 20px; "> Amount </label>
                        <input type="text" onkeypress="return CheckNumeric()" onkeyup="FormatCurrency(this)" name="amount" class="form-control"   style="width: 
                        95%; height: 30px; font-size: 20px;" required="required">
												<label style=" font-size: 20px; "> Reason</label>
												<textarea type="text" name="reason" class="form-control" style="width: 95%; height: 30px; font-size: 20px;" ></textarea>
                        <label style=" font-size: 20px; "> Picked By</label>
                        <input type="text" name="pickedby" class="form-control" placeholder="Picked By"  style="width: 95%; height: 30px; font-size: 20px;" required="recorded">
                        
                        
												<div class="span12" >
                          <div class="span8">
                                          <button type="submit" name="cashout" class="btn btn-primary">Save</button>
                                        </div>
                                        <div  class="span4">
                                          <a href="" class="btn btn-danger" data-dismiss="modal">Cancel</a>
                                        </div>	
                                      </div>
												</form>
											</div>
										</div>
										<!--Model Ends here -->
                    <!--Model begins here -->
                    
										<!--Model Ends here -->
                    <!-- < -->
                    <!-- ?php -->
                    
                                           <?php
                        if( $permissions['cash_at_hand'] == 1){
                            ?>
                    <div class="span12">
                                   <form method="POST" action="">
                              

                                        
                                        <div class="span4">
                                        <label>By Date from</label>
                                          <input type="date" name="from" class="form-control" id="dfrom" onchange="checkBystafftwo(this.value)" required="required">
                                        </div>
                                        <div class="span4">
                                        <label>By Date to</label>
                                          <input type="date" name="to" class="form-control" id="dto" onchange="checkBystaffthree(this.value)" required="required">
                                        </div>
                                        
                                        <div class="span4">
                                        <label><br></label>
                                          <input type="submit" name="filter" class="btn btn-primary" value="filter" >
                                        </div>
                                        

                                        
                                        
                                        
                                      </form> 
                                      </div>

                                      <?php
                                    }
                                      include '../includes/connection.php';
                                      if (isset($_POST['filter'])) {
                                        $dfrom=$_POST['from'];
                                        $dto=$_POST['to'];
                                      echo "<center><h3>Cash Out From $dfrom To $dto </h3><center>";
                                      //if($_SESSION['role']=="Super Admin"){
                                      if( $permissions['cashout_branch'] == 1){
        $sql = mysqli_query($con,"SELECT *,(select branch_name from branches where branch_id=cash_out.branch_id) as bchname FROM cash_out where business_id='$business' && date>='$dfrom' && date<='$dto'");
       
      }else{
        $sql = mysqli_query($con,"SELECT * FROM cash_out where  branch_id='$branch' && date>='$dfrom' && date<='$dto'");
      }
                                      }else{
                                        //if($_SESSION['role']=="Super Admin"){
                                        if( $permissions['cashout_branch'] == 1){
        $sql = mysqli_query($con,"SELECT *,(select branch_name from branches where branch_id=cash_out.branch_id) as bchname FROM cash_out where business_id='$business'");
       
      }else{
        $sql = mysqli_query($con,"SELECT * FROM cash_out where  branch_id='$branch'");
      }
    }
                                      
                                      ?>
                                     
                                  
                                  
                                   <?php

      
                                                               // Create connection



if (mysqli_num_rows($sql) > 0) {
    // output data of each row
    


                                   ?>
                                   
                                            <?php
                        if( $permissions['cash_at_hand'] == 1){
                            ?>
                                    <div id="toolbar">
                                        <select class="form-control">
                                                <option value="">Export Basic</option>
                                                <option value="all">Export All</option>
                                                <option value="selected">Export Selected</option>
                                            </select>
                                    </div>

                                    <table  id="table" data-toggle="table" data-pagination="true" data-search="true" data-show-columns="true" data-show-pagination-switch="true" data-show-refresh="false" data-key-events="true" data-show-toggle="false" data-resizable="false" data-cookie="true"
                                        data-cookie-id-table="saveId" data-show-export="true" data-click-to-select="true" data-toolbar="#toolbar" data-export-options='{"fileName": "Testing_filename"}'>
                                        <thead>
                                            <tr>
                                                <th>No</th>
                                                <?php
                                               // if($_SESSION['role']=="Super Admin"){
                                                if( $permissions['cashout_branch'] == 1){            
                                                  ?>
                                                <th>Branch Name</th>
                                                <?php 
                                                }?>
                                                <th> Date</th>
                                                <th>Amount</th>
                                                <th>Reason</th>
                                                <th>Picked By</th>
                                                <th>Recorded By</th>
                                                <th>Added By</th>
                                              
                                                <?php
                                                 //if($_SESSION['role']=="admin"){ 
                                                if( $permissions['cashout_action'] == 1){
                                                ?>
                                                <th>Action</th>
                                                <?php } ?>

                                            </tr>
                                        </thead>
                                        <tbody>
                                        
                                        <?php
										$no = 0;
                    $total=0;
										while($row = mysqli_fetch_assoc($sql)) {
											$no++;
                      $total=$total+$row['amount'];
												?>
										<tr class="gradeU">
                                                <td><?php echo $no; ?></td>
                                                <?php
                                                //if($_SESSION['role']=="Super Admin"){ 
                                                if( $permissions['cashout_branch'] == 1){           
                                                  ?>
                                                  <td><?php echo $row['bchname']; ?>
                                                  <?php
                                                }
                                                  ?>
                                                <td><?php echo $row['date']; ?></td>
                                                <td><?php echo $row['amount']; ?></td>
                                                <td><?php echo $row['reason']; ?></td>
                                                <td><?php echo $row['pickedby']; ?></td>
                                                
                                                
                                                
												<?php
												$uid = $row['recorded_by'];
												$sql2 = mysqli_query($con,"select name from users where id='$uid'");
												$row2 = mysqli_fetch_array($sql2);
												?>
                                                <td><?php echo $row2['name']; ?></td>
                                                <td><?php echo $row['recorded_on']; ?></td>

                                                <?php
                                                 //if($_SESSION['role']=="admin"){
                                                 if( $permissions['cashout_action'] == 1){ 
                                                  ?>
                                                <td class="center">
                                                
                                                <a href="#edit<?php echo $row['id']; ?>" data-toggle="modal" ><button class="btn btn-primary"><i class="icon-edit icon-white"></i></button></a>
                                                	
                                                	
                                                	
									<div id="edit<?php echo $row['id']; ?>" class="modal hide">
											<div class="modal-header" style="text-align: center; background-color: #08c; color: white;">
												<button data-dismiss="modal" class="close" type="button">&times;</button>
												<h3>Edit Supplier</h3>
											</div>
											<div class="modal-body">
                        <!--  -->
												<form action="" method="POST">
                        <input type="hidden" name="editid" value="<?php echo $row['id'];?>">
                          <label style=" font-size: 20px; ">Date</label>
                        <input type="date" name="date" class="form-control" value="<?php echo date('Y-m-d');?>" required style="width: 
                        95%; height: 30px; font-size: 20px;">
                         <label style=" font-size: 20px;"> Amount </label>
                         <input type="hidden" name="prevamount" value="<?php echo $row['amount'];?>" >
                        <input type="text" onkeypress="return CheckNumeric()" onkeyup="FormatCurrency(this)" name="amount" class="form-control" value="<?php echo number_format($row['amount']);?>" required  style="width: 95%; height: 30px; font-size: 20px;">
                        <label style=" font-size: 20px; "> Reason</label>
                        <textarea  name="reason" class="form-control"   required="required" style="width: 95%; height: 30px; font-size: 20px;"  ><?php echo $row['reason'];?></textarea>
                        <label style=" font-size: 20px; "> Picked By</label>
                        <input type="text" name="pickedby" class="form-control" value="<?php echo $row['pickedby'];?>"  style="width: 
                        95%; height: 30px; font-size: 20px;">
                        
                        
                        <div class="span12" >
                          <div class="span8">
                                          <button type="submit" name="editcashout" class="btn btn-primary">Save</button>
                                        </div>
                                        <div  class="span4">
                                          <a href="" class="btn btn-danger" data-dismiss="modal">Cancel</a>
                                        </div>  
                                      </div>
                        </form>

											</div>
											<div class="modal-footer">
												
												<!-- <a data-dismiss="modal" class="btn btn-warning" href="#">cancel</a> -->
											</div>
										</div>
                                            
                                                </td>
                                                
                                                <!-- <td><a onclick = "confirmationDelete(this); return false;" href="delete_supplier.php?cashoutid=<?php //echo $row['id'];?>" ><button class="btn btn-danger"><i class="icon-trash icon-white"></i></button></a></td> -->

                                                <?php } ?>
                                            </tr>
                                            
                                            <?php


    }
    ?>
    <tr>
      <td ><strong>TOTAL</strong></td>
      <td colspan="2" style="text-align: center;"><center><strong><?php echo $total ?></strong></center></td>
      <td colspan="5"></td>
    </tr>
    



                                        
                                            
                                        </tbody>
                                    </table>
<?php
                                    } else {
    echo "<h4 style='color:red;'></h4>";
}

}
?>
                                </div>
                            </div>
                        </div>
                        <!-- /block -->
                    </div>
                </div>
            </div>
            <hr>
            <?php include '../includes/footer.php'; ?>
        </div>
        <!--/.fluid-container-->

        <!--==========Footer js======-->
		<?php require_once("../includes/footerjs.php");?>
        <!--==========Footer js======-->
   <script type = "text/javascript">
    function confirmationDelete(anchor){
        var conf = confirm("Are you sure you want to delete this record?");
        if(conf){
            window.location = anchor.attr("href");
        }
    } 
    function confirmationSuspend(anchor){
        var conf1 = confirm("Are you sure you want to Suspend this supplier?");
        if(conf1){
            window.location = anchor.attr("href");
        }
    }  
    function confirmationReturn(anchor){
        var conf2 = confirm("Are you sure you want to Return this Supplier?");
        if(conf2){
            window.location = anchor.attr("href");
        }
    }      
</script>
<script src="../data-table-js/bootstrap-table.js"></script>
    <script src="../data-table-js/tableExport.js"></script>
    <script src="../data-table-js/data-table-active.js"></script>
    <script src="../data-table-js/bootstrap-table-editable.js"></script>
    <script src="../data-table-js/bootstrap-editable.js"></script>
    <script src="../data-table-js/bootstrap-table-resizable.js"></script>
    <script src="../data-table-js/colResizable-1.5.source.js"></script>
    <script src="../data-table-js/bootstrap-table-export.js"></script>
    </body>

<?php


if(isset($_POST['cashout'])){
	include '../includes/connection.php';
$date=mysqli_real_escape_string($con,ucwords($_POST['date']));
$reason=mysqli_real_escape_string($con,$_POST['reason']);

$pickedby=mysqli_real_escape_string($con,ucwords($_POST['pickedby']));

$bad_symbols = array(",");
   
    $amount=$_POST['amount'];
    $amount= str_replace($bad_symbols, "", $amount);
$id_user=$_SESSION['id'];

if($amount>$cash_at_hand){
	echo"<script>alert('Failed!. The amount of $amount to be cashed out cannot be greater than the cash at hand of shs $cash_at_hand !!. Correct your inputs'),history.go(-1)</script>";
}
else{
$sql = mysqli_query($con,"INSERT INTO cash_out (date,amount,reason,pickedby,business_id,branch_id,recorded_by)
VALUES ('$date', '$amount','$reason','$pickedby','$business','$branch','$id_user')");

if ($sql) {


    $id_user=$_SESSION['id'];
  $activity="Added a new cashout of amount".$amount." to : ".$pickedby." for: ".$reason;
  $log_sql=mysqli_query($con,"INSERT INTO logs(user_id, activity,branch_id) VALUES 
('$id_user','$activity','$branch')");
	
  echo "<script>
  alert('Cashout of amount $amount to $pickedby for  $reason has been recorded successfully');
  window.location='cash_out.php'
  </script>";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
}
// mysqli_close($con);
}

if(isset($_POST['editcashout'])){
  include '../includes/connection.php';
  $date=mysqli_real_escape_string($con,ucwords($_POST['date']));
$reason=mysqli_real_escape_string($con,$_POST['reason']);
$pickedby=mysqli_real_escape_string($con,ucwords($_POST['pickedby']));
$editid=$_POST['editid'];
$prevamount=$_POST['prevamount'];
$bad_symbols = array(",");
   
    $amount=$_POST['amount'];
    $amount= str_replace($bad_symbols, "", $amount);
    $cashathandnow=$cash_at_hand+$prevamount;
$id_user=$_SESSION['id'];
if($amount>$cashathandnow){
  echo"<script>alert('Failed!. The amount of $amount to be cashed out cannot be greater than the cash at hand of shs $cash_at_hand !!. Correct your inputs'),history.go(-1)</script>";
}
else{
$esql = mysqli_query($con,"UPDATE  cash_out set date='$date', amount='$amount',reason='$reason',pickedby='$pickedby' where id='$editid'");
if ($esql) {


    $id_user=$_SESSION['id'];
  $eactivity="Added a new supllier ".$ename." with a contact: ".$econtact." and email: ".$eemail;
  $elog_sql=mysqli_query($con,"INSERT INTO logs(user_id, activity) VALUES 
('$id_user','$eactivity')");
  
  echo "<script>
  alert('Cashout of  $amount to  $pickedby for $reason has been updated successfully');
  window.location='cash_out.php'
  </script>";
} else {
    echo "Error: " . $esql . "<br>" . mysqli_error($con);
}
 }
// mysqli_close($con);
}

?>
 
</html>

