<?php session_start();?>
<?php include'includes/header.php'; ?>
<?php include'includes/sidebar.php';?>
<?php include'includes/functions.php';?>
<?php include'includes/navbar.php'; ?>
<style>.sideNav{height:90vh;}

.insider{
  margin-top: -60px;
  /*margin-left: -30px;*/
}

</style>
<?php
// $_SESSION['customer'] = "Taiwo Tosin";
$_SESSION['username'] = 'Juwonlo';
if (isset($_SESSION['customer'])) {
  $customer = $_SESSION['customer'];

}

// Save Product
if (isset($_POST['add-btn'])) {
  $product_price  = $_POST['product'];
  $quantity       = $_POST['quantity'];
  $mode           = $_POST['mode'];

  $rmv = explode('-', $product_price);
  $product = $rmv[0]; // product name
  $price = $rmv[1]; // product price

  // validate product
  $valid = "SELECT * FROM products WHERE prodName = ?";
  $valPdo = $pdo->prepare($valid);
  $valPdo->execute([$product]);
  $valRow = $valPdo->fetch(PDO::FETCH_ASSOC);
  $valQuant = $valRow['quantity'];

  if ($quantity > $valQuant) {
    
    $difference = $quantity - $valQuant;

    require'validate.php';

  }else{
    // save to catalog db
    $insert = "INSERT INTO catalog(customer, product, price, quantity, mode, username)
              VALUES(?, ?, ?, ?, ?, ?)";
    $instPdo = $pdo->prepare($insert);
    if ($instPdo->execute([$customer, $product, $price, $quantity, $mode, $username])) {
      $_SESSION['message'] = 'Added Successfully';
      $_SESSION['type'] = 'success';
    }else{
      $_SESSION['message'] = 'Something went wrong';
      $_SESSION['type'] = 'error';
    }
  }

}

// Update Product quantity
if (isset($_POST['upd-product'])) {
  $edit_quant = $_POST['quantity'];
  $catalogId = $_POST['edit-id'];
  $prodName   = $_POST['prodName'];
  // get the same product from the products db
  $sql = "SELECT quantity FROM products WHERE prodName = ? ";
  $query = $pdo->prepare($sql);
  $query->execute([$prodName]);
  $data_row = $query->fetch(PDO::FETCH_ASSOC);
  $data_quant = $data_row['quantity'];

  if ($edit_quant > $data_quant) {
     // warning message
    $msgTitle     = "Quantity Update Exceeds Stock";
    $msgBody      = "You’re trying to update the product quantity in the cart to 
                      <b>$edit_quant</b> quantities, 
                      but only <b>$data_quant</b> quantities are currently available in stock. <br> Please reduce the quantity or restock before updating.";
    $msgCloseBtn  = "Cancel the update and leave quantity unchanged."; 
    require'includes/alertMsg-blur.php';
   }else{
    $update = "UPDATE catalog SET quantity = ?
              WHERE catalogId = ?";
    $updPdo = $pdo->prepare($update);
    if ($updPdo->execute([$edit_quant, $catalogId])) {
      $_SESSION['message'] = 'Updated Successfully';
      $_SESSION['type'] = 'info';
    }else{
      $_SESSION['message'] = 'Something went wrong';
      $_SESSION['type'] = 'error';
    
    }

   } 
  
}

// Handle Delete queue product in the catalog
if (isset($_POST['DeleteBtn'])) {
  $cart_prodName  = $_POST['cart_prodName'];
  $cart_quantity  = $_POST['cart_quantity'];

  $catalogId = $_POST['catalogId'];
  $del = "DELETE FROM catalog WHERE catalogId = ?";
  $delPdo = $pdo->prepare($del);
  if ($delPdo->execute([$catalogId])) {
    // search and remove the exact product in wallet db
    $sech = "DELETE FROM wallet 
          WHERE customer = ? AND products = ? AND supplied_quant = ?";
    $sechPdo = $pdo->prepare($sech);
    $sechPdo->execute([$customer, $cart_prodName, $cart_quantity]);
    
    // if ($sechPdo->execute([$customer, $cart_prodName, $cart_quantity, $cart_price ])) {
      
    // }
    $_SESSION['message'] = 'Product Removed Successfully';
    $_SESSION['type'] = 'success';
    
  }else{
    $_SESSION['message'] = 'Something went wrong';
    $_SESSION['type'] = 'error';
  }
  
}

?>

