<?php include("session_controller.php");

if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  //$theValue = function_exists("mysqli_real_escape_string") ? mysqli_real_escape_string($theValue) : mysqli_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}
//format date function
function dateformatReverse($datetime){
$received_timestamp = "";
 if($datetime != ""){
 $full_date = explode(" ", $datetime);
 $date = explode("-", $full_date[0]);
 $d = $date[2];
 $mo = $date[1];
 $y = $date[0];
 $time = explode(":",$full_date[1]);
 $h = $time[0];
 $min = $time[1];
 $s = $time[2];
 
 $received_timestamp = $d."/".$mo."/".$y." ".$h.":".$min.":".$s;
 }
 return $received_timestamp;
 }
 
function dateformat($datetime){
$received_timestamp = "";
 if($datetime != ""){
 $full_date = explode(" ", $datetime);
 $date = explode("/", $full_date[0]);
 $d = $date[0];
 $mo = $date[1];
 $y = $date[2];
 $time = explode(":",$full_date[1]);
 $h = $time[0];
 $min = $time[1];
 $s = $time[2];
 
 $received_timestamp = $y."-".$mo."-".$d." ".$h.":".$min.":".$s;
 }
 return $received_timestamp;
 }
 
 $colname_Recordset1 = "-1";
if (isset($_GET['account_no'])) {
  $colname_Recordset1 = $_GET['account_no'];
}

  mysqli_select_db($conn, $database_conn);
 $sel_query  = "SELECT * FROM tranx"; 
 $result = mysqli_query($conn, $sel_query); 
 $tranx_id = strtoupper(substr(md5(uniqid(rand(),1)),0,6)); 
 //$tranx_id = strtoupper(substr(md5(uniqid(rand(),1)),0,16)); 
   //$rand2 = base_convert( md5( microtime() ), 16,10); //added this for numeric ticket
   // $tranx_id = substr($rand2, 10, 12); //added this for numeric ticket

while($row = mysqli_fetch_array($result)){
    if($row['tranx_id'] == $tranx_id){
	$tranx_id = strtoupper(substr(md5(uniqid(rand(),1)),0,12)); 
    //$rand2 = base_convert( md5( microtime() ), 16, 10); //added this for numeric ticket
    //$tranx_id = substr($rand2, 10, 12); //added this for numeric ticket  to let draw time display
    $result = mysqli_query($sel_query,$conn); 
} 
}
 

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}



$acct =$colname_Recordset1 ;
$query_accounts_final2 = "SELECT s_no, account_no, credit, debit, balance, tranx_details, tranx_id, tranx_date FROM tranx WHERE tranx_date = (SELECT max(tranx_date) from tranx where account_no = '$acct')";
$accounts_final2 = mysqli_query($conn, $query_accounts_final2) or die(mysqli_error($conn));
$row_accounts_final2 = mysqli_fetch_assoc($accounts_final2);
$totalRows_accounts_final2 = mysqli_num_rows($accounts_final2);


$query_accounts_count = "SELECT count(s_no) AS 'no_of_tranx2' FROM tranx WHERE account_no = '$acct'";
$accounts_count = mysqli_query($conn, $query_accounts_count) or die(mysqli_error($conn));
$row_accounts_count = mysqli_fetch_assoc($accounts_count);
$totalRows_accounts_count = mysqli_num_rows($accounts_count);


  $updateBalance4 =  sprintf("UPDATE accounts SET balance = %s, no_of_tranx = %s WHERE account_no = %s",
            GetSQLValueString($row_accounts_final2['balance'], "int"), GetSQLValueString($row_accounts_count['no_of_tranx2'], "int"), GetSQLValueString($colname_Recordset1, "text"));
  $Result4 = mysqli_query($conn, $updateBalance4) or die(mysqli_error($conn));



