<?php
include './header.php';
require_once './src/Database.php';
require_once './src/stageGetInsert.php';
 //echo "<pre>";
  //print_r($_GET);
  $projectId=$_GET['id'];
  $projectName=$_GET['project_name'];
  $bitrix24UserId=$_GET['bitrix24UserId'];
  $bitrix24ProjectId =$_GET['bitrixProject'];
  $stageData= syncProjectStages($projectId, $bitrix24UserId, $bitrix24ProjectId);
   


?>
  <style>
    .stage-card {
      color: #fff;
      padding: 10px 15px;
      margin-right: 10px;
      border-radius: 8px;
      font-weight: bold;
      white-space: nowrap;
      flex-shrink: 0;
      display: flex;
      align-items: center;
    }

    .stage-card .remove-btn {
      margin-left: 10px;
      background: rgba(255, 255, 255, 0.2);
      border: none;
      color: white;
      font-weight: bold;
      padding: 0 6px;
      border-radius: 50%;
      cursor: pointer;
    }

    .new-lead { background-color: #00cfff; }
    .called { background-color: #f5a623; }
    .not-responding { background-color: #428bca; }
    .contacted { background-color: #f44336; }
    .qualification { background-color: #5bc0de; }

    .scrolling-wrapper {
      display: flex;
      overflow-x: auto;
      padding-bottom: 10px;
    }

    .scrolling-wrapper::-webkit-scrollbar {
      height: 6px;
    }

    .scrolling-wrapper::-webkit-scrollbar-thumb {
      background-color: #ccc;
      border-radius: 10px;
    }
  </style>
  <div class="container-fluid main-content">
    <h4 class="mb-3 text-center"><?=$projectName?> Project Stages</h4>

    <div class="card p-3">
          <div>
         <a href="#" class="btn btn-primary my-3" data-toggle="modal" data-target="#stageModal">
  <i class="fa fa-plus"></i> Create New Stage
</a>
      </div>
      
        <div id="responseMsg"></div>
        <div id="stage-alert"></div>
       
      <div class="scrolling-wrapper" id="stageWrapper">
      
      </div>
      
    </div>
  </div>
  <div class="modal fade" id="stageModal" tabindex="-1" role="dialog" aria-labelledby="stageModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <form id="stageForm">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="stageModalLabel">Add New Stage</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>

        <div class="modal-body">
          <!-- Stage Name -->
          <div class="form-group">
            <label for="stageName">Stage Name</label>
            <input type="text" class="form-control" id="stageName" name="stage_name" required>
          </div>

          <!-- Stage Color -->
          <div class="form-group">
            <label for="stageColor">Stage Color (Hex)</label>
            <input type="text" class="form-control" id="stageColor" name="stage_color" placeholder="e.g. FF0000" required>
          </div>       
          <input type="hidden" name="project_id" value="<?=$projectId?>">

          <input type="hidden" name="bitrix_user_id" value="<?=$bitrix24UserId?>">
          <input type="hidden" name="bitrix_project_id" value="<?=$bitrix24ProjectId?>">
        </div>

        <div class="modal-footer">
          <button type="submit" class="btn btn-success">Create Stage</button>
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
        </div>
      </div>
    </form>
  </div>
</div>
<?php  include("footer.php");?>
<script>
     let bitrixUserId = "<?=$bitrix24UserId; ?>";
     let projectId = "<?= $projectId; ?>";
     let bitrix24projectId = "<?= $bitrix24ProjectId; ?>";
    function removeStage(id,stageId,bitrix24User) {
if (!confirm("Are you sure you want to delete this stage?")) return;

  $.ajax({
    url: './src/deleteStage.php',
    method: 'POST',
    data: {
      stage_id: id,
      bitrix_stage_id: stageId,
      bitrix24_userId:bitrix24User
    },
   success: function (response) {
    showStageAlert(response, 'success');
    fetchStages(projectId, bitrixUserId); // reload updated stages
  },
  error: function () {
    showStageAlert("❌ Failed to delete the stage.", 'danger');
  }
  });
    }
   $('#stageForm').on('submit', function (e) {
    e.preventDefault();

    const form = $(this);
    const submitBtn = form.find('button[type="submit"]');
    const originalText = submitBtn.html();

    // Show loader on button
    submitBtn.prop('disabled', true).html(`<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Saving...`);

    $.ajax({
      url: './src/Projectstage.php',
      type: 'POST',
      data: form.serialize(),
      success: function (res) {
        // Set message in localStorage for redirect display
        localStorage.setItem('alertMessage', res);
        localStorage.setItem('alertType', 'success');
        location.reload(); // Redirect to same page
      },
      error: function () {
        localStorage.setItem('alertMessage', '❌ Something went wrong.');
        localStorage.setItem('alertType', 'danger');
        location.reload();
      },
      complete: function () {
        submitBtn.prop('disabled', false).html(originalText);
      }
    })
  });

  $(function () {
    const message = localStorage.getItem('alertMessage');
    const type = localStorage.getItem('alertType') || 'success';

    if (message) {
      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>`;
      $('#responseMsg').html(alertHtml);

      localStorage.removeItem('alertMessage');
      localStorage.removeItem('alertType');
    }
  });
function showStageAlert(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>`;

  $('#stage-alert').html(alertHtml);

  // Optional: auto-hide after 5 seconds
  setTimeout(() => {
    $('.alert').alert('close');
  }, 5000);
}
  function fetchStages(projectId, bitrixUserId) {
  $.ajax({
    url: './src/Projectstage.php',
    method: 'GET',
    data: {
      project_id: projectId,
      bitrix_user_id: bitrixUserId,
      bitrix24_project: bitrix24projectId
    },
    success: function(response) {
      let stages = JSON.parse(response);
      let html = '';

      stages.forEach(stage => {
       
        const safeColor = '#' + stage.stage_color.trim();
       

        html += `
          <div class="stage-card" style="background-color: ${safeColor}; color: #fff;">
            ${stage.stage_name}
            <button class="remove-btn" onclick="removeStage(${stage.id},${stage.stage_id},${bitrixUserId})">×</button>
          </div>
        `;
      });

      $('#stageWrapper').html(html);
    },
    error: function() {
      $('#stageWrapper').html('<div class="text-danger">Failed to load stages.</div>');
    }
  });
}

fetchStages(projectId, bitrixUserId);

  </script>
 