<?php require_once('../Connections/lancrox.php'); ?>
<?php
//initialize the session
if (!isset($_SESSION)) {
  session_start();
}

// ** Logout the current user. **
$logoutAction = $_SERVER['PHP_SELF']."?doLogout=true";
if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){
  $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){
  //to fully log out a visitor we need to clear the session varialbles
  $_SESSION['MM_Username'] = NULL;
  $_SESSION['MM_UserGroup'] = NULL;
  $_SESSION['PrevUrl'] = NULL;
  unset($_SESSION['MM_Username']);
  unset($_SESSION['MM_UserGroup']);
  unset($_SESSION['PrevUrl']);
	
  $logoutGoTo = "index.php";
  if ($logoutGoTo) {
    header("Location: $logoutGoTo");
    exit;
  }
}
?>
<?php
if (!isset($_SESSION)) {
  session_start();
}
$MM_authorizedUsers = "";
$MM_donotCheckaccess = "true";

// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { 
  // For security, start by assuming the visitor is NOT authorized. 
  $isValid = False; 

  // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. 
  // Therefore, we know that a user is NOT logged in if that Session variable is blank. 
  if (!empty($UserName)) { 
    // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. 
    // Parse the strings into arrays. 
    $arrUsers = Explode(",", $strUsers); 
    $arrGroups = Explode(",", $strGroups); 
    if (in_array($UserName, $arrUsers)) { 
      $isValid = true; 
    } 
    // Or, you may restrict access to only certain users based on their username. 
    if (in_array($UserGroup, $arrGroups)) { 
      $isValid = true; 
    } 
    if (($strUsers == "") && true) { 
      $isValid = true; 
    } 
  } 
  return $isValid; 
}

$MM_restrictGoTo = "index.php";
if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {   
  $MM_qsChar = "?";
  $MM_referrer = $_SERVER['PHP_SELF'];
  if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
  if (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0) 
  $MM_referrer .= "?" . $_SERVER['QUERY_STRING'];
  $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
  header("Location: ". $MM_restrictGoTo); 
  exit;
}
?>
<?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($GLOBALS["___mysqli_ston"], $theValue) : ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $theValue) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : ""));

  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;
}
}

$colname_Recordset1 = "-1";
if (isset($_SESSION['MM_Username'])) {
  $colname_Recordset1 = $_SESSION['MM_Username'];
}
mysqli_select_db( $lancrox, $database_lancrox);
$query_Recordset1 = sprintf("SELECT * FROM admin WHERE username = %s", GetSQLValueString($colname_Recordset1, "text"));
$Recordset1 = mysqli_query( $lancrox, $query_Recordset1) or die(mysqli_error($GLOBALS["___mysqli_ston"]));
$row_Recordset1 = mysqli_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysqli_num_rows($Recordset1);

mysqli_select_db( $lancrox, $database_lancrox);
$query_er = "SELECT * FROM currentprice";
$er = mysqli_query( $lancrox, $query_er) or die(mysqli_error($GLOBALS["___mysqli_ston"]));
$row_er = mysqli_fetch_assoc($er);
$totalRows_er = mysqli_num_rows($er);
				 
function random_string ($charset_string, $length)
{
$return_string = ""; // the empty string
for ($x = 0; $x < $length; $x++)
$return_string .= random_char($charset_string);
return($return_string);
}
 $down7 = "select sum(paid+bank)credit,debt from billing left join (select sum(unitcost*outputs)debt,userid from agwa where userid ='$_REQUEST[code]') agwa on agwa.userid=billing.userid where billing.userid='$_REQUEST[code]'";
$rst_chk7=mysqli_query($lancrox, $down7);
$num_chk7=mysqli_num_rows($rst_chk7); 
$row_down7 = mysqli_fetch_assoc($rst_chk7);



function fill_unit_select_box($connect)
{ 
 $output = '';
 $query = "SELECT * FROM currentprice WHERE owner='FEEDS' ORDER BY unit_name ASC";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  $output .= '<option value="'.$row["unit_name"].'">'.$row["unit_name"].'</option>';
 }
 return $output;
}

function get_items_as_array($connect)
{ 
 $output = '';
 $query = "SELECT * FROM currentprice WHERE owner='FEEDS'";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $output = json_encode($result);
 return $output;
}

	 $down8 = "select * from clients where userid = '$_REQUEST[code]' ";