if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) {
 
	        $query_accounts = "SELECT * FROM accounts WHERE account_no = '$colname_Recordset1'";
			$accounts = mysqli_query($conn, $query_accounts) or die(mysqli_error($conn));
			$row_accounts = mysqli_fetch_assoc($accounts);
			$totalRows_accounts = mysqli_num_rows($accounts);
			$net = 0;
			$no_of_tranx = 0;

       $stock_id = "";

     
       
       //$mode_of_payment = $_POST['mode_of_payment'] ;

	  if($_POST['tranx_type'] == "credit"){
        
        if(($_POST['mode_of_payment']== "stock_dispatch") && (isset($_POST['stock_id']) && ($_POST['stock_id'] != ""))) {

            $stock_id =   $_POST['stock_id'];
            $stock_id =intval($stock_id);

              $query_accounts3 = "SELECT * FROM stocks WHERE s_no = $stock_id";
              $accounts3 = mysqli_query($conn, $query_accounts3) or die(mysqli_error($conn));
              $row_accounts3 = mysqli_fetch_assoc($accounts3);
              $totalRows_accounts3 = mysqli_num_rows($accounts3);


            //  if($row_accounts['quantity'] >=intval($_POST['quantity'] ){

              $val = $row_accounts3['quantity'] + intval($_POST['quantity']);

		  $net =  ($row_accounts['balance'] + GetSQLValueString($_POST['amount'], "int"));
		 $no_of_tranx =  ($row_accounts['no_of_tranx'] + 1);
		   $updateBalance =  sprintf("UPDATE accounts SET balance = %s, no_of_tranx = %s WHERE account_no = %s",
					  GetSQLValueString($net, "int"), GetSQLValueString($no_of_tranx, "int"), GetSQLValueString($colname_Recordset1, "text"));
  $Result1 = mysqli_query($conn, $updateBalance) or die(mysqli_error($conn)) . "1";
 
  if($Result1){
       $updateSQL = sprintf("INSERT INTO tranx (account_no, credit, balance, mode_of_payment, tranx_details, tranx_date, tranx_id, stock_quantity, staff, stock_id) values( %s, %s, %s, %s, %s , %s, %s, %s, %s, %s)",
         GetSQLValueString($_GET['account_no'], "text"),
                             GetSQLValueString($_POST['amount'], "text"),
      					   GetSQLValueString($net, "int"),
      					   GetSQLValueString($_POST['mode_of_payment'], "text"),
                             GetSQLValueString($_POST['tranx_details'], "text"),
                             GetSQLValueString(dateformat($_POST['tranx_date']), "text"),
      					   GetSQLValueString($tranx_id, "text"),
                   GetSQLValueString($_POST['quantity'], "text"),
                 GetSQLValueString( $_SESSION['MM_Username'], "text"),
                  GetSQLValueString($stock_id, "int"));

        $Result1 = mysqli_query($conn, $updateSQL) or die(mysqli_error($conn)) . "2";



          $updateSQL2 = sprintf("UPDATE stocks SET quantity = %s WHERE s_no = %s",
                  GetSQLValueString($val, "int"),
                  GetSQLValueString($stock_id, "int"));

        $Result2 = mysqli_query($conn, $updateSQL2) or die(mysqli_error($conn)) . "3";

                  }

               // }
 
            }
             else{

                  $net =  ($row_accounts['balance'] + GetSQLValueString($_POST['amount'], "int"));
                     $no_of_tranx =  ($row_accounts['no_of_tranx'] + 1);
                       $updateBalance =  sprintf("UPDATE accounts SET balance = %s, no_of_tranx = %s WHERE account_no = %s",
                            GetSQLValueString($net, "int"), GetSQLValueString($no_of_tranx, "int"), GetSQLValueString($colname_Recordset1, "text"));
                  $Result1 = mysqli_query($conn, $updateBalance) or die(mysqli_error($conn));
                 
                  if($Result1){
                       $updateSQL = sprintf("INSERT INTO tranx (account_no, credit, balance, mode_of_payment, tranx_details, tranx_date, tranx_id, stock_quantity, staff) values( %s, %s, %s, %s, %s , %s, %s, %s, %s)",
                         GetSQLValueString($_GET['account_no'], "text"),
                                             GetSQLValueString($_POST['amount'], "text"),
                                   GetSQLValueString($net, "int"),
                                   GetSQLValueString($_POST['mode_of_payment'], "text"),
                                             GetSQLValueString($_POST['tranx_details'], "text"),
                                             GetSQLValueString(dateformat($_POST['tranx_date']), "text"),
                                   GetSQLValueString($tranx_id, "text"),
                                   GetSQLValueString($_POST['quantity'], "text"),
                 GetSQLValueString( $_SESSION['MM_Username'], "text"));

                        $Result1 = mysqli_query($conn, $updateSQL) or die(mysqli_error($conn));
            
              } 
          
           }
         }

  else if($_POST['tranx_type'] == "debit"){



     if(($_POST['mode_of_payment'] == "stock_release") && (isset($_POST['stock_id']) && ($_POST['stock_id'] != ""))) {

            $stock_id =   $_POST['stock_id'];
            $stock_id =intval($stock_id); 

//check if you have available stock
              $query_accounts4 = "SELECT * FROM stocks WHERE s_no = $stock_id";
              $accounts4 = mysqli_query($conn, $query_accounts4) or die(mysqli_error($conn));
              $row_accounts4 = mysqli_fetch_assoc($accounts4);
              $totalRows_accounts4 = mysqli_num_rows($accounts4);


              if($row_accounts4['quantity'] >= intval($_POST['quantity'] )){

              $val = $row_accounts4['quantity'] - intval($_POST['quantity']);

             $net =  ($row_accounts['balance'] - GetSQLValueString($_POST['amount'], "int"));
              $no_of_tranx =  ($row_accounts['no_of_tranx'] + 1);
             $updateBalance =  sprintf("UPDATE accounts SET balance = %s, no_of_tranx = %s WHERE account_no = %s",
                    GetSQLValueString($net, "int"), GetSQLValueString($no_of_tranx, "int"), GetSQLValueString($colname_Recordset1, "text"));
          $Result1 = mysqli_query($conn, $updateBalance) or die(mysqli_error($conn)). "11";
          if($Result1){
           $updateSQL = sprintf("INSERT INTO tranx (account_no, debit, balance, mode_of_payment, tranx_details, tranx_date, tranx_id, stock_quantity, staff, stock_id) values( %s, %s, %s, %s , %s, %s, %s, %s, %s, %s)",
           GetSQLValueString($_GET['account_no'], "text"),
                               GetSQLValueString($_POST['amount'], "text"),
                     GetSQLValueString($net, "int"),
                      GetSQLValueString($_POST['mode_of_payment'], "text"),
                               GetSQLValueString($_POST['tranx_details'], "text"),
                               GetSQLValueString(dateformat($_POST['tranx_date']), "text"),
                     GetSQLValueString($tranx_id, "text"),
                     GetSQLValueString($_POST['quantity'], "text"),
                 GetSQLValueString( $_SESSION['MM_Username'], "text"),
                GetSQLValueString($stock_id, "int"));

                $Result1 = mysqli_query($conn, $updateSQL) or die(mysqli_error($conn)). "111";


//update stocks table
          $updateSQL2 = sprintf("UPDATE stocks SET quantity = %s WHERE s_no = %s",
                  GetSQLValueString($val, "int"),
                  GetSQLValueString($stock_id, "int"));

        $Result2 = mysqli_query($conn, $updateSQL2) or die(mysqli_error($conn)). "1111"; 

                  }

                }
                else{

                  echo "<script> alert('Transaction Unsuccessful! Your stock quantity is below the requested quantity. Please get more stock'); </script>";
                }
 
            }


  else{
	   $net =  ($row_accounts['balance'] - GetSQLValueString($_POST['amount'], "int"));
	    $no_of_tranx =  ($row_accounts['no_of_tranx'] + 1);
	   $updateBalance =  sprintf("UPDATE accounts SET balance = %s, no_of_tranx = %s WHERE account_no = %s",
					  GetSQLValueString($net, "int"), GetSQLValueString($no_of_tranx, "int"), GetSQLValueString($colname_Recordset1, "text"));
  $Result1 = mysqli_query($conn, $updateBalance) or die(mysqli_error($conn));
  if($Result1){
	 $updateSQL = sprintf("INSERT INTO tranx (account_no, debit, balance, tranx_details, tranx_date, tranx_id, stock_quantity, staff) values( %s, %s, %s, %s , %s, %s, %s, %s)",
   GetSQLValueString($_GET['account_no'], "text"),
                       GetSQLValueString($_POST['amount'], "text"),
					   GetSQLValueString($net, "int"),
                       GetSQLValueString($_POST['tranx_details'], "text"),
                       GetSQLValueString(dateformat($_POST['tranx_date']), "text"),
					   GetSQLValueString($tranx_id, "text"),
             GetSQLValueString($_POST['quantity'], "text"),
                 GetSQLValueString( $_SESSION['MM_Username'], "text"));

        $Result1 = mysqli_query($conn, $updateSQL) or die(mysqli_error($conn));


        
        }


      }
  }
  


  $updateGoTo = "tranx_customer.php?account_no=". $_POST['account_no'];
  if (isset($_SERVER['QUERY_STRING'])) {
    $updateGoTo .= (strpos($updateGoTo, '?')) ? "&" : "?";
    $updateGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $updateGoTo));
  
}


