<?php
 
error_reporting(E_ALL);
ini_set('display_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';
require_once './src/user.php';
require_once './src/AccessToken.php';
require_once './src/team.php';
 

$bitrix24UserId = $_SESSION['bitrix_user_id'] ?? null;
$users = User::find_acording_bitrx($bitrix24UserId);
$tokenData = AccessToken::getAccessTokenByUserId($bitrix24UserId);
$accessToken = $tokenData['access_token'];
$clientEndPoint = $tokenData['client_endpoint'];
$teams = Team::findAll($clientEndPoint, $accessToken);
?>

<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="#">Setting</a>
      <span class="mx-2">/</span>
      <strong>Overview</strong>
    </div>
    <button class="btn btn-success user-button configure-bt" id="openPopup">⚙️ Configure</button>
  </div>
<div id="alert-container"></div>
  <div class="card mb-3">
    <div class="card-body">
      <div class="styled-table">
        <table id="ticketTable" class="table table-striped">
          <thead>
            <tr>
              <th>Project Name
                <i class="bi bi-funnel filter-icon"></i>
                <div class="filter-dropdown">
                  <input type="search" placeholder="Search Project Name" class="column-search" data-column="0">
                  <button class="clear-filter btn btn-sm btn-light" data-column="0">Clear</button>
                </div>
              </th>

              <th>Flow Type
                <i class="bi bi-funnel filter-icon"></i>
                <div class="filter-dropdown">
                  <input type="search" placeholder="Search Flow Type" class="column-search" data-column="1">
                  <button class="clear-filter btn btn-sm btn-light" data-column="1">Clear</button>
                </div>
              </th>

              <th>Responsible Person
                <i class="bi bi-funnel filter-icon"></i>
                <div class="filter-dropdown">
                  <input type="search" placeholder="Search Responsible Person" class="column-search" data-column="2">
                  <button class="clear-filter btn btn-sm btn-light" data-column="2">Clear</button>
                </div>
              </th>

              <th>Query Email
                <i class="bi bi-funnel filter-icon"></i>
                <div class="filter-dropdown">
                  <input type="search" placeholder="Search Query Email" class="column-search" data-column="3">
                  <button class="clear-filter btn btn-sm btn-light" data-column="3">Clear</button>
                </div>
              </th>

              <th>Project Type
                <i class="bi bi-funnel filter-icon"></i>
                <div class="filter-dropdown">
                  <input type="search" placeholder="Search Project Type" class="column-search" data-column="4">
                  <button class="clear-filter btn btn-sm btn-light" data-column="4">Clear</button>
                </div>
              </th>

              <th>Actions</th>
            </tr>

          </thead>
          <tbody id="projectData"></tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<!-- Slide Panel -->
<div class="slide-panel" id="popupPanel">
  <span class="close-btn" id="closePopup">&times;</span>
  <h4 class="mb-4">⚙️ Configure Project Flow</h4>
  <form id="popupProjectForm">
      <input type="hidden" id="localProjectId" name="local_project_id">
      <input type="hidden" name="bitrix_project_id" id="bitrixProjectId">

    <input type="hidden" name="bitrix_user_id" value="<?= $bitrix24UserId; ?>">

    <div class="form-group">
      <label>Flow Type</label>
      <select name="flow_type" class="form-control" id="flowTypeSelect" required>
        <option value="">Select Flow</option>
        <option value="internal">Internal Team</option>
        <option value="external">External Client</option>
      </select>
    </div>

    <div class="form-group">
      <label>Project Name</label>
      <input type="text" name="project_name" class="form-control" required>
    </div>

    <div class="form-group" id="queryEmailGroup">
      <label>Query Email</label>
      <input type="email" name="query_email" class="form-control">
    </div>

    <div class="form-group">
      <label>Project Type</label>
      <select id="projectTypeDropdown" class="form-control project-type-select" name="project_type" required>
        <option value="">Select Type</option>
        <option value="hr">HR</option>
        <option value="crm">CRM</option>
        <option value="support">Support</option>
        <option value="custom">Custom</option>
      </select>
    </div>

    <div class="form-group custom-type-input">
      <label>Custom Type</label>
      <input type="text" id="customProjectType" class="form-control" placeholder="Enter custom type">
    </div>

    <div class="form-group">
      <label>Responsible Persons</label>
      <select id="responsiblePersons" class="form-control">
        <option value="">Select Person</option>
        <?php foreach ($teams as $team): ?>
          <option value="<?= $team->ID; ?>"><?= $team->NAME; ?></option>
        <?php endforeach ?>
      </select>
      <div id="selectedPersons" class="mt-2"></div>
    </div>

    <button type="submit" class="btn btn-success">💾 Save</button>
  </form>
</div>

<?php include("footer.php") ?>
<script>
  let bitrix24UserId = "<?= $bitrix24UserId ?>";
  let editMode = false;
  const selectedMap = {};

  $(document).ready(function () {
    initUI();
    initFormHandlers();
    initTableAndFilters();
    displayAlertFromStorage();
  });

  function initUI() {
    $('#projectTypeDropdown').on('change', handleProjectTypeChange);

    $('#openPopup').on('click', () => {
      resetForm();
      editMode = false;
      $('#popupPanel').addClass('show');
      $('#popupProjectForm button[type="submit"]').text('Save');
    });

    $('#closePopup').on('click', () => $('#popupPanel').removeClass('show'));

    $('#flowTypeSelect').on('change', function () {
      const type = $(this).val();
      $('#queryEmailGroup').toggle(type !== 'internal');
      $('#queryEmailGroup input').prop('required', type !== 'internal');
    });

    $('#responsiblePersons').on('change', function () {
      const val = $(this).val();
      const text = $(this).find('option:selected').text();
      if (val && !selectedMap[val]) {
        selectedMap[val] = text;
        $('#selectedPersons').append(
          `<span class="selected-person" data-id="${val}">${text}<span class="remove" data-id="${val}"> ×</span></span>`
        );
      }
      $(this).val('');
    });

    $(document).on('click', '.remove', function () {
      const id = $(this).data('id');
      delete selectedMap[id];
      $(`.selected-person[data-id="${id}"]`).remove();
    });

    $(document).on('click', '.edit-btn', handleEditClick);
  }

  function resetForm() {
    $('#popupProjectForm')[0].reset();
    $('#projectTypeDropdown').val('').trigger('change');
    //$('#customProjectType').val('').hide();
    $('#customProjectType').removeAttr('name').removeAttr('required');
    $('#projectTypeDropdown').attr('name', 'project_type');
    $('#selectedPersons').empty();
    Object.keys(selectedMap).forEach(k => delete selectedMap[k]);
    $('#localProjectId').val('');
  }

  function handleProjectTypeChange() {
    const selected = $(this).val();
    if (selected === 'custom') {
      $('.custom-type-input').show();
      $(this).removeAttr('name');
      $('#customProjectType').attr('name', 'project_type').attr('required', true);
    } else {
      $('.custom-type-input').hide();
      $('#customProjectType').removeAttr('name').removeAttr('required');
      $(this).attr('name', 'project_type');
    }
  }

  function handleEditClick(e) {
    e.preventDefault();
    const btn = $(this);
    const id = btn.data('id');
    const projectId = btn.data('projectid');
    const name = btn.data('name');
    const flow = btn.data('flow');
    const email = btn.data('email');
    const type = btn.data('type');
    const persons = btn.data('persons');

    editMode = true;
    $('#popupPanel').addClass('show');
    $('#popupProjectForm button[type="submit"]').text('Update');

    $('#localProjectId').val(id);
    $('#bitrixProjectId').val(projectId);
    $('input[name="project_name"]').val(name);
    $('#flowTypeSelect').val(flow).trigger('change');
    $('input[name="query_email"]').val(email);
    $('#projectTypeDropdown').val(type).trigger('change');

    if (!['crm', 'support', 'hr'].includes(type)) {
      $('#projectTypeDropdown').val('custom').trigger('change');
      $('#customProjectType').val(type);
    }

    $('#selectedPersons').html('');
    Object.keys(selectedMap).forEach(k => delete selectedMap[k]);

    if (persons && persons.length) {
      persons.forEach(p => {
        selectedMap[p.id] = p.name;
        $('#selectedPersons').append(
          `<span class="selected-person" data-id="${p.id}">${p.name}<span class="remove" data-id="${p.id}"> ×</span></span>`
        );
      });
    }
  }

  function initFormHandlers() {
    $('#popupProjectForm').on('submit', function (e) {
      e.preventDefault();
      const form = $(this)[0];
      const formData = new FormData(form);

      for (const id in selectedMap) {
        formData.append('responsible_persons[]', JSON.stringify({ id, name: selectedMap[id] }));
      }

      const saveBtn = $(this).find('button[type="submit"]');
      const originalText = saveBtn.html();
      saveBtn.prop('disabled', true).html(
        `<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> ${editMode ? 'Updating' : 'Saving'}...`
      );

      const url = editMode ? 'ProjectUpdate.php' : 'ProjectSetting.php';

      $.ajax({
        url,
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function (re) {
             console.log(re);
          const msg = editMode ? '✅ Project flow updated successfully!' : '✅ Project flow added successfully!';
          localStorage.setItem('alertMessage', msg);
          localStorage.setItem('alertType', 'success');
          location.reload();
        },
        error: function (xhr) {
          console.error(xhr.responseText);
          localStorage.setItem('alertMessage', '❌ Something went wrong. Please try again.');
          localStorage.setItem('alertType', 'danger');
          location.reload();
        },
        complete: function () {
          saveBtn.prop('disabled', false).html(editMode ? 'Update' : 'Save');
        }
      });
    });
  }
  $(document).on('click', '.delete-project', function (e) {
  e.preventDefault();

  if (!confirm('Are you sure you want to delete this project?')) return;

  const localProjectId = $(this).data('local-id');
  const bitrixProjectId = $(this).data('bitrix-id');
  const bitrixUserId = $(this).data('user-id');

  const formData = new FormData();
  formData.append('local_project_id', localProjectId);
  formData.append('bitrix_project_id', bitrixProjectId);
  formData.append('bitrix_user_id', bitrixUserId);

  $.ajax({
    url: 'deleteProject.php',
    method: 'POST',
    data: formData,
    processData: false,
    contentType: false,
    success: function (response) {
      console.log(response);

      if (response.success) {
        localStorage.setItem('alertMessage', '✅ Project deleted successfully!');
        localStorage.setItem('alertType', 'success');
      } else {
        localStorage.setItem('alertMessage', '❌ ' + (response.message || 'Failed to delete project.'));
        localStorage.setItem('alertType', 'danger');
      }

      location.reload();
    },
    error: function (xhr) {
      console.error(xhr.responseText);
      localStorage.setItem('alertMessage', '❌ Server error. Please try again.');
      localStorage.setItem('alertType', 'danger');
      location.reload();
    }
  });
});


  function displayAlertFromStorage() {
    const message = localStorage.getItem('alertMessage');
    const type = localStorage.getItem('alertType') || 'success';
    if (message) {
      showAlert(message, type);
      localStorage.removeItem('alertMessage');
      localStorage.removeItem('alertType');
    }
  }

  function showAlert(message, type = 'success') {
    const alertHtml = `
      <div class="alert alert-${type} alert-dismissible fade show mt-3" role="alert">
        ${message}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>`;
    $('#alert-container').html(alertHtml);
  }

  // --- DataTable logic ---

  let table;
  const columnsToFilter = [0, 1, 2, 3, 4];
  const openDropdowns = new Set();

  function initTableAndFilters() {
    $.ajax({
      url: './src/flows-get.php',
      method: 'POST',
      dataType: 'json',
      data: { bitrix_user_id: bitrix24UserId },
      success: function (response) {
        if (response.success) {
          const projects = response.data;
          let html = '';
          projects.forEach(project => {
            const persons = project.responsible_persons?.map(p => p.name).join(', ') || '';
            html += `
              <tr>
                <td>${project.project_name}</td>
                <td>${project.flow_type}</td>
                <td>${persons}</td>
                <td>${project.query_email ?? ''}</td>
                <td>${project.project_type}</td>
                <td>
                  <div class="dropdown">
                    <button class="btn btn-sm btn-secondary dropdown-toggle" type="button" data-toggle="dropdown">Actions</button>
                    <div class="dropdown-menu">
                      <a class="dropdown-item edit-btn"
                         href="#"
                         data-id="${project.local_project_id}"
                         data-projectid="${project.bitrix_project_id}"
                         data-name="${project.project_name}"
                         data-flow="${project.flow_type}"
                         data-email="${project.query_email ?? ''}"
                         data-type="${project.project_type}"
                         data-persons='${JSON.stringify(project.responsible_persons)}'>Edit</a>
<a href="#" 
   class="dropdown-item delete-project" 
   data-local-id="${project.local_project_id}" 
   data-bitrix-id="${project.bitrix_project_id}" 
   data-user-id="${bitrix24UserId}">
   Delete
</a>                      <a class="dropdown-item" href="stage.php?id=${project.local_project_id}&project_name=${project.project_name}&bitrix24UserId=${bitrix24UserId}&bitrixProject=${project.bitrix_project_id}">Create Stage</a>
                    </div>
                  </div>
                </td>
              </tr>`;
          });

          $('#projectData').html(html);
          table = $('#ticketTable').DataTable({ destroy: true });

          setupFilters();
          populateFilters();
        }
      }
    });
  }

  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').not(dropdown).hide();
        if (openDropdowns.has(colIdx)) {
          dropdown.hide();
          openDropdowns.delete(colIdx);
        } else {
          dropdown.show();
          openDropdowns.clear();
          openDropdowns.add(colIdx);
          dropdown.find('input.filter-search').focus();
        }
      });

      dropdown.off('click').on('click', e => e.stopPropagation());
    });

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

  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}" checked> ${val}</label>`);
      });

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

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

    $('.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 total = $(`.filter-opt[data-col="${col}"]`).length;
      const checked = $(`.filter-opt[data-col="${col}"]:checked`).length;
      $(`.filter-opt-all[data-col="${col}"]`).prop('checked', checked === total);
    });

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

  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="7" class="text-center">No tickets found</td></tr>`);
    }
  }
</script>
