<!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>-->
                        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
                              <div class="d-flex justify-content-between align-items-center mb-3">
                            <!-- Left side: Title -->
                            <h4 class="card-title m-0">Manage Orders</h4>
                        
                            <!-- Right side: Search + Back button -->
                            <div class="d-flex align-items-center">
                                <input type="text" id="searchInput" class="form-control me-2" style="width: 200px;" placeholder="Search in table...">
                                <button class="btn btn-primary" onclick="history.back();">← Back</button>
                            </div>
                        </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;">Item Code</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";

                                    // Get order_id from GET, default to 0 if not set
                                    $order_id = isset($_GET['order_id']) ? (int)$_GET['order_id'] : 0;

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

                                    // Count total records filtered by order_id
                                    $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
                                                 WHERE o.id = $order_id";
                                    $countResult = mysqli_query($con, $countSql);
                                    $totalRecords = mysqli_fetch_assoc($countResult)['total'];
                                    $totalPages = ceil($totalRecords / $limit);

                                    // Fetch orders + customer name with pagination filtered by order_id
                                    $sql = "SELECT 
                                            oi.order_id AS order_id,
                                            oi.id AS item_order_id,
                                            oi.product_name,
                                            si.item_code,
                                            o.created_at,
                                            c.company_name,
                                            oi.total,
                                            oi.quantity,
                                            oi.issued_qty,
                                            oi.balance_qty,
                                            o.status,
                                            oi.status AS oistatus
                                        FROM orders o
                                        JOIN tbl_customers c ON o.customer_id = c.id
                                        JOIN order_items oi ON oi.order_id = o.id
                                        LEFT JOIN tbl_stock_items si ON si.id = oi.product_id
                                        WHERE o.id = $order_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 htmlspecialchars($row['created_at']); ?></td>
                                                <td>#<?php echo htmlspecialchars($row['order_id']); ?></td>
                                                <td><?php echo htmlspecialchars($row['item_code']); ?></td>
                                                <td><?php echo htmlspecialchars($row['product_name']); ?></td>
                                                <td><?php echo htmlspecialchars($row['company_name']); ?></td>
                                                <td><?php echo number_format($row['total'], 2); ?></td>
                                                <td><?php echo htmlspecialchars($row['quantity']); ?></td>
                                                <td><?php echo htmlspecialchars($row['issued_qty']); ?></td>
                                                <td><?php echo htmlspecialchars($row['balance_qty']); ?></td>
                                                <td><?php echo htmlspecialchars($row['oistatus']); ?></td>
                                                <td>
                                                    <?php if ($row['oistatus'] == 'Confirmed') { ?>
                                                        <!-- Issue -->
                                                         <?php if ((int)$row['quantity'] != $row['issued_qty']): ?>
                                                        <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>
                                                        <?php endif; ?>

                                                        <?php if ((int)$row['issued_qty'] === 0): ?>
                                                        <!-- Approve -->
                                                        <a href="#!" 
                                                           class="approveBtn text-success ms-2" 
                                                           data-id="<?php echo $row['item_order_id']; ?>">
                                                           <i class="fa fa-check text-success"></i>
                                                        </a>
                                                        <!-- Reject -->
                                                        <a href="#!"
                                                           class="rejectBtn text-danger ms-2"
                                                           data-id="<?php echo (int)$row['item_order_id']; ?>">
                                                           <i class="fa fa-close text-danger"></i>
                                                        </a>
                                                    <?php endif; ?>


                                                
                                                    <?php } elseif ($row['oistatus'] == 'Processing') { ?>
                                                        <!-- Issue -->
                                                        <?php if ((int)$row['quantity'] != $row['issued_qty']): ?>
                                                        <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>
                                                        <?php endif; ?>
                                                        <!-- Reject -->
                                                        <!--<a href="#!" -->
                                                        <!--   class="rejectBtn text-danger ms-2" -->
                                                        <!--   data-id="<?php echo $row['item_order_id']; ?>">-->
                                                        <!--   <i class="fa fa-close text-danger"></i>-->
                                                        <!--</a>-->
                                                        
                                                        <?php if ((int)$row['issued_qty'] === 0): ?>
                                                            <!-- Reject -->
                                                            <a href="#!"
                                                               class="rejectBtn text-danger ms-2"
                                                               data-id="<?php echo (int)$row['item_order_id']; ?>">
                                                               <i class="fa fa-close text-danger"></i>
                                                            </a>
                                                        <?php endif; ?>

                                                
                                                    <?php } elseif ($row['oistatus'] == 'Delivered') { ?>
                                                        <span class="badge bg-success">Delivered</span>
                                                
                                                    <?php } elseif ($row['oistatus'] == 'Cancelled') { ?>
                                                        <span class="badge bg-danger">Cancelled</span>
                                                    <?php } ?>
                                                </td>
                                                <td></td>
                                            </tr>
                                            <?php
                                        }
                                    } else {
                                        echo "<tr><td colspan='11' 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);
                                        });
                                    });

                                    // Delivered action (if you want to enable it, uncomment the HTML and this block)
                                    /*
                                    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") {
                                                // Reload page to reflect changes
                                                window.location.href = "manage_order.php?order_id=<?php echo $order_id; ?>&page=<?php echo $page; ?>";
                                            } 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="?order_id=<?php echo $order_id; ?>&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="?order_id=<?php echo $order_id; ?>&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="?order_id=<?php echo $order_id; ?>&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>