mysqli_select_db($conn, $database_conn);
$query_Recordset1 = sprintf("SELECT * FROM accounts WHERE account_no = %s", GetSQLValueString($colname_Recordset1, "int"));
$Recordset1 = mysqli_query($conn, $query_Recordset1) or die(mysqli_error($conn));
$row_Recordset1 = mysqli_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysqli_num_rows($Recordset1);

mysqli_free_result($Recordset1);


$query_accounts_final = "SELECT s_no, account_no, credit, debit, balance, tranx_details, tranx_id, tranx_date FROM tranx WHERE tranx_date = (SELECT max(tranx_date) from tranx where account_no = '$acct')";
$accounts_final = mysqli_query($conn, $query_accounts_final) or die(mysqli_error($conn));
$row_accounts_final = mysqli_fetch_assoc($accounts_final);
$totalRows_accounts_final = mysqli_num_rows($accounts_final);


?>


<html>
<head>
<title> Add Tranx</title>
<link href="style.css" rel="stylesheet" type="text/css" />

</head>
<body>
<?php include("links.php");?>
<div class="container">
<div class="row">
<div class="col-sm-6">
<div style="font-family:Century Gothic; font-size:26px; font-weight:300"> <?php echo "Balance: NGN". number_format($row_Recordset1['balance']); ?></div>
<div style="font-family:Century Gothic; font-size:18px; font-weight:bold"> Add Transaction for: <?php echo $row_Recordset1['surname']. " ". $row_Recordset1['firstname']. " ". $row_Recordset1['middlename'] . " - ". $row_Recordset1['account_no']; ?></div>
<div style="font-family:Century Gothic; font-size:16px; font-weight:bold"> Transaction Ref: <?php echo $tranx_id; ?></div>


