<?php
 session_start();
 require_once('../connect.php');
 require_once('sql_required.php');

$datetoday = date('Y-m-d'); 
$active_tab = "walk";
if (!isset($_SESSION['unique_id'])) { ?>
    <script language="javascript">
      window.location.href = '../index.php';
    </script>
<?php } 

$success_messages = '';
if (isset($_POST['save'])) {
  $member_id = $_POST['member_id'];
  $orderunique_customer = $member_id;
  $totalPurchase = $_POST['totalRequest'];

  function generateRandomString($length = 6) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
      $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
  }

  $purchase_code = 'MPW'.generateRandomString();

  $sqlInsert = "INSERT INTO tbl_purchase(purchase_id, member_id, total_purchase, date_purchase)VALUES('$purchase_code', '$member_id', '$totalPurchase', '$datetoday')";
  if (mysqli_query($conn, $sqlInsert)) {
    header('location:walkinPurchase.php');

    include("getunilevels.php");
    $youRI = $totalPurchase * 0.06;
    $lvl1ri = $totalPurchase * 0.04;
    $lvl2ri = $totalPurchase * 0.03;
    $lvl3ri = $totalPurchase * 0.03;
    $lvl4ri = $totalPurchase * 0.02;
    $lvl5ri = $totalPurchase * 0.02;

    $sql_insertbonus ="INSERT INTO tbl_hybrid_bonus(unique_id, debit, credit, bonus_type, transaction_type, date_accumulated, verification_code, level) VALUES
    ('$orderunique_customer', '$youRI', '0', 'RI', 'PP', '$datetoday', '$purchase_code', '0'),
    ('$indrlevel1', '$lvl1ri', '0', 'RI', 'PP', '$datetoday', '$purchase_code', '1'),
    ('$indrlevel2', '$lvl2ri', '0', 'RI', 'PP', '$datetoday', '$purchase_code', '2'),
    ('$indrlevel3', '$lvl3ri', '0', 'RI', 'PP', '$datetoday', '$purchase_code', '3'),
    ('$indrlevel4', '$lvl4ri', '0', 'RI', 'PP', '$datetoday', '$purchase_code', '4'),
    ('$indrlevel5', '$lvl5ri', '0', 'RI', 'PP', '$datetoday', '$purchase_code', '5')";
    mysqli_query($conn, $sql_insertbonus);

    if (isset($_POST['productSelected'])) {
      $selectedProduct = count($_POST['productSelected']);
      for($i=0; $i<$selectedProduct; $i++) { 
        $productSelected = mysqli_real_escape_string($conn, $_POST["productSelected"][$i]);
        $priceProduct = $_POST['productPrice'][$i];
        $quantity = mysqli_real_escape_string($conn, $_POST['quantity'][$i]);
        $sqlInsertPurchase = "INSERT INTO tbl_purchase_product(purchase_id, product_id, product_quantity, product_price) VALUES ('$purchase_code', '$productSelected', '$quantity', '$priceProduct')";
        mysqli_query($conn, $sqlInsertPurchase);
      }
    }
  }
}
?>  
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Purchase</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
  <link rel="icon" href="images/logo.png" type="image/png" sizes="16x16">
  <link rel="stylesheet" href="plugins/fontawesome-free/css/all.min.css">
  <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
  <link rel="stylesheet" href="dist/css/adminlte.min.css">
  <link rel="stylesheet" href="plugins/icheck-bootstrap/icheck-bootstrap.min.css">
  <link rel="stylesheet" href="plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
  <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700" rel="stylesheet">
  <link rel="stylesheet" type="text/css" href="css/style1.css">
  <link rel="stylesheet" type="text/css" href="css/skeleton_loading.css">
<style type="text/css">
  .content-wrapper {
    background: #151e27!important;
  }
  @media(max-width:800px) {
    .modal-content {
      position: fixed; bottom: 40%; width: 96%; left: 7;
    }
    .modal-dialog {
      margin: 0!important; padding: 0!important;
    }
  }
  .page-item.active .page-link {
    background-color: #27313d!important;
    border-color: #27313d!important;
    color: #000;
  }
  .page-item .page-link {
    background-color: #151e27!important;
    border-color: grey!important;
    color: grey!important;
  }

  .alert-success {
    color: #3c763d;
    background-color: #dff0d8;
    border-color: #d6e9c6;
    border-radius: 0;
  }

  .alert-danger {
    color: #a94442;
    background-color: #f2dede;
    border-color: #ebccd1;
    border-radius: 0;
  }
  .form-control {
    border-radius: 10px;
  }
  .form-control:focus {
    border: 1px solid #ffd700!important;
  }

  .containerProduct {
    height: 300px;
    min-height: 250px;
    overflow-y: scroll;
  }

  /* custom scrollbar */
  ::-webkit-scrollbar {
    width: 20px;
  }

  ::-webkit-scrollbar-track {
    background-color: transparent;
  }

  ::-webkit-scrollbar-thumb {
    background-color: #d6dee1;
    border-radius: 20px;
    border: 7px solid transparent;
    background-clip: content-box;
  }

  ::-webkit-scrollbar-thumb:hover {
    background-color: #a8bbbf;
  }

  #result {
   position: absolute;
   width: 100%;
   max-width: 330px;
   cursor: pointer;
   overflow-y: auto;
   max-height: 400px;
   box-sizing: border-box;
   z-index: 1001;
   border-radius: 10px;
   margin-top: -10px;
  }
  .link-class:hover{
   background-color:#f1f1f1;
  }
