<?php session_start();?>
<?php include'includes/header.php'; ?>
<?php include'includes/sidebar.php';?>
<?php include'includes/functions.php';?>
<?php include'includes/navbar.php'; ?>

<!-- Handle Add Slider -->
<style>
td span{
padding: 10px;
border-radius: 6px;
font-size: 13px;
}
.success_stutus{
    background: #E8FCEF; color: #4ECA74;
}
.error_status{
    background: #F8D7DA; color: #90151C;
}
.invoice-cust{
  padding-top: 20px;
}
.invoice-cust h4{
  font-size: 17px;
}
.invoice-cust span{
  font-size: 16px;
  font-weight: bold;
}
.total h4{
  font-size: 18px;
  font-weight: bold;
}
.summary {
  background-color: #f1f1f1;
  padding: 15px;
  margin-top: 20px;
  border-radius: 8px;
}

.summary h3 {
  margin-bottom: 10px;
  color: #444;
}

.summary p {
  margin: 5px 0;
}
select{
    width: 180px;
    height: 40px;
    border:2px solid #ccc;
    border-radius: 5px;
    outline: none;
    padding-left: 10px;
} 
</style>

<?php
if (isset($_SESSION['orderId'])) {
    $orderId = $_SESSION['orderId'];
    $status = "pending";
    // Get the current date
    $dateTime = date('Y-m-d H:i:s');
    $rmvTime = explode(" ", $dateTime);
    $created = $rmvTime[0];
    // Search the cust's info using their orderId
    $search = "SELECT user_Id FROM order_items WHERE order_no = ? AND status = ?";
    $thepdo = $pdo->prepare($search);
    $thepdo->execute([$orderId, $status]);
    $NoOrder = $thepdo->rowCount();
    $orderRow = $thepdo->fetch(PDO::FETCH_ASSOC);
    $userId = $orderRow['user_Id'];

    // Now decrypt this userId to find cust info.
    $decrUserId = decryptData($userId);
    // Finding the customer Id using their userId
    $cust = "SELECT * FROM account WHERE mobile = ?";
    $custpdo = $pdo->prepare($cust);
    $custpdo->execute([$decrUserId]);
    $custRow = $custpdo->fetch(PDO::FETCH_ASSOC);
    // get all info
    $firstname = $custRow['firstname'];
    $lastname = $custRow['lastname'];
    $mobile = $custRow['mobile'];
    $email = $custRow['email'];
    $fullName = $firstname.' '.$lastname;
    // =================================
    // Loop each productId and quantity to get their info
    $totalPrice = 0;
    $proset = "SELECT * FROM order_items 
             WHERE order_no = ? AND status = ?";
    $setpdo = $pdo->prepare($proset);
    $setpdo->execute([$orderId, $status]);
    while ($setRow = $setpdo->fetch(PDO::FETCH_ASSOC)) {
        $uniqueId = $setRow['orderId'];
        $prodId = $setRow['product_id'];
        $quantity = $setRow['quantity'];
    // Using prodId to find each products information
    $proInfo = "SELECT prodName, prodImg, unit_price, quantity, 
                (unit_price * ?) AS prices 
                FROM products WHERE prodId = ?";
    $propdo = $pdo->prepare($proInfo);
    $propdo->execute([$quantity, $prodId]);
        while ($prodRow = $propdo->fetch(PDO::FETCH_ASSOC)) {
            $prodName = $prodRow['prodName'];
            $prodImg   = $prodRow['prodImg'];
            $price      = $prodRow['unit_price'];
            $total_unit_Price = $prodRow['prices'];
            $totalPrice += $total_unit_Price;
        }
    }
      
}else{
    // if the session not found, return back to order page.
    header("Location:order.php");
}