$rst_chk8=mysqli_query($lancrox, $down8);
$num_chk8=mysqli_num_rows($rst_chk8); 
$row_down8 = mysqli_fetch_assoc($rst_chk8);
 $order_id = uniqid();	
$mh=str_shuffle($row_down8[userid]);
$str =$mh.$order_id;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Welcome</title>
<link href="../macss.css" rel="stylesheet" type="text/css" />
 <script src="../jquery.min.js"></script>
  <link rel="stylesheet" href="../bootstrap.min.css" />
  <link href="../SpryAssets/SpryValidationTextField.css" rel="stylesheet" type="text/css" />
  <script src="../bootstrap.min.js"></script>
  <script src="../jsviews.min.js"></script>
<script src="../SpryAssets/SpryValidationTextField.js" type="text/javascript"></script>
</head>

<body>
<div id="container">
  <div id="header">
    <div id="main">
      <div id="logo"></div>
      
      <? include('nav.php');?>
    </div>
  </div>
  <div id="thebody">
    <div id="mainbody">
      <p>&nbsp;</p>
      <p>Welcome <?php echo $row_Recordset1['fullname']; ?> <? echo $print;?></p>
      <table width="59%" border="0" align="center" cellpadding="4" cellspacing="4" class="table-condensed">
        <tr>
          <td bgcolor="#FFFFCC"><strong>Surname</strong></td>
          <td bgcolor="#FFFFCC"><strong><? echo $row_down8[fullname];?></strong></td>
        </tr>
        <tr>
          <td width="30%" bgcolor="#D6D6D6">Phone Number</td>
          <td width="70%" bgcolor="#D6D6D6"><? echo $row_down8[phone];?></td>
        </tr>
        <tr>
          <td bgcolor="#FFFFFF"><strong>Profile</strong></td>
          <td bgcolor="#FFFFFF"><strong><? echo $row_down8[profile];?> Customer</strong></td>
        </tr>
        <tr>
          <td bgcolor="#FFFF99"><strong>Account Balance</strong></td>
          <td bgcolor="#FFFF99">₦<? echo number_format($row_down7[credit]-$row_down7[debt]);?></td>
        </tr>
      </table>
      <p>&nbsp;</p>
      <form method="post" id="insert_form">
    <div class="table-repsonsive">
     <span id="error"></span>
     <table class="table table-bordered" id="item_table">
     
     </table>
     <label for="specimen"></label><?
$print="print.php?me=$str";?>
     <input name="batch" type="hidden" id="batch" value="<? echo $str;?>" />
     <input name="userid" type="hidden" id="userid" value="<? echo $_REQUEST[code];?>" />
     <input name="sender" type="hidden" id="sender" value="<?php echo $row_Recordset1[fullname]; ?>" />
     <input name="station" type="hidden" id="station" value="<?php echo $row_Recordset1[station]; ?>" />
     Bank Transfer
     <span id="sprytextfield1">
     <label for="bank"></label>
     <input name="bank" type="text" id="bank" value="0" />
     <span class="textfieldRequiredMsg">A value is required.</span><span class="textfieldInvalidFormatMsg">Invalid format.</span></span>&nbsp;&nbsp;&nbsp;<span id="sprytextfield2">Cash Deposit
     <label for="cash"></label>
     <input name="cash" type="text" id="cash" value="0" />
     <span class="textfieldInvalidFormatMsg">Invalid format.</span><span class="textfieldRequiredMsg">A value is required.</span></span>&nbsp;
     <label for="bankname"></label>
     <input type="text" name="bankname" id="bankname"  placeholder="Bank Name"/>
     <div align="center">
       <input type="submit" name="submit" class="btn btn-info" value="Purchase" />
 </div>
    </div>
   </form>
      <p>&nbsp;</p>
      <p>&nbsp;</p>
    </div>
  </div>
</div>
<script type="text/javascript">
var sprytextfield1 = new Spry.Widget.ValidationTextField("sprytextfield1", "integer", {useCharacterMasking:true});
var sprytextfield2 = new Spry.Widget.ValidationTextField("sprytextfield2", "integer", {useCharacterMasking:true});
</script>
</body>
</html>
<?php
((mysqli_free_result($Recordset1) || (is_object($Recordset1) && (get_class($Recordset1) == "mysqli_result"))) ? true : false);