</style>
</head>
<body class="hold-transition sidebar-mini layout-footer-fixed layout-fixed" style="background: #151e27;">
<div id="preloader" class="loading" style="display: none"></div>
<div class="wrapper">
  <nav class="main-header navbar navbar-expand navbar-white" style="background: #151e27; border-bottom: 0; box-shadow: none!important;">
    <ul class="navbar-nav">
      <li class="nav-item">
        <a href="index.php?<?php echo generate_string($permitted_chars, 100); ?>" class="withanimation back_arrow"><i class="fas fa-angle-left pr-2" style="font-size: 20px; color: #ffd700;"></i></a><span class="brand-text" style="font-size: 20px;"><span style="font-size: 20px; font-weight: bolder; line-height: 20px; color: #fff;">Purchase</span></a>
      </li>
    </ul>
    <ul class="navbar-nav ml-auto">
      <a class="nav-link" data-widget="pushmenu" href="#" role="button"><i class="fas fa-bars"></i></a>
    </ul>
  </nav>

<?php include ("navbar.php")?>
<div class="content-wrapper">
  <div class="content-header p-0">
    <div class="container-fluid p-0">
      <span id="message">
        <?php echo $success_messages; ?>
      </span>
    </div>
  </div>
  <section class="content">
    <div class="container-fluid pt-0">

      <div class="row pt-2">
        <div class="col-lg-6 offset-lg-3">
          <form method="POST" autocomplete="off" id="userDetails">

          <div class="form-group search-box">
           <input type="text" name="search" id="search" placeholder="Search Member Name" class="form-control" required/>
          </div>
          <ul class="list-group" id="result"></ul>

          <input type="hidden" name="member_id" id="member_id">
            <label><small class="text-white">Select Product</small></label>

            <div class="containerProduct">
              <?php 
                $sqlProduct = "SELECT * FROM tbl_product";
                $resultProduct = $conn->query($sqlProduct);
                  while($rowProduct = mysqli_fetch_array($resultProduct)) {

                    if ($rowProduct['product_id'] == 1) {
                      $productPrice = 1400;
                    }elseif($rowProduct['product_id'] == 2){
                      $productPrice = 270;
                    }elseif($rowProduct['product_id'] == 3){
                      $productPrice = 270;
                    }elseif($rowProduct['product_id'] == 4){
                      $productPrice = 310;
                    }elseif($rowProduct['product_id'] == 5){
                      $productPrice = 300;
                    }
              ?>
              <div class="form-group card p-2" style="border-radius: 10px; background-color: #1d2532!important;">
                <div class="display-flex-item">
                  <div class="icheck-warning">
                     <input type="checkbox" name="productSelected[]" id="<?php echo $rowProduct['product_id']; ?>" data-product-price="<?php echo $productPrice; ?>" class="checkbox-product" value="<?php echo $rowProduct['product_id']; ?>" required>
                     <label for="<?php echo $rowProduct['product_id']; ?>" class="text-white"><?php echo $rowProduct['product_name']; ?></label>
                  </div>
                  <label for="<?php echo $rowProduct['product_id']; ?>" style="line-height: 35px; color: #ffd700;">&#8369; <?php echo $productPrice; ?>.00</label>
                </div>
                <input type="number" name="quantity[]" id="quantity_<?php echo $rowProduct['product_id']; ?>" class="form-control" placeholder="Enter quantity" value="1" required disabled/>
                <input type="hidden" name="productPrice[]" value="<?php echo $productPrice; ?>">
                <input type="hidden" class="calculatedProduct" id="totalPerItem_<?php echo $rowProduct['product_id']; ?>" value="0">
              </div>

              <script type="text/javascript">
                $(document).ready(function() {
                  $('#<?php echo $rowProduct['product_id']; ?>').change(function() {
                    if($(this).is(':checked')){
                      var productPrice = $(this).attr('data-product-price');
                      var quantity = $('#quantity_<?php echo $rowProduct['product_id']; ?>').val();
                      $('#totalPerItem_<?php echo $rowProduct['product_id']; ?>').val(productPrice * quantity);
                      $('#quantity_<?php echo $rowProduct['product_id']; ?>').attr('disabled', false);
                      calculate();
                    } else {
                      $('#quantity_<?php echo $rowProduct['product_id']; ?>').attr('disabled', true);
                      $('#totalPerItem_<?php echo $rowProduct['product_id']; ?>').val(0);
                      var quantity = $('#quantity_<?php echo $rowProduct['product_id']; ?>').val('1');
                      calculate();
                    }
                  });

                  $('#quantity_<?php echo $rowProduct['product_id']; ?>').keyup(function() {
                    var quantity = $(this).val();
                    var productPrice = $('#<?php echo $rowProduct['product_id']; ?>').attr('data-product-price');
                    $('#totalPerItem_<?php echo $rowProduct['product_id']; ?>').val(productPrice * quantity);
                    calculate();
                  });

                  function calculate() {
                    var total = 0;
                    $(".calculatedProduct").each(function(){
                        total += parseInt($(this).val());
                    });
                    $('.total').html('&#8369; '+total);
                    $('#total_allrequest').val(total);

                    var amountDeposit = $('#amount').val();

                    if(total > amountDeposit) {
                      $('.btnSubmit').attr('disabled', true);
                      $('#invalidMessage').html('<small class="text-danger">Your deposit amount is not enough!</small>');
                    }else{
                      $('.btnSubmit').attr('disabled', false);
                      $('#invalidMessage').html('');
                    }
                  }
                });
              </script>
              <?php } ?>
            </div>

            <div class="form-group mt-3">
              <input type="hidden" name="totalRequest" id="total_allrequest" value="0">
              <h5 class="text-white mb-0">Total: <span class="total font-weight-bolder" style="color: #ffd700;">&#8369; 0</span></h5>
              <span id="invalidMessage"></span>
            </div>
            
            <div class="form-group">
              <button type="button" data-toggle="modal" data-target="#submit_form" class="btn btn-success btn-block pt-2 pb-2 btnSubmit">PROCEED</button>
            </div>


            <div class="modal" id="submit_form">
              <div class="modal-dialog">
                <div class="modal-content" style="background-color: #151e27!important;">
                  <div class="modal-header pb-0" style="border: 0px;">
                    <h5 class="modal-title text-white" style="font-weight: bold;">Alert Message</h5>
                  </div>
                  <div class="modal-body pt-0 pb-0">
                    <p class="text-muted">Are you sure you want to submit?</p>
                  </div>
                  <div class="modal-footer pr-0 pl-0 pb-2 pt-0" style="display: block; border: 0px">
                    <div class="row">
                      <div class="col-6">
                        <button type="button" class="btn btn-default btn-lg btn-block" style="background: transparent; color: #fff;" data-dismiss="modal">Cancel</button>
                      </div>
                      <div class="col-6">
                        <button type="submit" name="save" class="btn btn-warning btn-lg btn-block withanimation_submit" style="background: #FFD700; border-color: #ffd700;">Yes, Submit</button>
                      </div>
                    </div>
                  </div>
                </form>
              </div>
            </div>
    </div>
  </section>
