<?php 
  if (!isset($_SESSION['username'])) {
    $_SESSION['msg'] = "To access this page, Login is required";
    header('location: login.php');
  }  ?>

<?php
$status="";
$amount="";

if (isset($_POST['action']) && $_POST['action']=="remove"){
if(!empty($_SESSION["shopping_cart"])) {
    foreach($_SESSION["shopping_cart"] as $key => $value) {
        if($_POST["code"] == $key){
        unset($_SESSION["shopping_cart"][$key]);
        $status = "<div class='msg-box'>
        Product is removed from your cart!</div>";
        }
        if(empty($_SESSION["shopping_cart"]))
        unset($_SESSION["shopping_cart"]);
            }       
        }
}

if (isset($_POST['action']) && $_POST['action']=="change"){
  foreach($_SESSION["shopping_cart"] as &$value){
    if($value['code'] === $_POST["code"]){
        $value['quantity'] = $_POST["quantity"];
        break; // Stop the loop after we've found the product
    }
}
    
}
?>
<html>
<head>
<style type="text/css">
    
.cart-cart{ float: left; width: 100%;  font-size: x-small; background: none; border: 1px solid whitesmoke; padding: 10px;   
 border-radius: 5px; margin-bottom: 2%;}
.cart-cart span {  background: orange; padding:8px; border-radius: 50%;  font-weight: bold; font-size: small; font-size: x-small; color: white;  position: relative; margin: 1%; }
.status { float: left; width: 100%; background: white; padding: 15px; font-size: x-small; color: red; border: 1px solid whitesmoke; border-radius: 4px; }

.remove { background: none; border: none; font-size: x-small; color: red; text-decoration: none;  margin-top: 5%;}

.cart-1{ float: right; font-size:larger; margin-top: -2%; }

