<?php
session_set_cookie_params([
  'lifetime' => 0,
  'path' => '/',
  'domain' => '.' . $_SERVER['HTTP_HOST'],
  'secure' => true,
  'httponly' => true,
  'samesite' => 'None'
]);
session_start();
include './header.php';
require_once './src/AccessToken.php';
/*require_once './src/Database.php';
require_once './src/user.php';
require_once './src/team.php';*/
require_once './src/InternalTicket.php';


$bitrix24UserId = isset($_SESSION['bitrix_user_id']) && !empty($_SESSION['bitrix_user_id']) ? $_SESSION['bitrix_user_id'] : null;
$userInfo = InternalTicket::getCurrentUser($bitrix24UserId);
$userId = $userInfo['ID'];
$internalTicket = InternalTicket::getInternalTicket($bitrix24UserId, $userId);
$departments = InternalTicket::getDistinctFieldValues('project_type', $bitrix24UserId, $userId);
$priorities = InternalTicket::getDistinctFieldValues('priority', $bitrix24UserId, $userId);
$statuses = InternalTicket::getDistinctFieldValues('status', $bitrix24UserId, $userId);


?>
<div class="container-fluid main-content">

  <div class="d-flex justify-content-between align-items-center p-2 mb-3 rounded hedding-content">
    <!-- Left side (Breadcrumb) -->
    <div>
      <a href="#">My Ticket</a>
      <span class="mx-2">/</span>
      <strong>My All Ticket List</strong>
    </div>

    <!-- Right side (Button) -->
    <a href="./intrnal-ticket-create.php" class="btn btn-success user-button">
      <i class="fa fa-plus"></i> New Ticket
    </a>
  </div>

  <div class="styled-table">
  <table id="ticketsTable" class="table table-striped">
    <thead>
      <tr>
        <th>Ticket id
          <i class="bi bi-funnel filter-icon"></i>
          <div class="filter-dropdown">
            <input type="search" placeholder="Search Ticket ID" class="column-search" data-column="0">
            <button class="clear-filter btn btn-sm btn-light" data-column="0">Clear</button>
          </div>
        </th>
        <th>Department
          <i class="bi bi-funnel filter-icon"></i>
          <div class="filter-dropdown">
            <input type="search" placeholder="Search Department" class="column-search" data-column="1">
            <button class="clear-filter btn btn-sm btn-light" data-column="1">Clear</button>
          </div>
        </th>
        <th>Priority
          <i class="bi bi-funnel filter-icon"></i>
          <div class="filter-dropdown">
            <input type="search" placeholder="Search Priority" class="column-search" data-column="2">
            <button class="clear-filter btn btn-sm btn-light" data-column="2">Clear</button>
          </div>
        </th>
        <th>Subject
          <i class="bi bi-funnel filter-icon"></i>
          <div class="filter-dropdown">
            <input type="search" placeholder="Search Subject" class="column-search" data-column="3">
            <button class="clear-filter btn btn-sm btn-light" data-column="3">Clear</button>
          </div>
        </th>
        <th>Status
          <i class="bi bi-funnel filter-icon"></i>
          <div class="filter-dropdown">
            <input type="search" placeholder="Search Status" class="column-search" data-column="4">
            <button class="clear-filter btn btn-sm btn-light" data-column="4">Clear</button>
          </div>
        </th>
        <th>Date Created
          <i class="bi bi-funnel filter-icon"></i>
          <div class="filter-dropdown">
            <input type="search" placeholder="Search Date" class="column-search" data-column="5">
            <button class="clear-filter btn btn-sm btn-light" data-column="5">Clear</button>
          </div>
        </th>
        <th>View</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($internalTicket as $ticket): ?>
        <tr>
          <td><?= $ticket['id'] ?></td>
          <td><?= $ticket['project_type'] ?></td>
          <td><?= $ticket['priority'] ?></td>
          <td><?= $ticket['ticket_subject'] ?></td>
          <td><?= $ticket['status'] ?></td>
          <td><?= $ticket['created_at'] ?></td>
          <td><button class="btn btn-info btn-sm">View</button></td>
        </tr>
      <?php endforeach ?>
    </tbody>
  </table>
  </div>