</div>
</div>

<script src="plugins/jquery/jquery.min.js"></script>
<script src="plugins/jquery-validation/jquery.validate.min.js"></script>
<script src="plugins/jquery-validation/additional-methods.min.js"></script>
<script src="plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#search').bind("change keyup input", function(){
  var search = $(this).val();
  if(search != '') {
    $("#result").show();
    $.ajax({
        url:'backend-search.php',
        method:"POST",
        data:{search:search, search_action:'search_member'},
        success:function(data){
          console.log(data);
          if (data != 0) {
            $('#result').html(data);
          }else{
            $('#result').html('<li class="list-group-item link-class disabled">No Result...</li>');
          }

        }
    });
  }else{
    $("#result").hide();
  }
});

var form = $("#userDetails");
  form.validate({ // initialize plugin
    ignore:":not(:visible)",      
    rules: {
      autocomplete : "required",
      store_name : "required",
      complete_address : "required"
    },

    errorElement: 'span',
    errorPlacement: function (error, element) {
      error.addClass('invalid-feedback');
      element.closest('.form-group').append(error);
    },
    highlight: function (element, errorClass, validClass) {
      $(element).addClass('is-invalid');
    },
    unhighlight: function (element, errorClass, validClass) {
      $(element).removeClass('is-invalid');
    }
  });

  $(".withanimation").click(function() {
    $(".loading").show();
  });
});

// if ( window.history.replaceState ) {
//   window.history.replaceState( null, null, window.location.href );
// }
</script>
</body>
</html>