// If the print button is pressed 
if (isset($_POST['pay-btn'])) {
    $payment = $_POST['payment'];
    $orderId;
    $status = "pending";
    $new_status = "Supplied"; 
    $invoiceNo = 'INV-' . str_pad(mt_rand(1, 999999), 6, '0', STR_PAD_LEFT);
    $mobile; // customer mobile number

    // Declearing the success alert messages.
    $success;
    $msgTitle     = "Payment Notification";
    $msgBody      = "You have Successfully supplied Customer <b>$firstname</b> 
                    Their requested products.
                     <br><br> 
                     Would you like to generate an invoice for the product(s)?
                     ";

    $msgCloseBtn  = "No, Cancel";
    $msgActionBtn = "Yes, Generate Invoice";
    $ActionBtn    = "yes";
    require'includes/order-page-alert.php';

    $proset = "SELECT * FROM order_items 
             WHERE order_no = ? AND status = ?";
    $setpdo = $pdo->prepare($proset);
    $setpdo->execute([$orderId, $status]);
    while ($setRow = $setpdo->fetch(PDO::FETCH_ASSOC)) {
        $uniqueId = $setRow['orderId']; // The table unique Id
        $prodId = $setRow['product_id'];
        $quantity = $setRow['quantity'];
    // Using prodId to find each products information
    $proInfo = "SELECT prodName, unit_price, quantity 
                FROM products WHERE prodId = ?";
    $propdo = $pdo->prepare($proInfo);
    $propdo->execute([$prodId]);
        while ($prodRow = $propdo->fetch(PDO::FETCH_ASSOC)) {
            $prodName   = $prodRow['prodName'];
            $price      = $prodRow['unit_price'];
            $dataQty    = $prodRow['quantity'];

        // Save the items to history table
        $hist = "INSERT INTO history 
                (invoiceId, customer, amount, payment_type, prodName, quantity, cashier, created)
                VALUES(?, ?, ?, ?, ?, ?, ?, ?)";
        $histpdo = $pdo->prepare($hist);
        $histpdo->execute([$invoiceNo, $mobile, 
                    $price, $payment, $prodName, 
                    $quantity, $username, $created]);
        // Since we have inserted the details into history table
        // Then update status in order_items table
        $update = "UPDATE order_items SET status = ? WHERE orderId = ? ";
        $updapdo = $pdo->prepare($update);
        $updapdo->execute([$new_status, $uniqueId]);

        // Now remove the requested quantity from the original quantity
        $newQty = $dataQty - $quantity;
        $remqty = "UPDATE products SET quantity = ? WHERE prodId = ? ";
        $rempdo = $pdo->prepare($remqty);
        $rempdo->execute([$newQty, $prodId]);

        }
    }   
}
// If the cancel in the success-alert is pressed: go to order page
// instead of returning to the order_market page
if (isset($_POST['cancel-btn'])) {
    header("Location:order.php");
}


?>
<?php
include'includes/order-page-invoice-print.php';
?>
<div id="notification-containers" class="notification-containers"></div>
<div class="insider">
    <div class="container">
        <div class="cat-pag">
            <div class="cat-page-header d-flex justify-content-between align-items-center">
                <h5>Pending Products</h5>
                <div>
                    <form action="" method="POST">
                        <select name="payment" required="">
                            <option value="" hidden="">Select Method</option>
                            <option value="Cash">Cash</option>
                            <option value="Pos">Pos</option>
                            <option value="Transfer">Transfer</option>
                        </select>
                        
                        <button class="btn btn-success" name="pay-btn">Pay Now 
                            <i class="fa fa-print"></i>
                        </button>
                    </form>
                </div>
            </div>
            <div class="invoice-cust">
              <table>
                <tr>
                  <td><span>Full Name:</span></td>
                  <td style="padding-left: 10px;"><?=$fullName?></td>
                </tr>
                
                <tr>
                  <td><span>Order No:</span></td>
                  <td style="padding-left: 10px;"><?= $orderId?></td>
                </tr>
                
                <tr>
                  <td><span>No Product:</span></td>
                  <td style="padding-left: 10px;"><?=$NoOrder?></td>
                </tr>
                
                <tr>
                  <td><span>Total:</span></td>
                  <td style="padding-left: 10px;">₦<?php echo number_format($totalPrice, 2) ?></td>
                </tr>
              </table>  
            </div>
            <div class="card mt-3">
                <div class="card-header text-center">
                    <h5>Awaiting Products</h5>
                </div>
                <div class="card-body">
                    <form action="" method="POST" id="mainForm">
                        <div class="table-responsive">
                            <table id="example" class="display table table-striped table-bordered">
                                <thead>
                                    <tr>
                                        <th><input type="checkbox" id="SelectAllBoxes"></th>
                                        <th>ID</th>
                                        <th>Images</th>
                                        <th>Product Name</th>
                                        <th>Unit Price</th>
                                        <th>Quantity</th>
                                        <th>Product Status</th>
                                       
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $sn = 0;
                                    // Loop each productId and quantity to get their info
                                    $proset = "SELECT * FROM order_items 
                                             WHERE order_no = ? AND status = ?";
                                    $setpdo = $pdo->prepare($proset);
                                    $setpdo->execute([$orderId, $status]);
                                    while ($setRow = $setpdo->fetch(PDO::FETCH_ASSOC)) {
                                        $prodId = $setRow['product_id'];
                                        $quantity = $setRow['quantity'];
                                    // Using prodId to find each products information
                                    $proInfo = "SELECT * FROM products WHERE prodId = ?";
                                    $propdo = $pdo->prepare($proInfo);
                                    $propdo->execute([$prodId]);
                                    while ($prodRow = $propdo->fetch(PDO::FETCH_ASSOC)) {
                                        $prodName = $prodRow['prodName'];
                                        $prodImg   = $prodRow['prodImg'];
                                        $price      = $prodRow['unit_price'];

                                        $sn = $sn + 1;

                                        $split = explode(',', $prodImg);
                                        $firstImg = $split[0];

                                        if ($quantity > 0) {
                                            $prodStatus = "Available";
                                            $status_type = 'success_stutus';
                                        }else{
                                            $prodStatus = "Not Available";
                                            $status_type = 'error_status'; 
                                        }  
                                    ?>
                                    <tr>
                                        <td>
                                            <input type="checkbox" name="checkBoxArray[]" value="<?= $prodId ?>" class='checkBoxes'>
                                        </td>
                                        <td><?= $sn ?></td>
                                        <td>
                                            <img src="<?php echo $firstImg;?>" style="width:50px; height:50px;">
                                        </td>
                                        <td>
                                            <?php
                                            if (strlen($prodName) > 20) {
                                                echo substr($prodName, 0, 20).'...';
                                            }else{
                                                echo $prodName;
                                            }?>
                                        </td>
                                        <td>₦<?php echo $price;?></td>
                                        <td><?php echo $quantity;?></td>
                                        <td style="text-align: center; padding-top: 20px;"><span class="<?php echo $status_type?>"><?php echo $prodStatus;?></span></td>
                                    </tr> 
                                    <?php } } ?>
                                </tbody>
                            </table>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>




