<?php 
		require("header.php");
?>
  <main class="main-content position-relative border-radius-lg ">
    <!-- Navbar -->
      <nav class="navbar navbar-main navbar-expand-lg px-0 mx-4 shadow-none border-radius-xl " id="navbarBlur" data-scroll="false">
      <div class="container-fluid py-1 px-3">
        <nav aria-label="breadcrumb">
          <ol class="breadcrumb bg-transparent mb-0 pb-0 pt-1 px-0 me-sm-6 me-5">
            <li class="breadcrumb-item text-sm"><a class="opacity-5 text-white" href="javascript:;">Pages</a></li>
            <li class="breadcrumb-item text-sm text-white active" aria-current="page">Dashboard</li>
          </ol>
          <h6 class="font-weight-bolder text-white mb-0">Dashboard</h6>
        </nav>
        <div class="collapse navbar-collapse mt-sm-0 mt-2 me-md-0 me-sm-4" id="navbar">
          <ul class="navbar-nav  justify-content-end">
            <li class="nav-item d-xl-none ps-3 d-flex align-items-center">
              <a href="javascript:;" class="nav-link text-white p-0" id="iconNavbarSidenav">
                <div class="sidenav-toggler-inner">
                  <i class="sidenav-toggler-line bg-white"></i>
                  <i class="sidenav-toggler-line bg-white"></i>
                  <i class="sidenav-toggler-line bg-white"></i>
                </div>
              </a>
            </li>
            
            
          </ul>
        </div>
      </div>
    </nav>
    <!-- End Navbar -->
    <?php
    $sql = "SELECT COUNT(*) AS count FROM a_orders WHERE OrderStatus='Pending'";
    $result = mysqli_query($con, $sql);
    while ($row = mysqli_fetch_assoc($result)) {
      $active_order = $row["count"];
    }
    ?>

    <div class="container-fluid py-4">
      <div class="row">
        <div class="col-xl-3 col-sm-6 mb-xl-0 mb-4">
          <div class="card">
            <div class="card-body p-3">
              <div class="row">
                <div class="col-8">
                  <div class="numbers">
                    <p class="text-sm mb-0 text-uppercase font-weight-bold">Active Orders</p>
                    <h5 class="font-weight-bolder">
                      <?php echo $active_order ?>
                    </h5>
                  </div>
                </div>
                <div class="col-4 text-end">
                  <div class="icon icon-shape bg-gradient-primary shadow-primary text-center rounded-circle">
                    <i class="ni ni-money-coins text-lg opacity-10" aria-hidden="true"></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <?php
        $sql = "SELECT COUNT(*) AS count FROM a_orders WHERE OrderStatus='Completed'";
        $result = mysqli_query($con, $sql);
        while ($row = mysqli_fetch_assoc($result)) {
          $all_orders = $row["count"];
        }
        ?>

        <div class="col-xl-3 col-sm-6 mb-xl-0 mb-4">
          <div class="card">
            <div class="card-body p-3">
              <div class="row">
                <div class="col-8">
                  <div class="numbers">
                    <p class="text-sm mb-0 text-uppercase font-weight-bold">Completed Orders</p>
                    <h5 class="font-weight-bolder">
                      <?php echo $all_orders ?>
                    </h5>
                  </div>
                </div>
                <div class="col-4 text-end">
                  <div class="icon icon-shape bg-gradient-danger shadow-danger text-center rounded-circle">
                    <i class="ni ni-world text-lg opacity-10" aria-hidden="true"></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <?php
        $sql = "SELECT
        s.SpecificationID,
        s.S_description,
        SUM((od.D_Quantity * (od.D_Price - s.S_cost))) AS TotalProfit FROM a_specifications s JOIN a_orderdetails od ON s.SpecificationID = od.D_SpecificationID_FK GROUP BY s.SpecificationID, s.S_description";
        $result = mysqli_query($con, $sql);
        if(!$result){
            echo mysqli_error($con);
        }
        while ($row = mysqli_fetch_assoc($result)) {
          $specificationID = $row['SpecificationID'];
          $totalProfit= $totalProfit + $row['TotalProfit'];

        }
        ?>
        <div class="col-xl-3 col-sm-6 mb-xl-0 mb-4">
          <div class="card">
            <div class="card-body p-3">
              <div class="row">
                <div class="col-8">
                  <div class="numbers">
                    <p class="text-sm mb-0 text-uppercase font-weight-bold">Total Profits</p>
                    <h5 class="font-weight-bolder text-success">
                      <?php echo $totalProfit ?>$
                    </h5>
                  </div>
                </div>
                <div class="col-4 text-end">
                  <div class="icon icon-shape bg-gradient-success shadow-success text-center rounded-circle">
                    <i class="ni ni-paper-diploma text-lg opacity-10" aria-hidden="true"></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <?php
        $sql = "SELECT COUNT(*) AS count FROM a_orders ";
        $result = mysqli_query($con, $sql);
        while ($row = $row = mysqli_fetch_assoc($result)) {
          $count_p = $row["count"];
        }
        ?>
        <div class="col-xl-3 col-sm-6">
          <div class="card">
            <div class="card-body p-3">
              <div class="row">
                <div class="col-8">
                  <div class="numbers">
                    <p class="text-sm mb-0 text-uppercase font-weight-bold">Total Odrders</p>
                    <h5 class="font-weight-bolder">
                      <?php echo $count_p ?>
                    </h5>
                  </div>
                </div>
                <div class="col-4 text-end">
                  <div class="icon icon-shape bg-gradient-warning shadow-warning text-center rounded-circle">
                    <i class="ni ni-cart text-lg opacity-10" aria-hidden="true"></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="row mt-4">
        <div class="col-lg-7 mb-lg-0 mb-4">
          <div class="card z-index-2 h-100">
            <div class="card-header pb-0 pt-3 bg-transparent">
              <h6 class="text-capitalize">Sales overview</h6>

            </div>
            <div class="card-body p-3">
                  <div class="year-dropdown">
                <label for="year">Select Year: </label>
                <select id="year">
                  <?php
                  $currentYear = date('Y');
                  for ($year = $currentYear; $year >= 2023; $year--) {
                    echo "<option value=\"$year\">$year</option>";
                  }
                  ?>
                </select>
              </div>
                
              <div class="chart">
                <canvas id="chart-line" class="chart-canvas" height="300"></canvas>
              </div>
            </div>
          </div>
        </div>
        <div class="col-lg-5">
          <div class="card card-carousel overflow-hidden h-100 p-0">
            <div id="demo" class="carousel slide" data-bs-ride="carousel">
              <?php
              $query = "SELECT * FROM a_slider";
              $result = mysqli_query($con, $query);

              $firstItem = true; // Variable to track the first item
              $slideNumber = 0; // Initialize a variable to track the slide number
              ?>
              <div class="carousel-indicators">
                <?php
                while ($row = mysqli_fetch_assoc($result)) {
                  $activeClass = ($slideNumber === 0) ? 'active' : '';
                ?>
                  <button type="button" data-bs-target="#demo" data-bs-slide-to="<?php echo $slideNumber; ?>" class="<?php echo $activeClass; ?>"></button>
                <?php
                  $slideNumber++;
                }
                ?>
              </div>
              <?php
              // Reset the result set pointer
              mysqli_data_seek($result, 0);
              ?>
              <div class="carousel-inner">
                <?php
                while ($row = mysqli_fetch_assoc($result)) {
                  $slider_id = $row['SliderID'];
                  $slider_image = $row['SliderImage'];
                  $imageurl = '' . $slider_image;

                  // Determine whether this is the first item in the loop
                  $activeClass = $firstItem ? 'active' : '';
                  $firstItem = false; // Set it to false after the first item

                ?>
                  <div class="carousel-item <?php echo $activeClass; ?>">
                    <img src="<?php echo $imageurl ?>" alt="Slider Image" class="d-block w-100" style="width: 300px; height: 350px;">
                    <div class="carousel-icons">
                      <!-- Delete Icon -->
                      <a href="#" class="carousel-icon delete-icon" data-bs-toggle="modal" data-bs-target="#deleteModal<?php echo $slider_id; ?>">
                        <i class="fas fa-trash-alt"></i>
                      </a>
                      <!-- Edit Icon -->
                      <a href="#" class="carousel-icon edit-icon" data-bs-toggle="modal" data-bs-target="#updateModal<?php echo $slider_id; ?>">
                        <i class="fas fa-edit"></i>
                      </a>
                    </div>
                  </div>
                  <!-- Delete Modal -->
                  <div class="modal fade" id="deleteModal<?php echo $slider_id; ?>" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
                    <div class="modal-dialog">
                      <div class="modal-content">
                        <div class="modal-header">
                          <h5 class="modal-title" id="deleteInstructorModalLabel">Confirm Deletion</h5>
                          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                          <p>Are you sure you want to delete this Image?</p>
                        </div>
                        <div class="modal-footer">
                          <!-- Button to confirm the deletion -->
                          <button class="btn btn-danger deleteBtnImg" id="" data-bs-dismiss="modal" data-slider-id="<?php echo $slider_id; ?>">Delete</button>
                          <!-- Button to close the modal without deleting -->
                          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        </div>
                      </div>
                    </div>
                  </div>

                  <!-- Update Modal -->
                  <div class="modal fade" id="updateModal<?php echo $slider_id; ?>" tabindex="-1" role="dialog" aria-labelledby="updateModalLabel" aria-hidden="true">
                    <div class="modal-dialog">
                      <div class="modal-content">
                        <div class="modal-header">
                          <h5 class="modal-title" id="">Update Image</h5>
                          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                          <!-- Form for editing Item details -->
                          <form>
                            <div class="mb-3">
                              <label for="editColor" class="form-label">Image</label>
                              <input type="file" class="form-control" id="editImage<?php echo $slider_id ?>" required>
                              <img src="<?php echo $imageurl ?>" alt="" width="100" height="70" class="mt-3">
                            </div>
                          </form>
                        </div>
                        <div class="modal-footer">
                          <!-- Button to save the edited category -->
                          <button type="button" class="btn btn-success EditbtnImg" data-bs-dismiss="modal" data-slider-id="<?php echo $slider_id; ?>">Save</button>
                          <!-- Button to close the modal without saving changes -->
                          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        </div>
                      </div>
                    </div>
                  </div>
                <?php
                }
                ?>
              </div>
              <button class="carousel-control-prev" type="button" data-bs-target="#demo" data-bs-slide="prev">
                <span class="carousel-control-prev-icon"></span>
              </button>
              <button class="carousel-control-next" type="button" data-bs-target="#demo" data-bs-slide="next">
                <span class="carousel-control-next-icon"></span>
              </button>
            </div>
            <div class="d-flex align-items-center justify-content-center">
            
              <form action="">
                <input type="file" class="" id="addSliderImage" required>
                <button class="btn btn-sm mt-3" id="submitbtn">Add Image</button>
              </form>
            </div>
          </div>

        </div>
      </div>