<!-- Insufficient Requested Products  -->
<?php
if (isset($_POST['Alert-Btn'])) {
  echo "<script>alert('We got here')</script>";
    $product    = $_POST['product'];
    $quantity   = $_POST['quantity'];
    $valQuant   = $_POST['valQuant'];
    $difference = $_POST['difference'];
    $price      = $_POST['price'];
    // $mode       = $_POST['mode'];
    $customer;
    $username;
    $created            = date("Y-m-d H:i:s");
    $requested_quant    = $quantity;
    $available_quant    = $valQuant;
    $owed_quant         = $difference;
    $amount_paid        = $price * $quantity;
    $amount_owed        = $price * $difference;

    // save into wallet
    $db = "INSERT INTO wallet(
            customer, products, created, requested_quant, 
            supplied_quant, owed_quant, amount_paid, amount_owed, username)
            VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)";
    $dbStmt = $pdo->prepare($db);
    if(
      $dbStmt->execute([$customer, $product, 
      $created, $requested_quant, 
      $available_quant, $owed_quant, $amount_paid, 
      $amount_owed, $username])) {
      // save into the catalog table

      $cata = " INSERT INTO catalog(customer, product, price, quantity, username)
                VALUES(?, ?, ?, ?, ?)";
      $cataPdo = $pdo->prepare($cata);
      
      if ($cataPdo->execute([$customer, $product, $price, $available_quant, $username])) {
        $_SESSION['message'] = 'Added Successfully';
        $_SESSION['type'] = 'success';
      }else{
        $_SESSION['message'] = 'Something went wrong.';
        $_SESSION['type'] = 'error';
      }

    }else{
        $_SESSION['message'] = 'Unable to process the stock.';
        $_SESSION['type'] = 'error';
    }
    
}else{
  echo "<script>alert('We have not seen anything')</script>";
}

?>
<?php

// When the print button is pressed, do these:
if (isset($_POST['print-invoice'])) {
  $walletId = 'WAL-' . str_pad(mt_rand(1, 999999), 6, '0', STR_PAD_LEFT); 
  $invoiceId = 'INV-' . str_pad(mt_rand(1, 999999), 6, '0', STR_PAD_LEFT);
  $created = date('Y-m-d H:i:s');

  $invoice_case = "cart";
  include'includes/invoice-print.php';

  // select the total products in cart db for customer
  $set = "SELECT * FROM catalog WHERE customer = ?";
  $thePdo = $pdo->prepare($set);
  $thePdo->execute([$customer]);
  while ($rows = $thePdo->fetch(PDO::FETCH_ASSOC)) {
    $catalog_id = $rows['catalogId'];
    $prodName = $rows['product'];
    $price    = $rows['price'];
    $cust_qty = $rows['quantity'];
    $mode     = $rows['mode'];

    // get the original quantity from products
  $ori = "SELECT quantity FROM products WHERE prodName = ?";
  $oriPdo = $pdo->prepare($ori);
  $oriPdo->execute([$prodName]);
  while ($qtyRow = $oriPdo->fetch(PDO::FETCH_ASSOC)) {
    $ori_qty = $qtyRow['quantity'];

    // deduct the customer quantity from the original quantity
    $deduct = $ori_qty - $cust_qty;
    
    // update the quantity in products db
    $upd_qty = "UPDATE products SET quantity = ? WHERE prodName = ?";
    $upd_qty_pdo = $pdo->prepare($upd_qty);
    $upd_qty_pdo->execute([$deduct, $prodName]);

    // delete every product in cart for this customer
    $del_cart = "DELETE FROM catalog WHERE catalogId = ?";
    $del_cart_pdo = $pdo->prepare($del_cart);
    $del_cart_pdo->execute([$catalog_id]);

    // move the products to history db
   
    $amount  = $price * $cust_qty;
    $move = "INSERT INTO history (customer, invoiceId, amount, payment_type, prodName, quantity, cashier, created)
            VALUES(?, ?, ?, ?, ?, ?, ?, ?)";
    $movePdo = $pdo->prepare($move);
    $movePdo->execute([$customer, $invoiceId, $amount, $mode, $prodName, $cust_qty, $username, $created]);

    // Then update wallet if there a need.
    $walUpd = "UPDATE wallet SET walletNo = ?
              WHERE products = ? AND supplied_quant = ? AND customer = ?";
    $walPdo = $pdo->prepare($walUpd);
    $walPdo->execute([$walletId, $prodName, $cust_qty, $customer]);

    // trigger the print button 
    // include'includes/invoice-print.php';
  


  }

  }
  
}

?>


