 <?php
error_reporting(E_ALL);
ini_set('display_errors', 0); // ✅ Show errors in browser
ini_set('log_errors', 1);
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/Database.php';
$bitrix24UserId = $_SESSION['bitrix_user_id'] ?? null;

require_once './src/ticket.php';
$ticket = new Ticket();
$allTickets = $ticket::findAll($bitrix24UserId);


/*if (isset($_GET['del'])) {
  $id = $_GET['del'];
  try {
    $ticket->delete($id);
     echo "Ticket deleted successfully";
    $_SESSION['success'] = "Ticket deleted successfully!";
    //header("Location: ./dashboard.php");
    exit;
  } catch (Exception $e) {
    $_SESSION['error'] = "Error deleting ticket: " . $e->getMessage();
    header("Location: ./dashboard.php");
    exit;
  }
}*/

?>

<!-- Flatpickr CSS -->


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

  <div class="d-flex justify-content-between align-items-center p-2 mb-3 rounded hedding-content">
   
    <div>
      <a href="#">Dashboard</a>
      <span class="mx-2">/</span>
      <strong>All Ticket List</strong>
    </div>
  </div>
 
 <?php if (isset($_SESSION['success'])): ?>
  <div class="alert alert-success alert-dismissible fade show" role="alert">
    <?= htmlspecialchars($_SESSION['success']); ?>
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <?php unset($_SESSION['success']); ?>
<?php endif; ?>

<?php if (isset($_SESSION['error'])): ?>
  <div class="alert alert-danger alert-dismissible fade show" role="alert">
    <?= htmlspecialchars($_SESSION['error']); ?>
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <?php unset($_SESSION['error']); ?>
<?php endif; ?>


      <div class="styled-table">
        <table id="ticketTable" 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" data-column="0">Clear</button>
        </div>
      </th>
      <th>Name 
        <i class="bi bi-funnel filter-icon"></i>
        <div class="filter-dropdown">
          <input type="search" placeholder="Search Name" class="column-search" data-column="1">
          <button class="clear-filter" data-column="1">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="2">
          <button class="clear-filter" data-column="2">Clear</button>
        </div>
      </th>
      <!--<th>Issue Type 
        <i class="bi bi-funnel filter-icon"></i>
        <div class="filter-dropdown">
          <input type="search" placeholder="Search Issue Type" class="column-search" data-column="3">
          <button class="clear-filter" data-column="3">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" data-column="3">Clear</button>
        </div>
      </th>
       <th>Source 
        <i class="bi bi-funnel filter-icon"></i>
        <div class="filter-dropdown">
          <input type="search" placeholder="Search Source" class="column-search" data-column="4">
          <button class="clear-filter" data-column="4">Clear</button>
        </div>
      </th>
       <th>Responsible 
        <i class="bi bi-funnel filter-icon"></i>
        <div class="filter-dropdown">
          <input type="search" placeholder="Search Responsible" class="column-search" data-column="5">
          <button class="clear-filter" data-column="5">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="6">
          <button class="clear-filter" data-column="6">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="7">
          <button class="clear-filter" data-column="7">Clear</button>
        </div>
      </th>
      <th>Action</th>
    </tr>
          </thead>
          <tbody>
            <?php foreach ($allTickets as $ticket): ?>
              <tr>
                <td><?= htmlspecialchars($ticket->task_id); ?></td>
                <td><?= htmlspecialchars($ticket->user_name); ?></td>
                <td>
                <?php
                $status = htmlspecialchars($ticket->status);
                $color = ltrim($ticket->stage_color ?? '999', '#'); // Ensure it's a valid hex without #
                ?>
                <span class="badge px-2 py-1" style="background-color: #<?= $color ?>; color: #fff;">
                  <?= $status ?>
                </span>
              </td>
                <td><?= htmlspecialchars($ticket->subject); ?></td>
                <td><?= htmlspecialchars($ticket->source ?? $ticket->source ?? ''); ?></td>
                <td><?= htmlspecialchars($ticket->responsible_name ?? $ticket->responsible_name ?? ''); ?></td>
                <td><?= htmlspecialchars($ticket->project_type ?? $ticket->project_type ?? ''); ?></td>
                <td><?= htmlspecialchars($ticket->created_at); ?></td>
                <td>
                  <button class="btn btn-info btn-sm view-details-btn" data-id="<?= (int)$ticket->id; ?>">View Details</button>
                  <!--<a class="btn btn-sm btn-danger" onclick="return confirm('Are you sure you want to delete this ticket?')" href="?del="">Delete</a>-->
                </td>
              </tr>
            <?php endforeach ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>


