<?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>Product Sell 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">
    <style>
    ion-icon {
        font-size: 20px;
        margin-bottom: -5px;
    }
    </style>
</head>

<body>
    <!-- loader Start -->
    <div id="loading">
        <div id="loading-center">
        </div>
    </div>
    <!-- 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">Product Sell Report</h4>
                            </div>
                        </div>


<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

<style>
  body {
    background-color: #f4f6f9;
  }

  .filter-card {
    background: white;
    padding: 25px 30px;
    border-radius: 14px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.08);
    margin-top: 20px;
  }

  .filter-header {
    text-align: center;
    font-size: 18px;
    font-weight: 700;
    color: #007bff;
    margin-bottom: 20px;
  }

  .form-label {
    font-weight: 600;
    font-size: 14px;
  }

  .btn {
    border-radius: 8px;
  }

  #productTable th, #productTable td {
    font-size: 13px;
    vertical-align: middle;
  }

  .summary-box {
    background: #ffffff;
    border-radius: 10px;
    box-shadow: 0 3px 6px rgba(0,0,0,0.08);
    padding: 15px;
    margin-bottom: 20px;
  }

  .summary-item {
    text-align: center;
  }

  .summary-item h5 {
    font-size: 16px;
    color: #007bff;
    margin-bottom: 5px;
  }

  .summary-item span {
    font-size: 18px;
    font-weight: 700;
    color: #333;
  }

  @media print {
    .filter-card, #printButton { display: none !important; }
    table { width: 100%; border-collapse: collapse; }
    th, td { border: 1px solid black !important; padding: 6px; }
    th { background: #f2f2f2; }
  }
</style>

<div class="container-fluid mt-4">
  <div class="filter-card">
    <div class="filter-header">🧾 <b>Sales Report Filter</b></div>
    <form id="filterForm" class="row align-items-end g-3">
      <div class="col-md-3">
        <label for="startDate" class="form-label">From Date:</label>
        <input type="date" id="startDate" class="form-control">
      </div>

      <div class="col-md-3">
        <label for="endDate" class="form-label">To Date:</label>
        <input type="date" id="endDate" class="form-control">
      </div>

      <div class="col-md-3">
        <label for="userSelect" class="form-label">Select User:</label>
        <select id="userSelect" class="form-control" multiple>
          <option value="all" selected>All Users</option>
          <?php
            include 'includes/config.php';
            $stmtUsers = $conn->prepare("SELECT `id`, `user_name` FROM `users`");
            $stmtUsers->execute();
            foreach ($stmtUsers->fetchAll(PDO::FETCH_ASSOC) as $user) {
              echo "<option value='{$user['id']}'>{$user['user_name']}</option>";
            }
          ?>
        </select>
      </div>

      <div class="col-md-3">
        <label for="brandSelect" class="form-label">Select Brand:</label>
        <select id="brandSelect" class="form-control" multiple>
          <option value="all" selected>All Brands</option>
          <?php
            $stmtBrands = $conn->prepare("SELECT `id`, `name` FROM `brands` ORDER BY name ASC");
            $stmtBrands->execute();
            foreach ($stmtBrands->fetchAll(PDO::FETCH_ASSOC) as $brand) {
              echo "<option value='{$brand['id']}'>{$brand['name']}</option>";
            }
          ?>
        </select>
      </div>

      <div class="col-md-3 d-flex mt-3">
        <button type="button" id="filterButton" class="btn btn-primary w-50 me-2">🔍 Filter</button>
        <a href="product_sell_report.php" class="btn btn-secondary w-50">❌ Clear</a>
      </div>
    </form>
  </div>

  <div id="filterSummary" class="alert alert-info mt-3" style="display:none;">
    <b>Filters Applied:</b> 
    <span id="filterText"></span>
  </div>

  <div class="summary-box row text-center">
    <div class="col-md-6 summary-item">
      <h5>Total Quantity</h5>
      <span id="summaryQuantity">0</span>
    </div>
    <div class="col-md-6 summary-item">
      <h5>Total Price</h5>
      <span id="summaryPrice">0 ₨</span>
    </div>
  </div>

  <div class="iq-card-body mt-3" style="overflow:auto;">
    <button id="printButton" class="btn btn-success mb-3">🖨️ Print Report</button>
    <table class="table table-bordered table-hover" id="productTable">
      <thead class="table-light">
        <tr>
          <th>Brand</th>
          <th>Product</th>
          <th>Total Qty</th>
          <th>Unit Price</th>
          <th>Total Amount</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>

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

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
$(document).ready(function() {
  $('#userSelect, #brandSelect').select2({ placeholder: "Select Options", allowClear: true });

  // Default dates to today
  let today = new Date().toISOString().split('T')[0];
  $('#startDate').val(today);
  $('#endDate').val(today);

  let currentPage = 1;
  const pageSize = 20; 

  function renderPagination(currentPage, totalPages) {
      const pagination = $('#pagination');
      pagination.empty();

      const createPageItem = (page, text = null, active = false, disabled = false) => {
          return `<li class="page-item ${active ? 'active' : ''} ${disabled ? 'disabled' : ''}">
                      <a class="page-link" href="#" data-page="${page}">${text ?? page}</a>
                  </li>`;
      };

      if(currentPage > 3) pagination.append(createPageItem(1));
      if(currentPage > 4) pagination.append('<li class="page-item disabled"><span class="page-link">...</span></li>');

      const start = Math.max(2, currentPage - 2);
      const end = Math.min(totalPages - 1, currentPage + 2);
      for(let i = start; i <= end; i++) {
          pagination.append(createPageItem(i, null, i === currentPage));
      }

      if(currentPage < totalPages - 3) pagination.append('<li class="page-item disabled"><span class="page-link">...</span></li>');
      if(totalPages > 1) pagination.append(createPageItem(totalPages));

      $('.page-link').click(function(e) {
          e.preventDefault();
          const pageNum = parseInt($(this).data('page'));
          if(!isNaN(pageNum) && pageNum !== currentPage) fetchReport(pageNum);
      });
  }

  function fetchReport(page = 1) {
    currentPage = page;
    const users = $('#userSelect').val();
    const brands = $('#brandSelect').val();
    const startDate = $('#startDate').val();
    const endDate = $('#endDate').val();

    let data = { user_ids: users, brand_ids: brands, page: page, page_size: pageSize };
    if (startDate && endDate) {
      data.start_date = startDate;
      data.end_date = endDate;
    }

    let filterText = `<b>Users:</b> ${users.includes('all') ? 'All Users' : $('#userSelect option:selected').map(function(){return $(this).text();}).get().join(', ')} `;
    filterText += `| <b>Brands:</b> ${brands.includes('all') ? 'All Brands' : $('#brandSelect option:selected').map(function(){return $(this).text();}).get().join(', ')} `;
    if (startDate && endDate) {
      filterText += ` | <b>Date Range:</b> ${startDate} → ${endDate}`;
    }
    $('#filterText').html(filterText);
    $('#filterSummary').show();

    $.ajax({
      url: 'fetch_sale_report.php',
      method: 'GET',
      data: data,
      dataType: 'json',
      success: function(response) {
        const tbody = $('#productTable tbody');
        tbody.empty();

        if(response.error) {
            tbody.html(`<tr><td colspan="5" class="text-center text-danger">${response.error}</td></tr>`);
            $('#summaryQuantity').text(0);
            $('#summaryPrice').text('0 ₨');
            $('#pagination').empty();
            return;
        }

        response.data.forEach(row => {
            tbody.append(`
                <tr>
                    <td>${row.brand_name ?? ''}</td>
                    <td>${row.product_name}</td>
                    <td>${row.total_qty}</td>
                    <td>${parseFloat(row.unit_price).toLocaleString('en-IN', { minimumFractionDigits: 2 })} ₨</td>
                    <td>${parseFloat(row.total_amount).toLocaleString('en-IN', { minimumFractionDigits: 2 })} ₨</td>
                </tr>
            `);
        });

        $('#summaryQuantity').text(response.summary_quantity ?? 0);
        $('#summaryPrice').text((response.summary_price ?? 0).toLocaleString('en-IN', { minimumFractionDigits: 2 }) + ' ₨');

        const totalPages = Math.ceil(response.total / pageSize);
        renderPagination(currentPage, totalPages);
      },
      error: function() { alert('Error fetching data.'); }
    });
  }

  fetchReport();
  $('#filterButton').on('click', function(){ fetchReport(1); });

  $('#printButton').on('click', function() {
    const printContent = `<div style="text-align:center;"><h3>Sales Report</h3><p>${$('#filterText').html()}</p></div>${$('#productTable')[0].outerHTML}`;
    const win = window.open('', '', 'width=900,height=700');
    win.document.write(`<html><head><title>Sales Report</title>
      <style>table{width:100%;border-collapse:collapse}th,td{border:1px solid black;padding:6px;font-size:12px}th{background:#f2f2f2}</style></head><body>${printContent}</body></html>`);
    win.document.close();
    win.print();
  });
});
</script>



    <!-- 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>

</html>