<?php
session_set_cookie_params([
  'lifetime' => 0,
  'path' => '/',
  'domain' => '.' . $_SERVER['HTTP_HOST'],  // Dynamic domain fetch karna
  'secure' => true,
  'httponly' => true,
  'samesite' => 'None'
]);
session_start();
include './header.php';

require_once './src/user.php';
require_once './src/Database.php';



// Check and assign session data with null fallback
$responsibleId = isset($_SESSION['responsible_id']) && !empty($_SESSION['responsible_id']) ? $_SESSION['responsible_id'] : null;
$projectId     = isset($_SESSION['project_id']) && !empty($_SESSION['project_id']) ? $_SESSION['project_id'] : null;
$folderId      = isset($_SESSION['folder_id']) && !empty($_SESSION['folder_id']) ? $_SESSION['folder_id'] : null;
$bitrix24UserId      = isset($_SESSION['bitrix_user_id']) && !empty($_SESSION['bitrix_user_id']) ? $_SESSION['bitrix_user_id'] : null;

$query = http_build_query([
  'bitrix_user'    => $bitrix24UserId,
  'responsible_id' => $responsibleId,
  'folder_id'      => $folderId,
  'project_id'     => $projectId,
]);

$users = User::find_acording_bitrx($bitrix24UserId);
?>


<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="#">Users</a>
      <span class="mx-2">/</span>
      <strong>Overview</strong>
    </div>

    <!-- Right side (Button) -->
    <a href="newuser.php?<?= htmlspecialchars($query) ?>" class="btn btn-success user-button">
      <i class="fa fa-plus"></i> Create New User
    </a>
  </div>

  
  <div class="styled-table">
    <table id="usersTable" class="table table-striped">
      <thead>

        <tr>
          <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="0">
              <button class="clear-filter btn btn-sm btn-light" data-column="0">Clear</button>
            </div>
          </th>
          <th>Email
            <i class="bi bi-funnel filter-icon"></i>
            <div class="filter-dropdown">
              <input type="search" placeholder="Search Email" class="column-search" data-column="1">
              <button class="clear-filter btn btn-sm btn-light" data-column="1">Clear</button>
            </div>
          </th>
          <th>Phone
            <i class="bi bi-funnel filter-icon"></i>
            <div class="filter-dropdown">
              <input type="search" placeholder="Search Phone" class="column-search" data-column="2">
              <button class="clear-filter btn btn-sm btn-light" data-column="2">Clear</button>
            </div>
          </th>
          <th>Created At
            <i class="bi bi-funnel filter-icon"></i>
            <div class="filter-dropdown">
              <input type="search" placeholder="Search Created Date" class="column-search" data-column="3">
              <button class="clear-filter btn btn-sm btn-light" data-column="3">Clear</button>
            </div>
          </th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody>
        <?php if (empty($users)): ?>
          <tr>
            <td colspan="5" class="text-center">Not Found</td>
          </tr>
        <?php else: ?>
          <?php foreach ($users as $user): ?>
            <?php if ($user && is_object($user)): ?> <!-- Check if $user is not null and is an object -->
              <tr>
                <td><?php echo $user->name ?: 'Not Found'; ?></td>
                <td><?php echo $user->email ?: 'Not Found'; ?></td>
                <td><?php echo $user->phone ?: 'Not Found'; ?></td>
                <td><?php echo $user->created_at ?: 'Not Found'; ?></td>
                <td>
                  <a href="edit-users-password.php?user_id=<?php echo $user->id; ?>" class="btn btn-success">Update profile</a>
                </td>
              </tr>
            <?php endif; ?>
          <?php endforeach; ?>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>


</div>
</div>
<!-- /.container-fluid -->
<?php include("footer.php") ?>
<script>
  $(document).ready(function() {
    const table = $('#usersTable').DataTable();
    const columnsToFilter = [0, 1, 2, 3];
    const openDropdowns = new Set();

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

    function setupFilters() {
      columnsToFilter.forEach(function(colIdx) {
        const th = $('#usersTable 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="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 class="filter-option"><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" data-col="${colIdx}">Apply</button>`);
      dropdown.append(`<button class="btn btn-sm btn-secondary clear-filter" data-col="${colIdx}">Clear</button>`);

      // Filter checkbox options inside dropdown
      dropdown.find('.filter-search').on('keyup', function() {
        const search = $(this).val().toLowerCase();
        dropdown.find('.filter-option').each(function() {
          const labelText = $(this).text().toLowerCase();
          $(this).toggle(labelText.includes(search));
        });
      });

      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>