<?php
include('footer.php');
?>
<!-- Custom Filtering -->
<script>
 $(document).ready(function () {
    const table = $('#ticketTable').DataTable();
    const columnsToFilter = [0, 1, 2, 3, 4, 5,6,7]; // Ticket ID to Date Created
    const openDropdowns = new Set();

    // Toggle dropdown visibility
    function setupFilters() {
      columnsToFilter.forEach(function (colIdx) {
        const th = $('#ticketTable thead th').eq(colIdx);
        const dropdown = th.find('.filter-dropdown');

        th.find('.filter-icon').off('click').on('click', function (e) {
          e.stopPropagation();
          $('.filter-dropdown').hide(); // Hide others
          if (openDropdowns.has(colIdx)) {
            dropdown.hide();
            openDropdowns.delete(colIdx);
          } else {
            dropdown.show();
            openDropdowns.clear();
            openDropdowns.add(colIdx);
            dropdown.find('input[type="search"]').focus();
          }
        });

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

    // Fill dropdown with unique checkbox values
    function populateFilters() {
      columnsToFilter.forEach(function (colIdx) {
        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();
        const th = $('#ticketTable thead th').eq(colIdx);
        const dropdown = th.find('.filter-dropdown');
        dropdown.empty();

        dropdown.append(`<input type="search" placeholder="Search..." class="filter-search" data-col="${colIdx}">`);
        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}"> ${val}</label>`);
        });

        dropdown.append(`<button class="apply-filter" data-col="${colIdx}">Apply Filter</button>`);
      });

      // Search inside dropdown
      $('.filter-search').off('input').on('input', function () {
        const col = $(this).data('col');
        const text = $(this).val().toLowerCase();
        $(this).closest('.filter-dropdown').find('label').each(function () {
          const label = $(this).text().toLowerCase();
          $(this).toggle(label.indexOf(text) > -1 || $(this).find('input').hasClass('filter-opt-all'));
        });
      });

      // Select All logic
      $('.filter-opt-all').off('change').on('change', function () {
        const col = $(this).data('col');
        const isChecked = $(this).is(':checked');
        $(`.filter-opt[data-col="${col}"]`).prop('checked', isChecked);
      });

      $('.filter-opt').off('change').on('change', function () {
        const col = $(this).data('col');
        const all = $(`.filter-opt[data-col="${col}"]`).length;
        const checked = $(`.filter-opt[data-col="${col}"]:checked`).length;
        $(`.filter-opt-all[data-col="${col}"]`).prop('checked', checked === all);
      });

      $('.apply-filter').off('click').on('click', function (e) {
        e.stopPropagation();
        applyFilters();
      });
    }

    // Apply checked filters
    function applyFilters() {
      columnsToFilter.forEach(function (colIdx) {
        const checkedValues = $(`.filter-opt[data-col="${colIdx}"]:checked`).map(function () {
          return $(this).val();
        }).get();

        if (checkedValues.length === 0) {
          table.column(colIdx).search('', true, false);
        } else {
          const regex = checkedValues.map(v => v.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|');
          table.column(colIdx).search(regex, true, false);
        }
      });

      table.draw();
      $('.filter-dropdown').hide();
      openDropdowns.clear();

      if (table.rows({ filter: 'applied' }).data().length === 0) {
        $('#ticketTable tbody').html(`<tr><td colspan="8" class="text-center">No tickets found</td></tr>`);
      }
    }

    // Flatpickr
    flatpickr("#dateFilter", {
      dateFormat: "Y-m-d",
      altInput: true,
      altFormat: "F j, Y",
      allowInput: true,
      onChange: function (selectedDates, dateStr) {
        table.column(7).search(dateStr).draw();
      }
    });

    setupFilters();
    populateFilters();
  });
</script>