<?php
$page_title = 'All Group';
require_once('includes/load.php');
require 'vendor/autoload.php'; // Autoload PHPSpreadsheet

// Checkin What level user has permission to view this page
// page_require_level(1);
$startDate = isset($_GET['startDate']) ? $_GET['startDate'] : '';
$endDate = isset($_GET['endDate']) ? $_GET['endDate'] : '';
$shopId = isset($_GET['shop']) ? $_GET['shop'] : '';

// Base SQL query
$sql = "SELECT 
    s.kode AS `shop_name`,
    p.platform_name AS `platform_name`,
    COUNT(DISTINCT o.id) AS `total_invoice`,
    SUM(CASE WHEN od.model_discounted_price = 0 THEN od.model_original_price ELSE od.model_discounted_price END) AS `total_quantity`,
    SUM(CASE WHEN od.model_discounted_price = 0 THEN od.model_original_price ELSE od.model_discounted_price END * od.model_quantity_purchased) AS `total_price`
FROM 
    shop s
JOIN 
    platform p on s.platform_id = p.id 
LEFT JOIN 
    orders o ON s.shop_id = o.shop_id
LEFT JOIN 
    order_detail od ON o.id = od.order_id where 1=1"; // Start with a true condition for easier appending

// Append conditions based on form inputs
if (!empty($startDate)) {
  $sql .= " AND o.create_time >= '" . addslashes($startDate) . "'";
}

if (!empty($endDate)) {
  $sql .= " AND o.create_time <= '" . addslashes($endDate) . "'";
}

if (!empty($shopId) && $shopId != 'all') {
  $sql .= " AND o.shop_id = " . intval($shopId);
}

$sql .= " GROUP BY s.kode, p.platform_name;";

// Execute the query
$all_orders = $db->query($sql);

?>

<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.dataTables.min.css">

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

<?php include_once('layouts/header.php'); ?>

<div class="row">
  <div class="col-md-12">
    <?php echo display_msg($msg); ?>
  </div>