.table-1 th { background: white; color: #7CB9E8;  padding:7px; font-weight: bold; }

.msg-box { float: left; width: 100%; background: white; padding: 10px; font-size: x-small; color: red; border: 1px solid whitesmoke; border-radius: 4px; margin-bottom: 1%;  }
.get-total { text-align: right; font-weight: bold; font-size:small; padding:8px;  }


</style>


</head>
<body>
<div>

<h4>Shopping Cart <i class="fa fa-shopping-cart cart-1"></i> </h4>  

<div>
<?php echo $status; ?>
</div>


<?php
if(!empty($_SESSION["shopping_cart"])) {
$cart_count = count(array_keys($_SESSION["shopping_cart"]));
?>
<div class="cart-cart">
<span><?php echo $cart_count; ?> </span> <a> items on carts</a> 
</div>
<?php
}
?>

<div class="cart">
<?php
if(isset($_SESSION["shopping_cart"])){
    $total_price = 0;
?>  
<table class="table-1">
<tbody>
<tr>
<th>Item name</th>
<th>Item Size</th>
<th>Quantity</th>
<th>Unit Price</th>
<th>Total Price</th>
</tr>   



<?php       
foreach ($_SESSION["shopping_cart"] as $product){
?>
<tr>

<td><?php echo $product["name"]; ?><br />
<form method='post' action=''>
<input type='hidden' name='code' value="<?php echo $product["code"]; ?>" />
<input type='hidden' name='action' value="remove" />
<button type='submit' class='remove'>Remove Item</button>
</form>
</td>

<td><?php echo $product["size"]; ?> </td>

<td>
<form method='post' action=''>
<input type='hidden' name='code' value="<?php echo $product["code"]; ?>" />
<input type='hidden' name='action' value="change" />
<select name='quantity' class='quantity' onchange="this.form.submit()">
<option <?php if($product["quantity"]==1) echo "selected";?> value="1">1</option>
<option <?php if($product["quantity"]==2) echo "selected";?> value="2">2</option>
<option <?php if($product["quantity"]==3) echo "selected";?> value="3">3</option>
<option <?php if($product["quantity"]==4) echo "selected";?> value="4">4</option>
<option <?php if($product["quantity"]==5) echo "selected";?> value="5">5</option>
<option <?php if($product["quantity"]==6) echo "selected";?> value="6">6</option>
<option <?php if($product["quantity"]==7) echo "selected";?> value="7">7</option>
<option <?php if($product["quantity"]==8) echo "selected";?> value="8">8</option>
<option <?php if($product["quantity"]==9) echo "selected";?> value="9">9</option>
<option <?php if($product["quantity"]==10) echo "selected";?> value="10">10</option>
<option <?php if($product["quantity"]==11) echo "selected";?> value="11">11</option>
<option <?php if($product["quantity"]==12) echo "selected";?> value="12">12</option>
<option <?php if($product["quantity"]==13) echo "selected";?> value="13">13</option>
<option <?php if($product["quantity"]==14) echo "selected";?> value="14">14</option>
<option <?php if($product["quantity"]==15) echo "selected";?> value="15">15</option>
<option <?php if($product["quantity"]==16) echo "selected";?> value="16">16</option>
<option <?php if($product["quantity"]==17) echo "selected";?> value="17">17</option>
<option <?php if($product["quantity"]==18) echo "selected";?> value="18">18</option>
<option <?php if($product["quantity"]==19) echo "selected";?> value="19">19</option>
<option <?php if($product["quantity"]==20) echo "selected";?> value="20">20</option>
<option <?php if($product["quantity"]==21) echo "selected";?> value="21">21</option>
<option <?php if($product["quantity"]==22) echo "selected";?> value="22">22</option>
<option <?php if($product["quantity"]==23) echo "selected";?> value="23">23</option>
<option <?php if($product["quantity"]==24) echo "selected";?> value="24">24</option>
<option <?php if($product["quantity"]==25) echo "selected";?> value="25">25</option>
<option <?php if($product["quantity"]==26) echo "selected";?> value="26">26</option>
<option <?php if($product["quantity"]==27) echo "selected";?> value="27">27</option>
<option <?php if($product["quantity"]==28) echo "selected";?> value="28">28</option>
<option <?php if($product["quantity"]==29) echo "selected";?> value="29">29</option>
<option <?php if($product["quantity"]==30) echo "selected";?> value="30">30</option>
<option <?php if($product["quantity"]==31) echo "selected";?> value="31">31</option>
<option <?php if($product["quantity"]==32) echo "selected";?> value="32">32</option>
<option <?php if($product["quantity"]==33) echo "selected";?> value="33">33</option>
<option <?php if($product["quantity"]==34) echo "selected";?> value="34">34</option>
<option <?php if($product["quantity"]==35) echo "selected";?> value="35">35</option>
<option <?php if($product["quantity"]==36) echo "selected";?> value="36">36</option>
<option <?php if($product["quantity"]==37) echo "selected";?> value="37">37</option>
<option <?php if($product["quantity"]==38) echo "selected";?> value="38">38</option>
<option <?php if($product["quantity"]==39) echo "selected";?> value="39">39</option>
<option <?php if($product["quantity"]==40) echo "selected";?> value="40">40</option>
<option <?php if($product["quantity"]==41) echo "selected";?> value="41">41</option>
<option <?php if($product["quantity"]==42) echo "selected";?> value="42">42</option>
<option <?php if($product["quantity"]==43) echo "selected";?> value="43">43</option>
<option <?php if($product["quantity"]==44) echo "selected";?> value="44">44</option>
<option <?php if($product["quantity"]==45) echo "selected";?> value="45">45</option>
<option <?php if($product["quantity"]==46) echo "selected";?> value="46">46</option>
<option <?php if($product["quantity"]==47) echo "selected";?> value="47">47</option>
<option <?php if($product["quantity"]==48) echo "selected";?> value="48">48</option>
<option <?php if($product["quantity"]==49) echo "selected";?> value="49">49</option>
<option <?php if($product["quantity"]==50) echo "selected";?> value="50">50</option>
</select>
</form>

</td>

<td><?php echo "KSH. ".$product["price"]; ?></td>
<td><?php echo "KSH. ".$product["price"]*$product["quantity"]; ?></td>
</tr>
<?php  if (isset($_POST["quantity"])) { $code = $product["code"];  $q1 = $_POST["quantity"]; 
$res = mysqli_query($db,"SELECT * FROM `products` WHERE code = '$code'");
  $r = mysqli_fetch_assoc($res);  $size = $r['size']; $q = $r['quantity'];    $new_q = ( $q -  $q1 );
if ($q < $product["quantity"]) {  echo "<script type= 'text/javascript'>alert('sorry ! few items in store for [ $name - $size ] - kindly shop again');</script>"; 

unset($_SESSION["shopping_cart"]); echo "<script type='text/javascript'>location.href = 'index.php?link=001release';</script>";
}
}


$total_price += ($product["price"]*$product["quantity"]);

}
?>
<tr>
<td colspan="5" > 
 <nav class="get-total"> 

  <button class="open-button" onclick="opencustomerForm()">CHECKOUT</button>

  TOTAL: <?php echo "KSH  ".$total_price; ?>/=</nav>

</td>
</tr>
</tbody>
</table>        
  <?php
}else{
    echo "<a class='status'>Your cart is empty!</a>";
  // echo "<script type='text/javascript'>location.href = 'index.php?link=manage-staffs';</script>";
// onclick="return confirm('Are you sure want to checkout and print report?');"
    }
?>
</div>
</div>
</body>
</html>



<script>
function opencustomerForm() {   document.getElementById("customerForm").style.display = "block"; }
function closecustomerForm() {   document.getElementById("customerForm").style.display = "none";  }

function showformHide() {
        let paymentmode = document.getElementById('payment')
        if (paymentmode.value == 1) {
                    document.getElementById('hidden-panel-c').style.display = 'none'
                     document.getElementById('hidden-panel-b').style.display = 'none'
        }
         else if (paymentmode.value == 2) {
             document.getElementById('hidden-panel-c').style.display = 'none'
             document.getElementById('hidden-panel-b').style.display = 'none'

        }

        else if (paymentmode.value == 3) {
             document.getElementById('hidden-panel-c').style.display = 'block'
             document.getElementById('hidden-panel-b').style.display = 'none'
        }

        else if (paymentmode.value == 4) {
             document.getElementById('hidden-panel-b').style.display = 'block'
              document.getElementById('hidden-panel-c').style.display = 'none'
        }

           else if (paymentmode.value == 5) {
             document.getElementById('hidden-panel-b').style.display = 'block'
              document.getElementById('hidden-panel-c').style.display = 'none'
        }

           else if (paymentmode.value == 6) {
             document.getElementById('hidden-panel-c').style.display = 'none'
              document.getElementById('hidden-panel-b').style.display = 'none'
        }

         else {
            document.getElementById(('hidden-panel-c') || ('hidden-panel-b')).style.display = 'none'
        }
    }



</script>

<style type="text/css">
  
  body {font-family: Arial, Helvetica, sans-serif;}
* {box-sizing: border-box;}

/* Button used to open the contact form - fixed at the bottom of the page */
.open-button { background: skyblue; color: white; font-weight: bold; border : 0px solid whitesmoke; padding: 6px; border-radius: 5px; margin-right: 5%;
}

/* The popup form - hidden by default */
.form-popup {  display: none; margin-top: 2%;  z-index: 9; }

/* Add styles to the form container */
.form-container {width: 90%; margin: auto; padding: 15px;  background-color: white;  box-shadow: 3px 2px 3px 3px  whitesmoke;  }

/* Full-width input fields */
.form-container input[type=text],.form-container select, .form-container input[type=password] { border-radius: 5px;
  width: 100%;  padding: 10px;  margin: 5px 0 22px 0;  border: none;  background:white; border:  1px solid  #f1f1f1;
}

.form-container label { font-size: x-small; margin: 2%; }
/* When the inputs get focus, do something */
.form-container input[type=text]:focus, .form-container input[type=password]:focus { background-color: #ddd;  outline: none;}

/* Set a style for the submit/login button */
.form-container .btn {  background-color: #04AA6D;  color: white;  padding: 16px 20px;  border: none;
  cursor: pointer;  width: 100%;  margin-bottom:10px;  opacity: 0.8; }

/* Add a red background color to the cancel button */
.form-container .cancel {  background-color: red; }

/* Add some hover effects to buttons */
.form-container .btn:hover, .open-button:hover {  opacity: 1;}

#hidden-panel-a , #hidden-panel-b, #hidden-panel-c { display: none; }


 </style>


<div class="form-popup" id="customerForm">
  <form action="" method="post" class="form-container">


    <h1> <i class="fa fa-user" style="margin-right: 5%; margin-left: 1%;"></i>Customer Billing   Details</h1>

    <input type="text" placeholder="Enter Customer Name eg . Joskin Doe" name="customer" required>

    <input type="text"  pattern="[0-9]{9,10}" placeholder="Customer Phone Number eg. 0708448164" name="phone" >

           <div id="drop-down" name="drop-down">
                    <label>Payment Mode</label>
          <select name="payment" onclick="showformHide()" id="payment"   >
             <option value="1" > CASH </option>
             <option value="2" > MPESA </option>
             <option value="3" > BOTH (MPESA & CASH)</option>
             <option value="4" > PARTIAL PAYMENT (With Mpesa Deposit) </option>
             <option value="5" > PARTIAL PAYMENT (With Cash Deposit) </option>
             <option value="6" > ON LOAN </option>
          </select>
        </div>

       <div name="hidden-panel-c" id="hidden-panel-c">
           <label style="font-size:x-small;">Specify Cash Amount Received only </label>
          <input type="text" name="cash_amount"  style="background:whitesmoke; color: black; font-weight: lighter;" placeholder="3000" />
       </div>

       <div name="hidden-panel-b" id="hidden-panel-b">
           <label style="font-size:x-small;">Specify  Amount Received  </label>
          <input type="text" name="amount_a"  style="background:whitesmoke; color: black; font-weight: lighter" placeholder="2000" />
       </div>



   <button type="submit" name="checkout" class="btn">Release Items & Generate Receipt</button>
   
  </form>
</div>


<?php include 'inc/config.php'; 
if (isset($_POST["checkout"])) { $code = $product["code"];
$username=$_SESSION['username'];  $customer= $_POST['customer'];  $phone= $_POST['phone']; $amount_a= $_POST['amount_a'];
$cash_amount= $_POST['cash_amount'];  $amount = $total_price;  $mode= $_POST['payment'];  $receipt = uniqid('ABH-');

  if ($_POST['payment'] == 1)  { $cash = $total_price; $balance = 0;    $mpesa =0; }
  else if ($_POST['payment'] == 2) {  $mpesa = $total_price; $balance = 0;    $cash =0; }
  else if ($_POST['payment'] == 3) {  $cash = $cash_amount;  $mpesa = $total_price - $cash;  $balance = 0; }
  else if ($_POST['payment'] == 4) {  $mpesa = $amount_a;  $balance = $total_price - $mpesa;  $cash = 0; }
  else if ($_POST['payment'] == 5) {  $cash = $amount_a;  $balance = $total_price - $cash;  $mpesa = 0; }
  else if($_POST['payment'] == 6) { $cash = 0;  $balance = $amount;  $mpesa = 0; }

   if ($amount_a > $amount  )  { 
     echo "<script type= 'text/javascript'>alert('Sorry [ $username ] Deposit Exceeds Total pay required');</script>";
     echo "<script type='text/javascript'>location.href = 'index.php?link=001release';</script>";
      }
elseif ($cash_amount > $amount ) { 
    echo "<script type= 'text/javascript'>alert('Sorry [ $username ] Cash amount exceeds total pay required');</script>";
     echo "<script type='text/javascript'>location.href = 'index.php?link=001release';</script>";
       } 
else {
  $sql_1 = "INSERT INTO earnings ( customer, phone, amount,mode, cash, mpesa, balance,receipt_no, session ) 
            VALUES ('$customer', '$phone', '$amount', '$mode', '$cash', '$mpesa', '$balance', '$receipt', '$username')";
            
            $db->query($sql_1);


foreach($_SESSION["shopping_cart"] as $product) {
 $name = $product["name"];  $code = $product["code"];  $size = $product["size"];    $quantity = $product["quantity"];   $price = $product["price"];
 $unit_totalprice = $quantity * $price ;  $amount_a= $_POST['amount_a'];  $total_price = $total_price;
 $new_qauntity =  $quantity; 

  $res = mysqli_query($db,"SELECT * FROM `products` WHERE code = '$code'");
  $r = mysqli_fetch_assoc($res);  $q = $r['quantity'];    $new_q = ( $q -  $quantity );
  
  //echo  $new_q;

 $sql = "INSERT INTO product_sales (customer,receipt_no, code, name,  size,  quantity,   price, unit_totalprice,  session ) 
    VALUES ('$customer','$receipt', '$code' ,  '$name',  '$size', '$quantity', '$price', '$unit_totalprice', '$username')";

     $sql_2 = "UPDATE products SET quantity  = '$new_q' WHERE code = '$code'"; 


if ( ($db->query($sql) === TRUE)  AND ($db->query($sql_2) === TRUE)   ) {
 echo "<script type= 'text/javascript'>alert('$name  - $size succesfully released.');</script>";

  //include "pdf/receipt.php";
   }

else{ echo "<script type= 'text/javascript'>alert('sorry  ! system is unable to release items purchased by [$customer].');</script>";  }


   }
  }
 unset($_SESSION["shopping_cart"]);
 echo "<script type='text/javascript'>location.href = 'index.php?link=001release';</script>";




}


?> 