((mysqli_free_result($er) || (is_object($er) && (get_class($er) == "mysqli_result"))) ? true : false);
?>
<script id="productTmpl" type="text/x-jsrender">
    <thead>      
        <tr>
            <th>Name of Product</th>
            <th>Enter Quantity</th>
            <th>Cost</th>
            <th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
        </tr>
    </thead>
    <tbody>
    {^{for selected_products}}
        <tr><td><select name="item_unit[]" class="form-control item_unit" id="item_selector"><option value="">Select Product</option><?php echo fill_unit_select_box($connect); ?></select></td>
            
            <td><input type="text" name="item_quantity[]"  data-link="quantity" class="form-control item_quantity" id="quantity_input" /></td>
            <td><input type="text" name="item_name[]" readonly data-link="price" class="form-control item_name" /></td>
            <td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td>
         </tr>
    {{/for}}
    </tbody>
    <tfoot>
        <tr>
            <td colspan=3>Total</td>
            <td colspan=1 data-link="total"></td>
        </tr>
    </tfoot>
</script>

<script>


 
  
$(document).ready(function(){
    
    /*-----------------------DO NOT TOUCH-------------------------------------*/
    
    var calculateTotal = function(products){
        return products.reduce(function(p, c){
            return p + (c.price * c.quantity)
        }, 0)
    }
    
    var products = <? echo get_items_as_array($connect); ?>;
    var selected_products = []
    var total = 0;
    
    var productTemplate = $.templates("#productTmpl");
    var app = {
        products: products,
        selected_products:selected_products,
        total:total
    };
    
    productTemplate.link("#item_table", app);
    
    $(document).on('click', '.add', function(){
        $.observable(selected_products).insert({name: "", price:"", quantity: 0, id:(new Date()).getTime()});
    })
    
    $(document).on('click', '.remove', function(){
        $.observable(selected_products).remove($.inArray($.view(this).data, selected_products))
        $.observable(app).setProperty({total: calculateTotal(selected_products)})
    });
    
    
     $(document).on('blur', '#quantity_input', function(ev){
        var active_data = $.view(this).data;
        $.observable(active_data).setProperty({quantity: this.value}) 
        $.observable(app).setProperty({total: calculateTotal(selected_products)})
     })
    
    $(document).on('change', '#item_selector', function(ev){
        selected_item_name = this.value;
        var item = products.find(function(element) {
            return element.unit_name === selected_item_name;
        });
        if(typeof(item) !== "undefined"){
            var active_data = $.view(this).data;
            $.observable(active_data).setProperty({name:item.name, price:item.price3, quantity: 1})      
            $.observable(app).setProperty({total: calculateTotal(selected_products)})
        }else{
            console.error("item", item)
        }
     
    });
    
 /*---------------------------------DO NOT TOUCH------------------------------*/
 
 
 $('#insert_form').on('submit', function(event){
  event.preventDefault();
  var error = '';
  $('.item_name').each(function(){
   var count = 1;
   if($(this).val() == '')
   {
    error += "<p>Enter Item Name at "+count+" Row</p>";
    return false;
   }
   count = count + 1;
  });
  
  $('.item_quantity').each(function(){
   var count = 1;
   if($(this).val() == '')
   {
    error += "<p>Enter Item Quantity at "+count+" Row</p>";
    return false;
   }
   count = count + 1;
  });
  
  $('.item_unit').each(function(){
   var count = 1;
   if($(this).val() == '')
   {
    error += "<p>Select Unit at "+count+" Row</p>";
    return false;
   }
   count = count + 1;
  });
  var form_data = $(this).serialize();
  if(error == '')
  {
   $.ajax({
    url:"insert.php",
    method:"POST",
    data:form_data,
    success:function(data)
    {
     if(data == 'ok')
     {
      $('#item_table').find("tr:gt(0)").remove();
      $('#error').html('<div class="alert alert-success">Item Details Saved <strong><a href="<? echo "$print";?>">Print</a></strong></div>');
     }
    }
   });
  }
  else
  {
   $('#error').html('<div class="alert alert-danger">'+error+'</div>');
  }
 });
 
});
</script>