</div>
<div class="row">
  <div class="col-md-12">
    <div class="panel panel-default">
      <div class="panel-heading clearfix">
        <strong>
          <span class="glyphicon glyphicon-th"></span>
          <span>List Sales Report</span>
        </strong>
      </div>
      <div class="panel-body">
        <div id="filter" style="margin-bottom: 10px;">
          <form method="get" action="" class="mb-4">
            <div class="form-row">
              <div class="range-date">
                <div class="form-group col-md-4">
                  <label for="startDate">Start DateTime</label>
                  <input type="text" name="startDate" class="form-control" id="startDate" placeholder="Start DateTime"
                    value="<?= isset($_GET['startDate']) ? htmlspecialchars($_GET['startDate']) : '' ?>">
                </div>
                <div class="form-group col-md-4">
                  <label for="endDate">End DateTime</label>
                  <input type="text" name="endDate" class="form-control" id="endDate" placeholder="End DateTime"
                    value="<?= isset($_GET['endDate']) ? htmlspecialchars($_GET['endDate']) : '' ?>">
                </div>
              </div>
              <div class="form-group col-md-4">
                <label for="store">Shop</label>
                <?php
                // Ambil nilai dari GET
                $selectedShop = isset($_GET['shop']) ? htmlspecialchars($_GET['shop']) : '';

                // Query untuk mendapatkan daftar toko
                $sql = "SELECT shop_id, kode FROM shop";
                $result = $db->query($sql);

                // Mulai elemen select
                echo '<select id="shop" name="shop" class="form-control">';
                echo '<option value="">Choose...</option>';
                echo '<option value="all"' . ($selectedShop === 'all' ? ' selected' : '') . '>All</option>';

                // Cek jika ada hasil query
                if ($result->num_rows > 0) {
                  while ($row = $result->fetch_assoc()) {
                    $isSelected = ($row['shop_id'] == $selectedShop) ? ' selected' : '';
                    echo '<option value="' . $row['shop_id'] . '"' . $isSelected . '>' . htmlspecialchars($row['kode']) . '</option>';
                  }
                } else {
                  echo '<option value="">No shops available</option>';
                }

                // Tutup elemen select
                echo '</select>';
                ?>
              </div>
            </div>
            <div class="col-md-12">
              <button type="submit" class="btn btn-primary" style="margin-bottom: 15px;">Filter</button>
              <button type="button" class="btn btn-secondary" style="margin-bottom: 15px;"
                onclick="window.location.href = window.location.pathname;">Refresh</button>
            </div>
          </form>
        </div>
        <button id="exportExcel" class="btn btn-success mb-3 ml-3">Export to Excel</button>

        <table id="orderTable" class="table table-bordered">
          <thead>
            <tr>
              <th class="text-center" style="width: 50px;">#</th>
              <th>Store Name</th>
              <th>Platform</th>
              <th>Total Invoice</th>
              <th>Total Quantity</th>
              <th>Total</th>
              <th>Aksi</th>
            </tr>
          </thead>
          <tbody>
            <?php
            $no = 1;
            $total_invoice = 0;
            $total_quantity = 0;
            $total_price = 0;
            $total_disc = 0;

            foreach ($all_orders as $item):
              $total_invoice += $item['total_invoice'];
              $total_quantity += $item['total_quantity'];
              $total_price += $item['total_price'];
            ?>
            <tr>
              <td class="text-center"><?php echo $no++; ?></td>
              <td><?php echo $item['shop_name'] ?? 'unknow'; ?></td>
              <td><?php echo $item['platform_name'] ?? 'unknow'; ?></td>
              <td><?php echo $item['total_invoice'] ?? 0; ?></td>
              <td><?php echo $item['total_quantity'] ?? 0; ?></td>
              <td><?php echo formatCurrency($item['total_price'] ?? 0); ?></td>
              <td>
                <a href="report_sales_detail.php?shop_id=<?php echo $item['shop_name']; ?>&platform=<?php echo $item['platform_name']; ?>&startDate=<?php echo $startDate; ?>&endDate=<?php echo $endDate; ?>"
                  class="btn btn-info btn-sm">Details</a>

              </td>
            </tr>
            <?php endforeach; ?>
          </tbody>
          <tfoot>
            <tr>
              <th colspan="3" class="text-center">Total</th>
              <th><?php echo $total_invoice; ?></th>
              <th><?php echo $total_quantity; ?></th>
              <th><?php echo formatCurrency($total_price); ?></th>
              <th></th>
            </tr>
          </tfoot>
        </table>
      </div>
    </div>
  </div>
</div>

<script>
$.noConflict();
jQuery(document).ready(function($) {
  // Initialize DataTable with options to disable sorting on the filter row
  var table = $('#orderTable').DataTable({
    paging: true,
    pageLength: 1000,
    lengthMenu: [
      [10, 100, 1000, -1],
      [10, 100, 1000, "All"]
    ],
    searching: true,
    info: true,
    buttons: ['excelHtml5'] // Jangan tambahkan tombol di sini jika ingin kontrol manual
  });
  new $.fn.dataTable.Buttons(table, {
    buttons: [{
      extend: 'excelHtml5',
      text: 'Export to Excel',
      title: 'Order Data', // Nama file Excel
      exportOptions: {
        columns: ':visible' // Ekspor hanya kolom yang terlihat
      }
    }]
  });

  // Pasang tombol ke elemen khusus
  $('#exportExcel').on('click', function() {
    console.log('exportExcel');
    table.buttons(0, 0).trigger(); // Trigger tombol ekspor Excel (indeks tombol harus tepat)

  });
});
</script>
<script>
// Initialize Flatpickr for date and time selection
flatpickr("#startDate", {
  enableTime: true,
  dateFormat: "Y-m-d H:i",
  onChange: function(selectedDates, dateStr, instance) {
    // Set the end date to be at least the start date
    if (selectedDates.length > 0) {
      const endDateInput = document.getElementById("endDate");
      endDateInput._flatpickr.set('minDate', dateStr);
    }
  }
});

flatpickr("#endDate", {
  enableTime: true,
  dateFormat: "Y-m-d H:i",
});
</script>
<?php include_once('layouts/footer.php'); ?>