<form method="post" name="form1" action="<?php echo $editFormAction; ?>" class="form-group">
  <div class="table-responsive">	
	<br/>
 <div style="font-family:Century Gothic; font-size:15px;"> Amount:</div>
  <input type="number" name="amount" value="" class="form-control">
   
   <br/>
   <div style="font-family:Century Gothic; font-size:15px;">Transaction Type:</div>
     
     <!-- <input type="text" name="sex" value="" size="32" /> -->
      <select name="tranx_type" class="form-control">
							  <option selected="selected" value="">Select</option>
							  <option value="credit" >Credit</option>
							  <option value="debit" >Debit</option>
						  
      </select>
      <br/>

      <div style="font-family:Century Gothic; font-size:15px;">Mode of Payment:</div>
  <!-- <input type="textfield" name="mode_of_payment" value="" class="form-control"> -->
    <select name="mode_of_payment" class="form-control" id="mode_of_payment" onchange="show_qty();">
               
                <option value="cash" >Cash</option>
                 <option value="bank_transfer" >Bank Transfer</option>
                  <option value="stock_dispatch" >Stock Dispatch</option>
                   <option value="stock_release" >Stock Release</option>


              
      </select>
 

  <div style="font-family:Century Gothic; font-size:15px;display: none;" id="stock_item"> <br/>Select Stock:<br/>
 <?php  

