<!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/font-awesome/css/font-awesome.min.css" />
      <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 -->
      <!-- <link rel="shortcut icon" href="assets/images/favicon.png" /> -->
   </head>
   <body>
      <div class="container-scroller">
         <!-- partial:partials/_navbar.html -->
         <!-- partial:partials/_navbar.html -->
    
            <?php
         session_start();
               //  $userid = $_SESSION['user_id'] ;
               //  $username = $_SESSION['username'] ;
                 $userid   = $_SESSION['user_id'] ?? 0;
               $username = $_SESSION['username'] ?? 'Guest';
           
            include "header.php"; 
            
            ?>
         <!-- partial -->
         <div class="container-fluid page-body-wrapper">
            <!-- partial:partials/_sidebar.html -->
            <?php
               include "sidebar.php";
               ?>
            <!-- partial -->
            <!-- partial -->
            <style>
               .table .thead-dark th {
               color: #fff;
               background-color: #212529;
               border-color: #32383e;
               }
            </style>
            <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">

            <div class="main-panel">
               <div class="content-wrapper">
                  <div class="page-header">
                     <h3 class="page-title">
                        <span class="page-title-icon bg-gradient-primary text-white me-2">
                        <i class="mdi mdi-home"></i>
                        </span> Dashboard
                     </h3>
                     <nav aria-label="breadcrumb">
                        <ul class="breadcrumb">
                           <li class="breadcrumb-item active" aria-current="page">
                              <!--<span></span>Overview <i class="mdi mdi-alert-circle-outline icon-sm text-primary align-middle"></i>-->
                           </li>
                        </ul>
                     </nav>
                  </div>
                  <div class="row">
                     <div class="col-md-12 grid-margin stretch-card">
                        <div class="card">
                           <div class="card-body" style="padding: 15px;">
                              <h4 class="card-title">Orders</h4>
                              <div class="table-responsive">
                                 <!-- ✅ Success / Error message section -->
                                 <?php if (isset($_GET['msg'])): ?>
                                    <div class="alert alert-<?php echo htmlspecialchars($_GET['type'] ?? 'success'); ?>">
                                          <?php echo htmlspecialchars($_GET['msg']); ?>
                                    </div>
                                 <?php endif; ?>

                                 <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: 200px;">Company name</th>
                                          <th style="width: 10px;">Amount</th>
                                          <th style="width: 10px;">T.Items</th>
                                          <th style="width: 10px;">Status</th>
                                          <!--<th style="width: 10px;">Action</th>-->
                                          <th>View</th>
                                       </tr>
                                    </thead>
                                    <?php
                                        include "config.php"; // DB connection
                                        
                                        // Pagination settings
                                        $limit = 20; // rows per page
                                        $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
                                        if ($page < 1) $page = 1;
                                        $offset = ($page - 1) * $limit;
                                        
                                        // Count total records (orders)
                                        $total_query = "SELECT COUNT(*) AS total FROM orders";
                                        $total_result = mysqli_query($con, $total_query);
                                        $total_row = mysqli_fetch_assoc($total_result);
                                        $total_records = $total_row['total'];
                                        $total_pages = ceil($total_records / $limit);
                                        
                                        // Fetch paginated data with item count
                                        $query = "
                                                SELECT 
                                                    o.id,
                                                    c.company_name,
                                                    o.total_amount,
                                                    o.created_at,
                                                    COUNT(d.id) AS item_count,
                                                    CASE 
                                                        WHEN SUM(CASE WHEN d.status = 'Delivered' THEN 1 ELSE 0 END) = COUNT(d.id) 
                                                            AND COUNT(d.id) > 0
                                                        THEN 'Delivered'
                                                        WHEN SUM(CASE WHEN d.status = 'Cancelled' THEN 1 ELSE 0 END) = COUNT(d.id) 
                                                            AND COUNT(d.id) > 0
                                                        THEN 'Cancelled'
                                                        ELSE 'Pending'
                                                    END AS status
                                                FROM orders o
                                                LEFT JOIN tbl_customers c ON o.customer_id = c.id
                                                LEFT JOIN order_items d ON o.id = d.order_id
                                                GROUP BY o.id
                                                ORDER BY o.created_at DESC
                                                LIMIT $offset, $limit
                                            ";
                                        $result = mysqli_query($con, $query);
                                        ?>
                                        
                                        <tbody>
                                        <?php
                                        if ($result && mysqli_num_rows($result) > 0) {
                                            while ($row = mysqli_fetch_assoc($result)) {
                                                // Add "table-secondary" class if cancelled
                                                $row_class = ($row['status'] === "Cancelled") ? "table-secondary text-muted" : "";
                                        
                                            //     echo '<tr class="' . $row_class . '">
                                            //     <td>' . htmlspecialchars($row['created_at']) . '</td>
                                            //     <td>
                                            //     <a href="manage.php?order_id=' . urlencode($row['id']) . '">
                                            //         #' . htmlspecialchars($row['id']) . '
                                            //     </a>
                                            // </td>
                                            //     <td>' . htmlspecialchars($row['company_name']) . '</td>
                                            //     <td>' . htmlspecialchars($row['total_amount']) . '</td>
                                            //     <td>' . htmlspecialchars($row['item_count']) . '</td>
                                            //     <td>' . htmlspecialchars($row['status']) . '</td>
                                            //     <td>
                                            //         <a href="view_items.php?order_id=' . urlencode($row['id']) . '">
                                            //             <i class="bi bi-eye"></i>
                                            //         </a>';
                                            echo '<tr class="' . $row_class . '" style="cursor:pointer;" data-href="manage.php?order_id=' . urlencode($row['id']) . '">
                                                <td>' . htmlspecialchars($row['created_at']) . '</td>
                                                <td>#' . htmlspecialchars($row['id']) . '</td>
                                                <td>' . htmlspecialchars($row['company_name']) . '</td>
                                                <td>' . htmlspecialchars($row['total_amount']) . '</td>
                                                <td>' . htmlspecialchars($row['item_count']) . '</td>
                                                <td>' . htmlspecialchars($row['status']) . '</td>
                                                <td>
                                                    <a href="view_items.php?order_id=' . urlencode($row['id']) . '" onclick="event.stopPropagation();">
                                                        <i class="bi bi-eye"></i>
                                                    </a>
                                                </td>
                                            </tr>';

                                                    
                                        // Add edit option only if condition is true
                                        // if ($row['status'] != 'Delivered' && $row['status'] != 'Cancelled' && $row['issued_qty'] == 0) {
                                        //     echo ' <a href="order-form1.php?order_id=' . urlencode($row['id']) . '" class="ms-2">
                                        //                 <i class="fa fa-pencil text-warning"></i>
                                        //             </a>';
                                        // }
                                        
                                        echo '   </td>
                                              </tr>';
                                        
                                            }
                                        } else {
                                            echo '<tr><td colspan="7">No orders found</td></tr>';
                                        }
                                        ?>
                                        
                                        </tbody>
                                        
                                        </table>
                                         <script>
                                        document.addEventListener("DOMContentLoaded", function() {
                                            document.querySelectorAll("tr[data-href]").forEach(function(row) {
                                                row.addEventListener("click", function() {
                                                    window.location.href = this.dataset.href;
                                                });
                                            });
                                        });
                                         </script>
                                        </div>
                                       

                                        <!-- Pagination -->
                                        <nav aria-label="Page navigation example">
                                            <ul class="pagination mt-3 d-flex justify-content-center">
                                                <!-- Previous -->
                                                <li class="page-item <?php if ($page <= 1) echo 'disabled'; ?>">
                                                    <a class="page-link" href="?page=<?php echo ($page-1); ?>">
                                                        <i class="fa fa-angle-left"></i>
                                                    </a>
                                                </li>
                                        
                                                <!-- Page Numbers -->
                                                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                                    <li class="page-item <?php if ($page == $i) echo 'active'; ?>">
                                                        <a class="page-link" href="?page=<?php echo $i; ?>">
                                                            <?php echo $i; ?>
                                                        </a>
                                                    </li>
                                                <?php endfor; ?>
                                        
                                                <!-- Next -->
                                                <li class="page-item <?php if ($page >= $total_pages) echo 'disabled'; ?>">
                                                    <a class="page-link" href="?page=<?php echo ($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>
                     </div>
                  </div>
               </div>
               <!-- content-wrapper ends -->
               <!-- partial:partials/_footer.html -->
               <?php
                  $title = "Php Header Footer";
                  include "footer.php";
                  ?>
               <!-- partial -->
            </div>
            <!-- main-panel ends -->
         </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>