<div id="notification-containers" class="notification-containers"></div>
<div class="insider">
  <div class="row">
    <div class="col-lg-6">
      <form action="" method="POST">
        <div class="invoice-bg">
          <div class="invoice-head">
            <input type="number" name="quantity" placeholder="Enter Quantity" required="" autocomplete="off">
            <select name="mode" required="">
              <option value="" hidden="">Mode</option>
              <option value="Cash">Cash</option>
              <option value="Pos">Pos</option>
              <option value="Transfer">Transfer</option>
            </select>
            <button class="" name="add-btn">Add Now <i class="fa fa-plus-circle"> </i> </button>
            <!-- <a href="" class="btn btn-primary">Continue</a> -->
          </div>
          <div class="prod-bg">
            <div class="prod-area">
              <!-- <div class="">
                <span>Select Product</span>
              </div> -->
              <div class="dropdown-container">
                <input type="text" class="search-box" id="searchBox" placeholder="Search for product..." oninput="filterOptions()" onclick="showOptions()" autocomplete="off">
                <div class="options" id="optionsList">
                  <h5>All Products</h5>
                  <?php

                  // Get Products
                  $prod = "SELECT * FROM products WHERE quantity > ?";
                  $stmt = $pdo->prepare($prod);
                  $stmt->execute([0]);
                  while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                    $prodName = $row['prodName'];
                    $unit_price = $row['unit_price'];
                  ?>
                  <div class="option-item" onclick="selectOption('<?php echo $prodName." - $unit_price";?>')">
                    <?php echo $prodName;?>  <span>₦<?php echo $unit_price;?></span>
                  </div>
                  <?php }?>
                </div>
                 <!-- Hidden input for form submission -->
                <input type="hidden" name="product" id="selectedValue">
              </div>

            </div>
          </div>
          <div class="ess-bg">
          </div>
        </div>
      </form>
    </div>
    <!-- the other side (right side) -->
    <div class="col-lg-6 mg-l">
      <div class="side2">
        <div class="head-side2">
         <span><i class="fa fa-user"></i> <?php echo $customer;?></span>
         <div class="right-mod">
          <span><i class="fa fa-cart-plus"></i></span>
          <label id="countNumber"></label>
          </div>
        </div>
        <div class="body-side2">
          <!-- <div class="sing-prod">
            <h2>Product name should be here</h2>
          </div> -->
          <div class="table-bg">
            <?php
            // Get selected prdouct
            $records = "SELECT * FROM catalog WHERE customer = ? ORDER BY catalogId DESC";
            $theStmt = $pdo->prepare($records);
            $theStmt->execute([$customer]);
            $checker = $theStmt->rowCount();

            if ($checker > 0) {
              $rev = "show";
              $valRecords = "showNot";
            }else{
              $rev = "showNot";
              $valRecords = "show";
            }

            ?>
            <div class="record" id="<?php echo $valRecords;?>">
              <h2>Oops.. No Records</h2>
              <i class="fa fa-history"></i>
            </div>
            <table class="table table-hover table-bordered" id="<?php echo $rev;?>">
              <thead>
                <tr>
                  <th>Product Name</th>
                  <th>Price</th>
                  <th>Quantity</th>
                  <th>Action</th>
                </tr>
              </thead>
              <tbody>
                <?php
                while ($dataRow = $theStmt->fetch(PDO::FETCH_ASSOC)) {
                  $catalogId = $dataRow['catalogId'];
                  $prodName = $dataRow['product'];
                  $price    = $dataRow['price'];
                  $quantity = $dataRow['quantity'];
                  $mode     = $dataRow['mode'];
                
                ?>
                <tr>
                  <td><?php echo $prodName;?></td>
                  <td>₦<?php echo $price;?></td>
                   <td><?php echo $quantity;?></td>
                  <td>
                    <div class="action-btn">
                      <button class="btn btn-danger" onclick="openModal('modal-delete-<?= $catalogId ?>')" title="Remove this product"><i class="fa fa-trash"></i></button>
                      <button class="btn btn-primary" onclick="openModal('modal-<?= $catalogId ?>')" title="Edit this product"><i class="fa fa-edit"></i></button>
                    </div>
                  </td>
                </tr>

                <div id="modal-<?= $catalogId ?>" class="modal">
                  <div class="modal-content" style="margin-top:100px;">
                     <div class="modal-header">Change Quantity</div>
                      <div class="modal-body">
                       <!-- Input form starts here -->
                        <form action="" method="POST" enctype="multipart/form-data">
                         
                         <input type="hidden" name="edit-id" value="<?= $catalogId ?>">
                         <input type="hidden" name="prodName" value="<?php echo $prodName;?>">
                         <label>Product Name:</label>
                         <input type="text" class="form-control" disabled="" name="prod-name" value="<?= htmlspecialchars($prodName) ?>" required>
                         <!-- Quantity -->
                         <small>Change Quantity</small>
                         <div class="quant-box">
                           <input type="number" name="quantity" step="0.01" min="0" autocomplete="off" placeholder="Quantity" value="<?php echo $quantity;?>" required>
                         </div>
     
                         <button name="upd-product" class="btn btn-success mt-2">Update Product</button>
                        </form>
                       <!-- End Form action -->
                      </div>
                     <!-- End Modal body -->
                     <div class="modal-footer">
                       <button type="button" class="btn btn-danger" onclick="closeModal('modal-<?= $catalogId ?>')">Cancel</button>
                     </div>

                   </div>
                   <!-- Modal Content -->
                </div>
                <!-- Modal overall -->

                <!-- Delete Confirmation Modal -->
                <div id="modal-delete-<?= $catalogId ?>" class="modal">
                  <div class="modal-content" style="margin-top:150px;">
                    <div class="modal-header">Delete Confirmation</div>
                    <div class="modal-body">Are you sure you want to remove 
                      <b><?php echo $prodName;?></b> from the list?
                    </div>

                    <form action="" method="POST">
                      <div class="modal-footer">
                        <input type="hidden" name="catalogId" value="<?php echo $catalogId;?>">
                        <input type="hidden" name="cart_prodName" value="<?php echo $prodName;?>">
                        <input type="hidden" name="cart_price" value="<?php echo $price;?>">
                        <input type="hidden" name="cart_quantity" value="<?php echo $quantity;?>">

                        <button type="button" class="btn btn-secondary" 
                          onclick="closeModal('modal-delete-<?= $catalogId ?>')">No, Cancel</button>
                        <button type="submit" name="DeleteBtn" class="btn btn-danger">Yes, Remove</button>
                      </div>
                    </form> 
                  </div>
                </div>

                <?php }?>
                
              </tbody>
              
            </table>
          </div>

          <?php

          $counter = "SELECT COUNT(catalogId) AS catNo, SUM(quantity) AS totalQuant,
                      SUM(quantity * price) AS totalPrice 
                      FROM catalog WHERE customer = ? ";
          $countStmt = $pdo->prepare($counter);
          $countStmt->execute([$customer]);

          $countData = $countStmt->fetch(PDO::FETCH_ASSOC);

          $totalRow = $countData['catNo'];
          $totalQuant = $countData['totalQuant'];
          $total    = $countData['totalPrice'];

          ?>
          <form action="" method="POST">
            <?php

            ?>
            <div class="bottom-details">
              <span>Total items: <?php echo $totalRow;?> | Total Quantity: <?php echo $totalQuant;?></span>
              <div class="print-in">
                <div class="total-amount">
                  <i class="fa fa-shopping-basket"></i><label>|</label> <span>₦<?php echo $total;?></span>
                </div>
                
                <button name="print-invoice" class="printer-btn" title="Print this invoice">
                  <i class="fa fa-print" title="Print this invoice"></i>
                </button>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>

  </div>