<?php include 'includes/footer.php'; ?>

<!-- DataTables & jQuery -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>

<script>
    $(document).ready(function () {
        $('#example').DataTable();
        $('#SelectAllBoxes').click(function () {
            $('.checkBoxes').prop('checked', this.checked);
        });
    });

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

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

    function handleDelete() {
        const checked = document.querySelectorAll("input[name='checkBoxArray[]']:checked");
        if (checked.length === 0) {
            alert("No products selected!");
            return;
        }
        openModal('modal-delete');
    }
   
</script>


<!-- Modal Styling -->
<style>
    .modal {
        display: none;
        position: fixed;
        z-index: 99999;
        left: 0; top: 0;
        width: 100%; height: 100%;
        overflow: auto;
        background-color: rgba(0,0,0,0.5);

    }

    .modal-content {
        background-color: #fff;
        margin: auto;
        padding: 20px;
        border-radius: 8px;
        width: 80%;
        max-width: 500px;
        animation: fadeIn 0.3s;
    }

    .modal-header, .modal-footer {
        font-weight: bold;
    }

    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(-20px); }
        to { opacity: 1; transform: translateY(0); }
    }

    /*.input-group button{
      background: #fff; 
      border-top-right-radius: 1px; 
      border-bottom-right-radius: 1px; 
      outline: none; 
      border:0.9px solid gray
    }
    .input-group input{
      border:0.9px solid gray
    }*/
    .label-wraps{
        width: 100%;
        padding-left: 30px;
        padding-right: 30px;
        display: flex;
        justify-content: space-between;
      
    }
    .input-wraps{
        width: 100%;
        display: flex;
        gap:8px;
        padding: 5px;
    }
    .price-box{
        width: 50%;
        height: 55px;
        /*border-bottom: 2px solid #ddd;*/
        border:2px solid #ddd;
        padding: 15px;
        border-radius: 10px;
    }
    .price-box span{
        font-size: 18px;
        color: #666;
        /*font-weight: bold;*/
    }
    .price-box input{
        width: 85%;
        
        border:none;
        outline: none;
        font-size: 16px;
        color: 888;
       /* height: 20px;*/
    }
    .quant-box{
        width: 50%;
        height: 55px;
        /*border-bottom: 2px solid #ddd;*/
        border:2px solid #ddd;
        padding: 15px;
        border-radius: 10px;
    }
    .quant-box input{
        width: 100%;
        border:none;
        outline: none;
        font-size: 16px;
        color: 888;
    }
</style>


<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";
    }
</script>
<!-- Notifications alert -->
<?php include'includes/notification-alert-js.php';?>