$query_stocks = "SELECT * FROM stocks ORDER BY s_no ASC";
$accounts_stocks = mysqli_query($conn, $query_stocks) or die(mysqli_error($conn));
$row_accounts_stocks = mysqli_fetch_assoc($accounts_stocks);
$totalRows_accounts_stocks = mysqli_num_rows($accounts_stocks);
 
?>
  <select name="stock_id" id="stock_id" class="form-control">
                <option selected="selected" value="">Select Item</option>
              
<?php 
if($totalRows_accounts_stocks > 0){
do{ ?>
   <option value="<?php echo $row_accounts_stocks['s_no'] ; ?>" ><?php echo $row_accounts_stocks['name'] ; ?> - <?php echo $row_accounts_stocks['quantity'] ; ?> qty</option>

<?php }while($row_accounts_stocks = mysqli_fetch_assoc($accounts_stocks)) ;

   }
   else{
    echo "<script> alert('No Stock items yet!'); </script>";
   }
 ?>
      
      </select>
  </div>
 

  <div style="font-family:Century Gothic; font-size:15px;display: none;" id="stock_qty"> <br/>Enter Quantity of Stock Item:<br/>
  <input type="number" name="quantity" value="" class="form-control">
  </div>
  <br/>


  


 <div style="font-family:Century Gothic; font-size:15px;">Transaction Details:</div>
  <input type="textfield" name="tranx_details" value="" class="form-control">
  <br/>
  
   <div style="font-family:Century Gothic; font-size:15px;"> Transaction Date: &nbsp;&nbsp; (DD/MM/YYYY HH:mm:ss) </label></div>
    <input type='text' class="form-control" id='datetimepicker1' name="tranx_date" />
        <script type="text/javascript">
            $(function () {
                $('#datetimepicker1').datetimepicker({
					format: 'DD/MM/YYYY HH:mm:ss'
				});
            });
        </script>	
        
        <br/><br/>				 
	<input type="submit" value="SAVE" class="btn btn-primary" style="width:40%; height:auto;padding-left:10px;padding-left:10px; background-color:#f2f1f3; border-radius:5px; color:#333"/> &nbsp; &nbsp; &nbsp; &nbsp; <a href="accounts.php" class="btn btn-primary" style="width:40%; height:auto;padding-left:10px;padding-left:10px; background-color:#f2f1f3; border-radius:5px; color:#333">CANCEL </a></td>
   
  </div>

  <input type="hidden" name="MM_update" value="form1">
<?php if (isset($_GET['account_no'])) {  ?>
 <input type="hidden" name="account_no" value="<?php echo $_GET['account_no']; ?>"> 
<?php } ?>  

</form>

  </form></div></div></div>

<br />

<script type="text/javascript">
        function show_qty(){
          if((document.getElementById('mode_of_payment').value == "stock_dispatch")||(document.getElementById('mode_of_payment').value == "stock_release")) {
            //alert("hi");
            document.getElementById('stock_qty').style.display= "inline";
             document.getElementById('stock_item').style.display= "inline";
          }
          else{
            document.getElementById('stock_qty').style.display= "none";
               document.getElementById('stock_item').style.display= "none";
          }
        }

      </script>

 </body>
 
 </html>

