<?php
include 'includes/config.php';
session_start();

if (!$_SESSION['email']) {
  header('location:login.php');
}
?><!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>View Item Report</title>
    <!-- Favicon -->
    <link rel="shortcut icon" href="images/favicon.ico" />
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <!-- Typography CSS -->
    <link rel="stylesheet" href="css/typography.css">
    <!-- Style CSS -->
    <link rel="stylesheet" href="css/style.css">
    <!-- Responsive CSS -->
    <link rel="stylesheet" href="css/responsive.css">
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

    <style>
    ion-icon {
        font-size: 20px;
        margin-bottom: -5px;
    }
    </style>
</head>

<body>
    <!-- loader Start -->

    <!-- loader END -->
    <!-- Wrapper Start -->
    <div class="wrapper">
        <!-- Sidebar  -->
        <?php 
            include 'includes/sidebar.php';
        ?>
        <!-- TOP Nav Bar -->
        <?php include 'includes/header.php';?>
        <!-- TOP Nav Bar END -->
        <!-- Page Content  -->
        <div id="content-page" class="content-page">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-sm-12">
                        <div class="iq-card">
                            <div class="iq-card-header d-flex justify-content-between row">
                                <div class="iq-header-title col-lg-6">
                                    <h4 class="card-title">Items Report
                                    </h4>
                                </div>
                            </div>
                            <!-- search bar -->
                           
                            <!-- searchbar end -->
                            <!-- buttons for export -->
                            <div class="row mt-5">
                                <!-- <div class="col-lg-2"></div>
                                <div class="col-lg-8">
                                    <button class="btn btn-primary">
                                        <ion-icon name="document-outline"></ion-icon>Export to CSV
                                    </button>
                                    <button class="btn btn-info">
                                        <ion-icon name="document-outline"></ion-icon>Export to Excel
                                    </button>
                                    <button class="btn btn-warning">
                                        <ion-icon name="print-outline"></ion-icon>Print
                                    </button>
                                    <button class="btn btn-danger">
                                        <ion-icon name="stop-outline"></ion-icon>Column Visibility
                                    </button>
                                    <button class="btn btn-dark">
                                        <ion-icon name="document-outline"></ion-icon>Export to PDF
                                    </button>
                                </div>
                            </div> -->
                            <!-- buttons for export end -->
                            <!-- Table to Display the Data -->
                <div class="container mt-4">   
  <h3 class="mb-3">Sale Item Report</h3>

  <!-- Filter Section -->
  <div class="row mb-3">
    <div class="col-lg-3">
      <label>From Date</label>
      <input type="date" id="start_date_sale" class="form-control">
    </div>
    <div class="col-lg-3">
      <label>To Date</label>
      <input type="date" id="end_date_sale" class="form-control" value="<?php echo date('Y-m-d'); ?>">
    </div>
    <div class="col-lg-3">
      <label>Search Product</label>
      <input type="search" id="search_sale" class="form-control" placeholder="Search product...">
    </div>
    <div class="col-lg-3">
      <label>Select Salesman</label>
      <select id="user_id" class="form-control">
        <option value="all" selected>All Salesmen</option>
        <?php
          include 'includes/config.php';
          $stmtUsers = $conn->query("SELECT id, user_name FROM users ORDER BY user_name");
          while($u = $stmtUsers->fetch(PDO::FETCH_ASSOC)){
              echo "<option value='{$u['id']}'>{$u['user_name']}</option>";
          }
        ?>
      </select>
    </div>
  </div>

  <div class="row mb-3">
    <div class="col-lg-12 text-end">
      <button id="filterBtnSale" class="btn btn-primary">Filter</button>
      <a href="item_report.php" class="btn btn-secondary">Clear Filter</a>
      <button id="printBtnSale" class="btn btn-success">Print</button>
    </div>
  </div>

  <!-- Summary Section -->
  <div id="summarySale" class="row g-3 mb-4">
    <div class="col-md-4">
      <div class="card text-white bg-primary h-100">
        <div class="card-body">
          <h6 class="card-title">Total Quantity</h6>
          <h3 id="totalQtyTop">0</h3>
        </div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="card text-white bg-success h-100">
        <div class="card-body">
          <h6 class="card-title">Total Amount</h6>
          <h3 id="totalAmountTop">0 ₨</h3>
        </div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="card text-white bg-info h-100">
        <div class="card-body">
          <h6 class="card-title">Top Selling Items</h6>
          <ul id="topSaleListTop" class="mb-0"></ul>
        </div>
      </div>
    </div>
  </div>

  <!-- Table Section -->
  <div style="overflow:auto;">
    <table class="table table-bordered" id="saleTable">
      <thead class="thead-light">
        <tr>
          <th>Product</th>
          <th>Invoice</th>
          <th>Date</th>
          <th>Customer</th>
          <th>Salesman</th>
          <th>Qty</th>
          <th>Price</th>
          <th>Subtotal</th>
        </tr>
      </thead>
      <tbody></tbody>
      <tfoot class="table-light font-weight-bold">
        <tr>
          <td colspan="5" class="text-end">Total:</td>
          <td id="totalQty" class="text-end"></td>
          <td></td>
          <td id="totalAmount" class="text-end"></td>
        </tr>
      </tfoot>
    </table>
  </div>

  <nav><ul id="paginationSale" class="pagination justify-content-center"></ul></nav>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function(){
  let page = 1;

  function formatCurrency(val){
    return `${Number(val || 0).toLocaleString('en-IN', { minimumFractionDigits: 2 })} ₨`;
  }

  function renderPagination(current, total) {
    const pagination = $('#paginationSale');
    pagination.empty();
    const delta = 2;
    let pages = [];
    for (let i = 1; i <= total; i++) {
      if (i === 1 || i === total || (i >= current - delta && i <= current + delta)) pages.push(i);
      else if (pages[pages.length-1] !== '...') pages.push('...');
    }
    pages.forEach(p => {
      if (p === '...') pagination.append(`<li class="page-item disabled"><span class="page-link">...</span></li>`);
      else pagination.append(`<li class="page-item ${p===current?'active':''}"><a href="#" class="page-link">${p}</a></li>`);
    });
  }

  function loadSales(){
    const search = $('#search_sale').val();
    const start = $('#start_date_sale').val();
    const end = $('#end_date_sale').val();
    const user_id = $('#user_id').val();

    $.ajax({
      url: 'fetch_item_report.php',
      type: 'GET',
      data: {page, search, start_date: start, end_date: end, user_id},
      dataType: 'json',
      success: function(res){
        const {data = [], top_items = [], total_pages = 1, overall_totals = {}} = res;
        const tbody = $('#saleTable tbody'); tbody.empty();
        let totalQty = 0, totalAmount = 0;

        if(data.length===0){
          tbody.html('<tr><td colspan="8" class="text-center text-danger">No sales found</td></tr>');
        } else {
          data.forEach(i=>{
            const qty = parseFloat(i.sale_qty||0);
            const price = parseFloat(i.price||0);
            const discount = parseFloat(i.discount||0);
            const subtotal = qty*price - discount;
            totalQty += qty; totalAmount += subtotal;
            tbody.append(`
              <tr>
                <td>${i.product_name}</td>
                <td>${parseInt(i.invoice)}</td>
                <td>${i.date_sale?i.date_sale.split(' ')[0]:'-'}</td>
                <td>${i.customer_name||'-'}</td>
                <td>${i.user_name||'-'}</td>
                <td class="text-end">${qty.toFixed(2)}</td>
                <td class="text-end">${formatCurrency(price)}</td>
                <td class="text-end">${formatCurrency(subtotal)}</td>
              </tr>
            `);
          });
        }

        $('#totalQty').text(totalQty.toFixed(2));
        $('#totalAmount').text(formatCurrency(totalAmount));
        $('#totalQtyTop').text(overall_totals.total_qty||0);
        $('#totalAmountTop').text(formatCurrency(overall_totals.total_amount||0));

        const topList = $('#topSaleListTop'); topList.empty();
        top_items.forEach(t=>topList.append(`<li>${t.product_name} — ${t.total_qty} sold</li>`));

        renderPagination(page,total_pages);
      }
    });
  }

  $('#paginationSale').on('click','a',function(e){e.preventDefault(); const p=parseInt($(this).text()); if(!isNaN(p)){page=p;loadSales();}});
  $('#filterBtnSale, #search_sale, #user_id, #start_date_sale, #end_date_sale').on('click change input',function(){page=1;loadSales();});
  loadSales();
});