<div class="row">
        <div class="col-12 my-4">
          <div class="card mb-4">
            <div class="card-header pb-0">
              <h4>Top 10 Selling Items</h4>
            </div>
            <div class="card-body px-0 pt-0 pb-2">
              <div class="table-responsive p-0">
                <table class="table align-items-center mb-0">
                  <thead>
                    <tr>
                      <th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">Item</th>
                      <th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7 ps-2">Specification</th>
                      <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">Total sold</th>
                    </tr>
                  </thead>
                  <tbody>

                    <?php
                       $sql1 = "SELECT s.S_description, i.ItemName, i.ItemImage,     SUM(od.D_Quantity) AS total_sold
                               FROM a_orderdetails od
                                 JOIN a_specifications s ON od.D_SpecificationId_FK = s.SpecificationID
                              JOIN a_items i ON s.ItemID_FK = i.ItemID
                              GROUP BY s.S_description, i.ItemName, i.ItemImage
                              ORDER BY total_sold DESC
                              LIMIT 10";
                    $result = mysqli_query($con, $sql1);
                    if(!$result){
                        echo mysqli_error($con);
                    }
                    while ($row = mysqli_fetch_assoc($result)) {
                      $total = $row['total_sold'];
                      $itemName = $row['ItemName'];
                      $itemImage = $row['ItemImage'];
                      $imageURL = "" . $itemImage;
                      $speciName = $row['S_description'];
                    ?>
                      <tr>
                      <td>
                        <div class="d-flex px-2 py-1">
                          <div>
                            <img src="<?php echo $imageURL?>" class="avatar avatar-sm me-3" alt="user1">
                          </div>
                          <div class="d-flex flex-column justify-content-center">
                            <h6 class="mb-0 text-m"><?php echo $itemName?></h6>
                          </div>
                        </div>
                      </td>
                        <td class="">
                        <p class="text-m text-bold mb-0"><?php echo $speciName ?></p>
                        </td>
                        <td class="align-middle text-center text-sm">
                        <p class="text-m text-bold mb-0"><?php echo $total ?></p>
                        </td>
                      </tr>
                    <?php
                    }
                    ?>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>


    </div>
  </main>

  <!--   Core JS Files   -->
  <script src="assets/js/core/popper.min.js"></script>
  <script src="assets/js/core/bootstrap.min.js"></script>
  <script src="assets/js/plugins/perfect-scrollbar.min.js"></script>
  <script src="assets/js/plugins/smooth-scrollbar.min.js"></script>
  <script src="assets/js/plugins/chartjs.min.js"></script>
  <script>
    document.addEventListener("DOMContentLoaded", function () {
    // Get the chart canvas and context
    var chartCanvas = document.getElementById("chart-line");
    var chartContext = chartCanvas.getContext("2d");

    // Create a linear gradient for the chart
    var gradientStroke = chartContext.createLinearGradient(0, 230, 0, 50);
    gradientStroke.addColorStop(1, 'rgba(75, 192, 192, 0.2)');
    gradientStroke.addColorStop(0.2, 'rgba(75, 192, 192, 0.0)');
    gradientStroke.addColorStop(0, 'rgba(75, 192, 192, 0)');

    // Function to update the chart with new data
    function updateChart(chartContext, data) {
        var chart = new Chart(chartContext, {
            type: "line",
            data: {
                datasets: [{
                    label: "Total orders",
                    tension: 0.4,
                    borderWidth: 3,
                    pointRadius: 5,
                    borderColor: "rgba(75, 192, 192, 1)",
                    backgroundColor: gradientStroke,
                    fill: true,
                    data: data,
                    maxBarThickness: 6
                }],
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false,
                    }
                },
                interaction: {
                    intersect: false,
                    mode: 'index',
                },
                scales: {
                    y: {
                        grid: {
                            drawBorder: false,
                            display: true,
                            drawOnChartArea: true,
                            drawTicks: false,
                            borderDash: [5, 5]
                        },
                        ticks: {
                            display: true,
                            padding: 10,
                            color: '#fbfbfb',
                            font: {
                                size: 11,
                                family: "Open Sans",
                                style: 'normal',
                                lineHeight: 2
                            },
                        }
                    },
                    x: {
                        grid: {
                            drawBorder: false,
                            display: false,
                            drawOnChartArea: false,
                            drawTicks: false,
                            borderDash: [5, 5]
                        },
                        ticks: {
                            display: true,
                            color: '#ccc',
                            padding: 20,
                            font: {
                                size: 11,
                                family: "Open Sans",
                                style: 'normal',
                                lineHeight: 2
                            },
                        }
                    },
                },
            },
        });

        // Return the created chart instance, which can be useful if you want to manipulate it later.
        return chart;
    }

    // Add an event listener to the year dropdown
    var yearDropdown = document.getElementById('year');
    yearDropdown.addEventListener('change', function () {
        var selectedYear = yearDropdown.value;

        // Fetch data for the selected year
        fetch('getTotalSales.php?year=' + selectedYear)
            .then(response => response.json())
            .then(data => {
                // Update the chart with the new data
                if (chart) {
                    chart.destroy(); // Destroy the existing chart
                }
                chart = updateChart(chartContext, data);
            })
            .catch(error => console.error('Error:', error));
    });

    // Initialize the chart with the data from the initial fetch
    fetch('functions/getTotalSales.php')
        .then(response => response.json())
        .then(data => {
            var chart = updateChart(chartContext, data);
        })
        .catch(error => console.error('Error:', error));
});

  </script>
  <script>
    var win = navigator.platform.indexOf('Win') > -1;
    if (win && document.querySelector('#sidenav-scrollbar')) {
      var options = {
        damping: '0.5'
      }
      Scrollbar.init(document.querySelector('#sidenav-scrollbar'), options);
    }
  </script>
  <!-- Github buttons -->
  <script async defer src="https://buttons.github.io/buttons.js"></script>
  <!-- Control Center for Soft Dashboard: parallax effects, scripts for the example pages etc -->
  <script src="assets/js/argon-dashboard.min.js?v=2.0.4"></script>

  <script>
    $(document).ready(function() {
      $("#submitbtn").on("click", function(e) {
        e.preventDefault();
        var SliderImage = $("#addSliderImage")[0].files[0];
        var formData = new FormData();
        formData.append("sliderImage", SliderImage);

        $.ajax({
          url: "functions/addSliderImage.php",
          method: "POST",
          data: formData,
          processData: false,
          contentType: false,
          success: function(response) {
            location.reload();
          },
          error: function(xhr, status, error) {
            // Handle errors
            console.error(error);
          }
        });
      });
    });
  </script>

  <script>
    $(document).ready(function() {
      $('.deleteBtnImg').click(function() {
        var sliderID = $(this).data('slider-id');
        $.ajax({
          type: "POST",
          url: "functions/deleteSliderImage.php",
          data: {
            slider_id: sliderID,
          },
          success: function(data) {
            location.reload();
          },
          error: function(xhr, status, error) {
            console.error(xhr);
          }
        })
      })
    })

    $(document).ready(function() {
      $('.EditbtnImg').click(function() {
        var sliderID = $(this).data('slider-id');
        var image = $('#editImage' + sliderID)[0].files[0];
        var formData = new FormData();
        formData.append("slider_id", sliderID);
        formData.append("sliderImage", image);
        $.ajax({
          type: "POST",
          url: "functions/updateSliderImage.php",
          contentType: false,
          processData: false,
          data: formData,
          success: function(data) {
              alert(data);
            location.reload();
          },
          error: function(xhr, status, error) {
            console.error(xhr);
          }
        });
      });
    });
  </script>

</body>

</html>