<?php
require_once('config.php');

// Delete Team
if (isset($_GET['delid'])) {
  $id_for_delete = $_GET['delid'] ;
  if (deleteData('mahamudfutureit_team', 'ID', $id_for_delete)){
    header("Location:mahamudfutureit-family.php");
    exit;
  }else {
    $tt_alert = ttAlert('danger', 'Something went wrong to delete !');
  }
}

// Add Team
if (isset($_POST['add_teacher'])) {
  $post_form_data = array(
    "TeamName"             => $_POST['TeamName'],
    "Position"           => 99999,
    "Status"           => 'Show',
  );
   // Insert Database
   $insert_now = InsertData('mahamudfutureit_team', $post_form_data);
    if ($insert_now) {
        $tt_alert = ttAlert('success', '  Team Added !');
     }else {
       $tt_alert = ttAlert('danger', 'Something went wrong to add Team !');
     }
}
require_once('inc/header.php');
?>
<style>
.dragElem {
  opacity: 0.4;
}
.bi-arrows-move {
    cursor: move !important;
}
.drop-placeholder {
  height: 40px;
  margin: 4px 0;
  background: #e0e0e0;
  border: 2px dashed #999;
  opacity: 0.5;
}
</style>
<main id="main" class="main">
  <div class="row">
    <div class="col-6 align-items-center">
      <div class="pagetitle mb-2">
        <h1><?php echo $page_title ?></h1>
      </div>
    </div>
  </div>
  <?php
  echo $tt_alert ?? '';
  ?>
  <section class="section mt-4">
    <div class="row">
      <div class="col-md-5">
        <div class="bg-white rounded-2 p-3">
          <?php
          $tt_team = showAllttdata("mahamudfutureit_team", "ORDER BY  Position  ASC");
          if (!empty($tt_team)) {
            ?>
            <div id="shortAbleList">
              <?php
              foreach ($tt_team as $the_team) {
                ?>
                <h4 class="justify-content-between align-items-center d-flex short-single m-0 p-2 border h6 mb-1" data-item-id="<?php echo $the_team['ID'] ?>" draggable="true">
                  <div class="d-flex justify-content-between align-items-center">
                    <i class="bi bi-arrows-move pe-2" style=" line-height: 1px; "></i>
                    <input type="text" name="team_name"  class="form-control form-control-sm border-0" value="<?php echo $the_team['TeamName'] ?>">
                  </div>
                  <div class="justify-content-between align-items-center d-flex">
                    <?php ttPopaction('delete_pop'.$the_team['ID'],'mahamudfutureit-family.php?delid='.$the_team['ID']); ?>
                    <div class="form-check form-switch">
                     <input name="team_status" class="form-check-input" type="checkbox" role="switch"  <?php echo ($the_team['Status'] =='Hide') ? '' : 'checked' ?>>
                    </div>
                    <a class="text-danger" data-bs-toggle="modal" data-bs-target="#delete_pop<?php echo $the_team['ID'] ?>" href="#"><i class="bi bi-trash3"></i></a>
                  </div>

                </h4>
                <?php
              }
              ?>
            </div>
            <?php
          }else {
            echo "No Team Added";
          }
          ?>
          <button id="saveChanges" class="btn btn-primary mt-2">
            <span class="btn-text">Save Changes</span>
            <img id="loadingSpinner" src="assets/img/loading.gif" alt="Loading..." style="width:18px; display:none; margin-left:8px;">
          </button>

        </div>
      </div>
      <div class="col-md-7">
        <form class="" action="" method="post">
          <div class="bg-white rounded-2 p-3">
              <div class="form-group mb-2">
                <label>Team Name <span class="text-danger">*</span> </label>
                <input name="TeamName" type="text" class="form-control" placeholder="eg. Upazila Correspondent" required>
              </div>
              <button type="submit" class="btn btn-success mt-2" name="add_teacher">Add Team</button>
          </div>
        </form>
      </div>
    </div>
  </section>
</main>
<script>
$(function() {
  let dragSrcEl = null;
  let placeholder = $('<div class="drop-placeholder"></div>');

  // Start dragging
  $(document).on("dragstart", ".short-single", function (e) {
    dragSrcEl = this;
    e.originalEvent.dataTransfer.effectAllowed = "move";
    e.originalEvent.dataTransfer.setData("text/html", this.outerHTML);
    $(this).addClass("dragElem");
  });

  // Drag over other items
  $(document).on("dragover", ".short-single", function (e) {
    e.preventDefault();
    if (dragSrcEl !== this) {
      $(this).before(placeholder);
    }
    return false;
  });

  // Drag over placeholder
  $(document).on("dragover", ".drop-placeholder", function (e) {
    e.preventDefault();
    return false;
  });

  // Drop on item
  $(document).on("drop", ".short-single", function (e) {
    e.stopPropagation();
    if (dragSrcEl !== this) {
      $(this).before($(dragSrcEl));
    }
    placeholder.remove();
    return false;
  });

  // Drop on placeholder
  $(document).on("drop", ".drop-placeholder", function (e) {
    e.stopPropagation();
    $(this).before($(dragSrcEl));
    placeholder.remove();
    return false;
  });

  // End dragging
  $(document).on("dragend", ".short-single", function () {
    $(".short-single").removeClass("dragElem");
    placeholder.remove();
  });

  // Collect data
  function collectData() {
    let teamData = [];
    $("#shortAbleList .short-single").each(function () {
      let id = $(this).data("item-id");
      let name = $(this).find("input[name='team_name']").val();
      let status = $(this).find("input[name='team_status']").is(":checked") ? "Show" : "Hide";

      teamData.push({
        id: id,
        name: name,
        status: status
      });
    });
    return teamData;
  }

  // Save button click
  $("#saveChanges").on("click", function () {
    let teamData = collectData();

    // Show spinner
    $("#loadingSpinner").show();
    $("#saveChanges").prop("disabled", true); // disable button

    $.ajax({
      url: "inc/update-team.php",
      method: "POST",
      data: { teams: teamData },
      error: function (xhr, status, error) {
        console.error("Error:", error);
      },
      complete: function () {
        // Always run after success or error
        $("#loadingSpinner").hide();
        $("#saveChanges").prop("disabled", false);
      }
    });
  });
});
</script>

<?php require_once('inc/footer.php'); ?>