$('#printBtnSale').on('click', function () {
  const reportContent = `
    <div class="container mt-4">
      <h3 class="mb-3 text-center">Sale Item Report</h3>
      ${document.querySelector('#summarySale').outerHTML}
      ${document.querySelector('#saleTable').outerHTML}
    </div>
  `;
  const win = window.open('', '', 'width=1000,height=800');
  win.document.write(`<html><head><title>Sale Item Report</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <style>table{width:100%;border-collapse:collapse;}th,td{border:1px solid #ddd;padding:8px;text-align:right;}th{text-align:center;}</style>
    </head><body>${reportContent}</body></html>`);
  win.document.close(); win.print(); win.close();
});
</script>

                    </div>
                </div>
            </div>

        </div>
    </div>
    </div>
    <!-- Wrapper END -->
    <!-- Footer -->
    <footer class="iq-footer">
        <div class="container-fluid">
            <div class="row">
                <div class="col-lg-6">
                    <ul class="list-inline mb-0">
                        <li class="list-inline-item"><a href="privacy-policy.html">Privacy Policy</a></li>
                        <li class="list-inline-item"><a href="terms-of-service.html">Terms of Use</a></li>
                    </ul>
                </div>
                <div class="col-lg-6 text-right">
                    Copyright <span id="copyright">
                        <script>
                        document.getElementById('copyright').appendChild(document.createTextNode(new Date()
                            .getFullYear()))
                        </script>
                    </span> <a href="#">Vito</a> All Rights Reserved.
                </div>
            </div>
        </div>
    </footer>
    <nav class="iq-float-menu">
        <input type="checkbox" href="#" class="iq-float-menu-open" name="menu-open" id="menu-open" />
        <label class="iq-float-menu-open-button" for="menu-open">
            <span class="lines line-1"></span>
            <span class="lines line-2"></span>
            <span class="lines line-3"></span>
        </label>
        <button class="iq-float-menu-item bg-info" data-toggle="tooltip" data-placement="top" title="Direction Mode"
            data-mode="rtl"><i class="ri-text-direction-r"></i></button>
        <button class="iq-float-menu-item bg-danger" data-toggle="tooltip" data-placement="top" title="Color Mode"
            id="dark-mode" data-active="true"><i class="ri-sun-line"></i></button>
        <button class="iq-float-menu-item bg-warning" data-toggle="tooltip" data-placement="top" title="Comming Soon"><i
                class="ri-palette-line"></i></button>
    </nav>
    <!-- Footer END -->
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="js/jquery.min.js"></script>
    <!-- Rtl and Darkmode -->
    <script src="js/rtl.js"></script>
    <script src="js/customizer.js"></script>
    <script src="js/popper.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <!-- Appear JavaScript -->
    <script src="js/jquery.appear.js"></script>
    <!-- Countdown JavaScript -->
    <script src="js/countdown.min.js"></script>
    <!-- Counterup JavaScript -->
    <script src="js/waypoints.min.js"></script>
    <script src="js/jquery.counterup.min.js"></script>
    <!-- Wow JavaScript -->
    <script src="js/wow.min.js"></script>
    <!-- Apexcharts JavaScript -->
    <script src="js/apexcharts.js"></script>
    <!-- Slick JavaScript -->
    <script src="js/slick.min.js"></script>
    <!-- Select2 JavaScript -->
    <script src="js/select2.min.js"></script>
    <!-- Owl Carousel JavaScript -->
    <script src="js/owl.carousel.min.js"></script>
    <!-- Magnific Popup JavaScript -->
    <script src="js/jquery.magnific-popup.min.js"></script>
    <!-- Smooth Scrollbar JavaScript -->
    <script src="js/smooth-scrollbar.js"></script>
    <!-- lottie JavaScript -->
    <script src="js/lottie.js"></script>
    <!-- Chart Custom JavaScript -->
    <script src="js/chart-custom.js"></script>
    <!-- Custom JavaScript -->
    <script src="js/custom.js"></script>
</body>

<!-- Mirrored from templates.iqonic.design/vito/html/main/data-table.html by HTTrack Website Copier/3.x [XR&CO'2014], Wed, 21 Aug 2024 10:45:18 GMT -->

</html>