<?php
session_start();
if (!isset($_SESSION['rol']) || !in_array($_SESSION['rol'], ['admin', 'adminTi'])) {
  header('Location: ../../index.php');
  exit();
}
?>

<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8" />
  <title>Movimientos de Aspirantes</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <!-- Bootstrap 5 + FontAwesome + MDB -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet" />
  <link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/6.4.0/mdb.min.css" rel="stylesheet" />
  <link href="../assets/css/recruiter.css" rel="stylesheet" />
</head>
<body class="bg-light">
<div class="d-flex">
  <?php include '../includes/sidebar.php'; ?>
  <div class="main-content" id="mainContent">
    <?php include '../includes/topbar.php'; ?>

    <div class="container-fluid p-4"> 
      <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="fw-bold">Reasignación de Aspirantes</h2>
        <a href="ver-movimientosadmin.php" class="btn btn-outline-secondary">
          <i class="fas fa-history me-2"></i>Ver movimientos
        </a>
      </div>

      <!-- Filtros -->
      <div class="card mb-4">
        <div class="card-body">
          <form id="form-reasignacion">
            <div class="row g-3">
              <div class="col-md-6">
                <label for="reclutador_origen" class="form-label">Reclutador actual</label>
                <select class="form-select" id="reclutador_origen" required>
                  <option value="">Selecciona un reclutador</option>
                </select>
              </div>
              <div class="col-md-6">
                <label for="reclutador_destino" class="form-label">Nuevo reclutador</label>
                <select class="form-select" id="reclutador_destino" required>
                  <option value="">Selecciona el nuevo reclutador</option>
                </select>
              </div>
            </div>
          </form>
        </div>
      </div>

      <!-- Tabla de aspirantes -->
      <div class="card">
        <div class="card-header bg-white d-flex justify-content-between align-items-center">
          <h5 class="mb-0">Aspirantes del reclutador</h5>
          <button class="btn btn-sm btn-success" id="btn-reasignar" disabled>
            <i class="fas fa-exchange-alt me-1"></i> Reasignar seleccionados
          </button>
        </div>
        <div class="card-body p-0">
          <div class="table-responsive">
            <table class="table table-hover mb-0">
              <thead class="table-light">
                <tr>
                  <th><input type="checkbox" id="select-all" /></th>
                  <th>Nombre</th>
                  <th>Vacante</th>
                  <th>Ubicación</th>
                  <th>Estatus</th>
                </tr>
              </thead>
              <tbody id="tabla-aspirantes">
                <!-- JS llenará esta tabla -->
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div><!-- /container -->
  </div>
</div>

<!-- Scripts -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/6.4.0/mdb.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', () => {
  const origen = document.getElementById('reclutador_origen');
  const destino = document.getElementById('reclutador_destino');
  const tabla = document.getElementById('tabla-aspirantes');
  const btnReasignar = document.getElementById('btn-reasignar');
  const selectAll = document.getElementById('select-all');

  // Cargar reclutadores
  fetch('../../backend/admin/get_reclutadores.php?roles=reclutador,admin&exclude_attuids=KA0707,EC420T')
    .then(r => r.json())
    .then(data => {
      data.reclutadores.forEach(r => {
        const option1 = new Option(`${r.nombre_completo} (${r.attuid})`, r.attuid);
        const option2 = option1.cloneNode(true);
        origen.appendChild(option1);
        destino.appendChild(option2);
      });
    });

  // Cargar aspirantes del reclutador seleccionado
  origen.addEventListener('change', () => {
    tabla.innerHTML = '';
    btnReasignar.disabled = true;
    fetch(`../../backend/admin/get_aspirantes_por_attuid.php?attuid=${origen.value}`)
      .then(r => r.json())
      .then(data => {
        if (!data.success) return;
        data.aspirantes.forEach(a => {
          const tr = document.createElement('tr');
          tr.innerHTML = `
            <td><input type="checkbox" class="aspirante-checkbox" value="${a.id}"></td>
            <td>${a.nombre_completo}</td>
            <td>${a.puesto}</td>
            <td>${a.ubicacion}</td>
            <td><span class="badge bg-secondary">${a.estatus}</span></td>
          `;
          tabla.appendChild(tr);
        });
      });
  });

  // Activar botón si hay selección
  tabla.addEventListener('change', () => {
    const seleccionados = document.querySelectorAll('.aspirante-checkbox:checked');
    btnReasignar.disabled = seleccionados.length === 0;
  });

  // Seleccionar todos
  selectAll.addEventListener('change', () => {
    const checks = tabla.querySelectorAll('.aspirante-checkbox');
    checks.forEach(cb => cb.checked = selectAll.checked);
    btnReasignar.disabled = !selectAll.checked;
  });

  // Reasignar
  btnReasignar.addEventListener('click', () => {
    const ids = [...document.querySelectorAll('.aspirante-checkbox:checked')].map(cb => cb.value);
    const nuevoAttuid = destino.value;

    if (!nuevoAttuid) return alert("Selecciona un reclutador destino.");
    if (!ids.length) return alert("Selecciona al menos un aspirante.");

    fetch('../../backend/admin/reasignar_aspirantes.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        aspirantes: ids,
        nuevo_attuid: nuevoAttuid
      })
    })
    .then(r => r.json())
    .then(data => {
      if (!data.success) throw new Error(data.message || 'Error al reasignar');
      alert('Reasignación exitosa');
      location.reload();
    })
    .catch(err => {
      console.error('Error al reasignar aspirantes:', err);
    });
  });
});
</script>
</body>
</html>