</div>

  <?php include('footer.php'); ?>
 
<script>
$(document).ready(function () {
  const table = $('#ticketsTable').DataTable();
  const columnsToFilter = [0, 1, 2, 3, 4, 5];
  const openDropdowns = new Set();

  function escapeRegex(string) {
    return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  }

  function setupFilters() {
    columnsToFilter.forEach(function (colIdx) {
      const th = $('#ticketsTable thead th').eq(colIdx);
      const icon = th.find('.filter-icon');
      const dropdown = th.find('.filter-dropdown');

      icon.on('click', function (e) {
        e.stopPropagation();
        $('.filter-dropdown').hide();
        if (openDropdowns.has(colIdx)) {
          dropdown.hide();
          openDropdowns.delete(colIdx);
        } else {
          populateDropdown(colIdx, dropdown);
          dropdown.show();
          openDropdowns.clear();
          openDropdowns.add(colIdx);
        }
      });

      dropdown.on('click', function (e) {
        e.stopPropagation();
      });
    });

    $(document).on('click', function () {
      $('.filter-dropdown').hide();
      openDropdowns.clear();
    });
  }

  function populateDropdown(colIdx, dropdown) {
    dropdown.html('');
    const uniqueValues = new Set();

    table.column(colIdx).data().each(function (val) {
      val = $('<div>').html(val).text().trim();
      if (val) uniqueValues.add(val);
    });

    const sorted = Array.from(uniqueValues).sort();

    dropdown.append(`<input type="text" class="search-box form-control form-control-sm my-1" placeholder="Search in values...">`);
    dropdown.append(`<label><input type="checkbox" class="filter-opt-all" data-col="${colIdx}" checked> <strong>Select All</strong></label>`);

    sorted.forEach(val => {
      dropdown.append(`<label><input type="checkbox" class="filter-opt" data-col="${colIdx}" value="${val}" checked> ${val}</label>`);
    });

    dropdown.append(`<button class="btn btn-sm btn-primary apply-filter mt-1" data-col="${colIdx}">Apply</button>`);
    dropdown.append(`<button class="btn btn-sm btn-secondary clear-filter mt-1" data-col="${colIdx}">Clear</button>`);

    dropdown.find('.search-box').on('keyup', function () {
      const val = $(this).val().toLowerCase();
      const matchingCheckboxes = [];

      dropdown.find('label').not(':first').each(function () {
        const labelText = $(this).text().toLowerCase();
        const match = labelText.includes(val);
        $(this).toggle(match);
        if (match) {
          const checkbox = $(this).find('input[type="checkbox"].filter-opt');
          if (checkbox.length) matchingCheckboxes.push(checkbox.val());
        }
      });

      // Table filter on live search
      if (matchingCheckboxes.length) {
        const regex = '^(' + matchingCheckboxes.map(escapeRegex).join('|') + ')$';
        table.column(colIdx).search(regex, true, false).draw();
      } else {
        table.column(colIdx).search('^$', true, false).draw(); // no match
      }
    });

    dropdown.find('.filter-opt-all').on('change', function () {
      const isChecked = $(this).is(':checked');
      dropdown.find('.filter-opt').prop('checked', isChecked);
    });

    dropdown.find('.clear-filter').on('click', function () {
      dropdown.find('.filter-opt').prop('checked', true);
      table.column(colIdx).search('').draw();
    });

    dropdown.find('.apply-filter').on('click', function () {
      const checked = dropdown.find('.filter-opt:checked').map(function () {
        return escapeRegex($(this).val());
      }).get();
      if (checked.length) {
        const regex = '^(' + checked.join('|') + ')$';
        table.column(colIdx).search(regex, true, false).draw();
      } else {
        table.column(colIdx).search('^$', true, false).draw();
      }
    });
  }

  setupFilters();
});
</script>