</div>


<script>

  // Modal script;
  function openModal(id) {
      document.getElementById(id).style.display = "block";
  }

  function closeModal(id) {
      document.getElementById(id).style.display = "none";
  }

  function handleDelete() {    
    openModal('modal-delete');
  }

  function closeModal(id){
    document.getElementById(id).style.display = "none";
  }


  const searchBox = document.getElementById('searchBox');
  const optionsList = document.getElementById('optionsList');
  const selectedValue = document.getElementById('selectedValue');

  function showOptions() {
    optionsList.style.display = 'block';
  }

  function filterOptions() {
    let input = searchBox.value.toLowerCase();
    let options = document.querySelectorAll('.option-item');
    optionsList.style.display = 'block'; // Always show when typing

    options.forEach(option => {
      let text = option.textContent.toLowerCase();
      option.style.display = text.includes(input) ? 'block' : 'none';
    });
  }

  function selectOption(value) {
    searchBox.value = value;
    selectedValue.value = value;
    optionsList.style.display = 'none';
  }

  // Optional: hide when clicking outside
  // document.addEventListener('click', function(event) {
  //   if (!event.target.closest('.dropdown-container')) {
  //     optionsList.style.display = 'none';
  //   }
  // });
</script>

<script>
  function CountNotification(){
   fetch("refresh/notify-counter.php",{
    method: 'POST'
   })
   .then(response=>{
    if (!response.ok) {
      throw new Error('The network is bad');
    }
    return response.text();
   })
   .then(data=>{
    document.getElementById('countNumber').innerHTML = data;
   })
   .catch(error=>{
    console.log('Soemthing went wrong');
   })
   
  }
  CountNotification();
  setInterval(CountNotification, 2000);

  // display all products
  // function DisplayAllProducts(){
  //   fetch("refresh/all_products.php",{
  //     method: 'POST'
  //   })
  //   .then(response=>{
  //     if (!response.ok) {
  //       throw new Error('Network is bad');
  //     }
  //     return response.text();
  //   })
  //   .then(data=>{
  //     document.getElementById('optionsList').innerHTML = data;
  //   })
  //   .catch(error=>{
  //     console.log("something went wrong");
  //   })
  // }
  // DisplayAllProducts();
  // setInterval(DisplayAllProducts, 2000);
</script>
  
<?php include'includes/notification-alert-js.php';?>
 <?php include'includes/footer.php';?>
<!-- learn to act as if nothing bothers you | Napoleon hill -->