<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Pipscart</title>
    <!-- plugins:css -->
    <link rel="stylesheet" href="assets/vendors/mdi/css/materialdesignicons.min.css">
    <link rel="stylesheet" href="assets/vendors/ti-icons/css/themify-icons.css">
    <link rel="stylesheet" href="assets/vendors/css/vendor.bundle.base.css">
    <link rel="stylesheet" href="assets/vendors/font-awesome/css/font-awesome.min.css">
    <!-- endinject -->
    <!-- Plugin css for this page -->
    <link rel="stylesheet" href="assets/vendors/bootstrap-datepicker/bootstrap-datepicker.min.css">
    <!-- End plugin css for this page -->
    <!-- inject:css -->
    <!-- endinject -->
    <!-- Layout styles -->
    <link rel="stylesheet" href="assets/css/style.css">
    <!-- End layout styles -->
</head>
<body>
    <div class="container-scroller">
        <?php
        session_start();
        $userid   = $_SESSION['user_id'] ?? 0;
        $username = $_SESSION['username'] ?? 'Guest';
        include "header.php"; 
        ?>
        <div class="container-fluid page-body-wrapper">
            <?php include "sidebar.php"; ?>
            <style>
                .table .thead-dark th {
                    color: #fff;
                    background-color: #212529;
                    border-color: #32383e;
                }
            </style>
            <div class="main-panel">
                <div class="content-wrapper">
                    <div class="row g-1">
                        <div class="col-md-12 grid-margin stretch-card">
                            <div class="card">
                                <div class="card-body" style="padding: 15px;">
                                    <div class="d-flex justify-content-between">
                                        <h4 class="card-title w-50">Manage Orders</h4>
                                        <input type="text" id="searchInput" class="mb-3 w-25" placeholder="Search in table...">
                                    </div>
                                    <div class="table-responsive">
                                        <table class="table table-striped table-bordered">
                                            <thead class="thead-dark">
                                                <tr>
                                                    <th style="width: 10px;">Order date</th>
                                                    <th style="width: 10px;">Order no</th>
                                                    <th style="width: 10px;">Product Name</th>
                                                    <th style="width: 200px;">Company name</th>
                                                    <th style="width: 10px;">Amount</th>
                                                    <th style="width: 10px;">Qty</th>
                                                    <th style="width: 10px;">I.Qty</th>
                                                    <th style="width: 10px;">B.Qty</th>
                                                    <th style="width: 10px;">Status</th>
                                                    <th style="width: 10px;">Action</th>
                                                    <th></th>
                                                </tr>
                                            </thead>
                                            <tbody id="tableBody">
                                                <?php
                                                include "config.php";

                                                // Pagination variables
                                                $limit = 10; // Number of records per page
                                                $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
                                                $offset = ($page - 1) * $limit;

                                                // Count total records
                                                $countSql = "SELECT COUNT(*) as total FROM orders o JOIN tbl_customers c ON o.customer_id = c.id JOIN order_items oi ON oi.order_id = o.id";
                                                $countResult = mysqli_query($con, $countSql);
                                                $totalRecords = mysqli_fetch_assoc($countResult)['total'];
                                                $totalPages = ceil($totalRecords / $limit);

                                                // Fetch orders + customer name with pagination
                                                $sql = "SELECT 
                                                    oi.order_id AS order_id,
                                                    oi.id AS item_order_id,
                                                    oi.product_name,
                                                    o.created_at,
                                                    c.company_name,
                                                    oi.total,
                                                    oi.quantity,
                                                    oi.issued_qty,
                                                    oi.balance_qty,
                                                    o.status
                                                FROM orders o
                                                JOIN tbl_customers c ON o.customer_id = c.id
                                                JOIN order_items oi ON oi.order_id = o.id
                                                ORDER BY o.created_at DESC
                                                LIMIT $limit OFFSET $offset";

                                                $result = mysqli_query($con, $sql);

                                                if (mysqli_num_rows($result) > 0) {
                                                    while ($row = mysqli_fetch_assoc($result)) {
                                                        ?>
                                                        <tr>
                                                            <td><?php echo $row['created_at']; ?></td>
                                                            <td>#<?php echo $row['order_id']; ?></td>
                                                            <td><?php echo $row['product_name']; ?></td>
                                                            <td><?php echo $row['company_name']; ?></td>
                                                            <td><?php echo number_format($row['total'], 2); ?></td>
                                                            <td><?php echo $row['quantity']; ?></td>
                                                            <td><?php echo $row['issued_qty']; ?></td>
                                                            <td><?php echo $row['balance_qty']; ?></td>
                                                            <td><?php echo $row['status']; ?></td>
                                                            <td>
                                                            <?php if ($row['status'] == 'Confirmed') { ?>
                                                                <!-- Issue -->
                                                                <!--<a href="#"-->
                                                                <!--   class="editBtn"-->
                                                                <!--   data-id="<?php echo $row['item_order_id']; ?>"-->
                                                                <!--   data-issued="<?php echo $row['issued_qty']; ?>"-->
                                                                <!--   data-bs-toggle="modal"-->
                                                                <!--   data-bs-target="#exampleModal">-->
                                                                <!--   <i class="fa fa-archive text-primary"></i> -->
                                                                 <!--</a>-->
                                                                
                                                                <!-- Delivered -->
                                                                    <a href="#!" 
                                                                       class="deliveredBtn text-success ms-2" 
                                                                       data-id="<?php echo $row['order_id']; ?>">
                                                                       <i class="fa fa-truck text-primary"></i>
                                                                    </a>                                                               
                                                        
                                                                <!-- Approve -->
                                                                <a href="#!" 
                                                                   class="approveBtn text-success ms-2" 
                                                                   data-id="<?php echo $row['order_id']; ?>">
                                                                   <i class="fa fa-check text-success"></i>
                                                                </a>
                                                        
                                                                <!-- Reject -->
                                                                <a href="#!" 
                                                                   class="rejectBtn text-danger ms-2" 
                                                                   data-id="<?php echo $row['order_id']; ?>">
                                                                   <i class="fa fa-close text-danger"></i>
                                                                </a>
                                                        
                                                            <?php } elseif ($row['status'] == 'Processing') { ?>
                                                                <!-- Issue -->
                                                                <!--<a href="#"-->
                                                                <!--   class="editBtn"-->
                                                                <!--   data-id="<?php echo $row['item_order_id']; ?>"-->
                                                                <!--   data-issued="<?php echo $row['issued_qty']; ?>"-->
                                                                <!--   data-bs-toggle="modal"-->
                                                                <!--   data-bs-target="#exampleModal">-->
                                                                <!--   <i class="fa fa-archive text-primary"></i> -->
                                                                <!--</a>-->
                                                                
                                                                <!-- Delivered -->
                                                                    <a href="#!" 
                                                                       class="deliveredBtn text-success ms-2" 
                                                                       data-id="<?php echo $row['order_id']; ?>">
                                                                       <i class="fa fa-truck text-primary"></i>
                                                                    </a>
                                                        
                                                                <!-- Reject -->
                                                                <a href="#!" 
                                                                   class="rejectBtn text-danger ms-2" 
                                                                   data-id="<?php echo $row['order_id']; ?>">
                                                                   <i class="fa fa-close text-danger"></i>
                                                                </a>
                                                        
                                                            <?php } elseif ($row['status'] == 'Delivered') { ?>
                                                                <span class="badge bg-success">Delivered</span>
                                                        
                                                            <?php } elseif ($row['status'] == 'Cancelled') { ?>
                                                                <span class="badge bg-danger">Cancelled</span>
                                                            <?php } ?>
                                                            
                                                            
                                                        </td>




                                                            <td></td>
                                                        </tr>
                                                        <?php
                                                    }
                                                } else {
                                                    echo "<tr><td colspan='10' class='text-center text-danger'>No orders found</td></tr>";
                                                }
                                                ?>
                                            </tbody>
                                        </table>
                                        <!-- Modal -->
                                        <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
                                            <div class="modal-dialog">
                                                <div class="modal-content">
                                                    <div class="modal-header">
                                                        <h5 class="modal-title" id="exampleModalLabel">Issue Quantity</h5>
                                                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                    </div>
                                                    <div class="modal-body">
                                                        <form id="issueForm" method="POST" action="update_issue.php">
                                                            <input type="hidden" name="order_id" id="order_id">
                                                            <div class="form-group">
                                                                <label for="issued_qty">Issued Quantity</label>
                                                                <input type="number" class="form-control" name="issued_qty" id="issued_qty" required>
                                                            </div>
                                                            <div class="modal-footer">
                                                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                                                <button type="submit" class="btn btn-primary">Issue</button>
                                                            </div>
                                                        </form>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <script>
                                            document.addEventListener("DOMContentLoaded", function() {
                                                document.querySelectorAll(".editBtn").forEach(btn => {
                                                    btn.addEventListener("click", function() {
                                                        let orderId = this.getAttribute("data-id");
                                                        let issuedQty = this.getAttribute("data-issued");
                                                        document.getElementById("order_id").value = orderId;
                                                        document.getElementById("issued_qty").value = issuedQty;
                                                    });
                                                });
                                            });
                                        </script>

                                        <script>
                                            document.addEventListener("DOMContentLoaded", function() {
                                                // Approve action
                                                document.querySelectorAll(".approveBtn").forEach(btn => {
                                                    btn.addEventListener("click", function(e) {
                                                        e.preventDefault();
                                                        let orderId = this.getAttribute("data-id");
                                                        updateOrderStatus(orderId, "approve", this);
                                                    });
                                                });

                                                // Reject action
                                                document.querySelectorAll(".rejectBtn").forEach(btn => {
                                                    btn.addEventListener("click", function(e) {
                                                        e.preventDefault();
                                                        let orderId = this.getAttribute("data-id");
                                                        updateOrderStatus(orderId, "reject", this);
                                                    });
                                                });
                                                
                                                // Reject action
                                                document.querySelectorAll(".deliveredBtn").forEach(btn => {
                                                    btn.addEventListener("click", function(e) {
                                                        e.preventDefault();
                                                        let orderId = this.getAttribute("data-id");
                                                        updateOrderStatus(orderId, "Delivered", this);
                                                    });
                                                });

                                                function updateOrderStatus(orderId, action, element) {
                                                    fetch("order_action.php", {
                                                        method: "POST",
                                                        headers: { "Content-Type": "application/x-www-form-urlencoded" },
                                                        body: "id=" + orderId + "&action=" + action
                                                    })
                                                    .then(res => res.text())
                                                    .then(data => {
                                                        if (data.trim() === "success") {
                                                            let row = element.closest("tr");
                                                            let statusCell = row.querySelector("td:nth-child(8)"); // status column
                                                            window.location.href = "manage_order.php";
                                                            // if (action === "approve") {
                                                            //     statusCell.textContent = "confirmed";
                                                            //     statusCell.classList.remove("text-danger");
                                                            //     statusCell.classList.add("text-success");
                                                            //     row.querySelector(".approveBtn").style.display = "none";
                                                            // } else if (action === "reject") {
                                                            //     statusCell.textContent = "cancelled";
                                                            //     statusCell.classList.remove("text-success");
                                                            //     statusCell.classList.add("text-danger");
                                                            //     row.querySelector(".approveBtn").style.display = "none";
                                                            //     row.querySelector(".rejectBtn").style.display = "none";
                                                            // }
                                                        } else {
                                                            alert("Error updating status");
                                                        }
                                                    });
                                                }
                                            });
                                        </script>

                                        <script>
                                            document.getElementById("searchInput").addEventListener("keyup", function () {
                                                let filter = this.value.toLowerCase();
                                                let rows = document.querySelectorAll("#tableBody tr");
                                                rows.forEach(row => {
                                                    let text = row.innerText.toLowerCase();
                                                    row.style.display = text.includes(filter) ? "" : "none";
                                                });
                                            });
                                        </script>
                                    </div>
                                    <!-- Pagination -->
                                    <nav aria-label="Page navigation example">
                                        <ul class="pagination mt-3 d-flex justify-content-center">
                                            <li class="page-item <?php if ($page <= 1) echo 'disabled'; ?>">
                                                <a class="page-link" href="?page=<?php echo max(1, $page - 1); ?>">
                                                    <i class="fa fa-angle-left"></i>
                                                </a>
                                            </li>
                                            <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                                                <li class="page-item <?php if ($i == $page) echo 'active'; ?>">
                                                    <a class="page-link" href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                                                </li>
                                            <?php endfor; ?>
                                            <li class="page-item <?php if ($page >= $totalPages) echo 'disabled'; ?>">
                                                <a class="page-link" href="?page=<?php echo min($totalPages, $page + 1); ?>">
                                                    <i class="fa fa-angle-right"></i>
                                                </a>
                                            </li>
                                        </ul>
                                    </nav>
                                    <div id="traffic-chart-legend" class="rounded-legend legend-vertical legend-bottom-left pt-4"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- content-wrapper ends -->
                <footer class="footer">
                    <div class="d-sm-flex justify-content-center justify-content-sm-between">
                        <span class="text-muted text-center text-sm-left d-block d-sm-inline-block">Copyright © <span id="year">2025</span> <a href="https://www.bootstrapdash.com/" target="_blank"></a>. All rights reserved.</span>
                        <span class="float-none float-sm-right d-block mt-1 mt-sm-0 text-center">Developed by <a href="www.programers.in" target="_blank">Programers.in</a></span>
                    </div>
                </footer>
                <script>
                    document.addEventListener("DOMContentLoaded", function () {
                        let fileName = window.location.pathname.split("/").pop().split(".")[0];
                        fileName = fileName.charAt(0).toUpperCase() + fileName.slice(1);
                        document.title = fileName;
                    });
                </script>
                <script>
                    document.getElementById("year").textContent = new Date().getFullYear();
                </script>
            </div>
            <!-- page-body-wrapper ends -->
        </div>
        <!-- container-scroller -->
        <!-- plugins:js -->
        <script src="assets/vendors/js/vendor.bundle.base.js"></script>
        <!-- endinject -->
        <!-- Plugin js for this page -->
        <script src="assets/vendors/chart.js/chart.umd.js"></script>
        <script src="assets/vendors/bootstrap-datepicker/bootstrap-datepicker.min.js"></script>
        <!-- End plugin js for this page -->
        <!-- inject:js -->
        <script src="assets/js/off-canvas.js"></script>
        <script src="assets/js/misc.js"></script>
        <script src="assets/js/settings.js"></script>
        <script src="assets/js/todolist.js"></script>
        <script src="assets/js/jquery.cookie.js"></script>
        <!-- endinject -->
        <!-- Custom js for this page -->
        <script src="assets/js/dashboard.js"></script>
        <!-- End custom js for this page -->
    </body>
</html>
