<?php
session_start();
header('Content-Type: application/json');
require_once(__DIR__ . '/../db/conexion.php');

$response = ['success' => false, 'message' => ''];

if (!isset($_SESSION['rol']) || $_SESSION['rol'] !== 'admin') {
    $response['message'] = 'No autorizado.';
    echo json_encode($response);
    exit;
}

$admin_attuid = $_SESSION['attuid'] ?? null;

// Validar datos recibidos
$data = json_decode(file_get_contents("php://input"), true);

$aspirantes_ids = $data['aspirantes'] ?? [];
$nuevo_attuid = $data['nuevo_attuid'] ?? '';

if (empty($aspirantes_ids) || empty($nuevo_attuid)) {
    $response['message'] = 'Datos incompletos.';
    echo json_encode($response);
    exit;
}

// Validar que el nuevo attuid exista
$check = $conn->prepare("SELECT id FROM reclutadores WHERE attuid = ?");
$check->bind_param("s", $nuevo_attuid);
$check->execute();
$exists = $check->get_result()->fetch_assoc();

if (!$exists) {
    $response['message'] = 'El ATTUID destino no existe.';
    echo json_encode($response);
    exit;
}

$conn->begin_transaction();

try {
    $updated = 0;

    // Preparar statements
    $stmtUpdate = $conn->prepare("UPDATE aspirantes SET attuid = ? WHERE id = ?");
    $stmtInsertMov = $conn->prepare("
        INSERT INTO movimientos_aspirantes (aspirante_id, de_attuid, a_attuid, realizado_por)
        VALUES (?, ?, ?, ?)
    ");

    foreach ($aspirantes_ids as $id) {
        $id = intval($id);

        // Obtener attuid actual del aspirante
        $result = $conn->query("SELECT attuid FROM aspirantes WHERE id = $id");
        if ($result && $row = $result->fetch_assoc()) {
            $attuid_anterior = $row['attuid'];

            // Actualizar aspirante
            $stmtUpdate->bind_param("si", $nuevo_attuid, $id);
            $stmtUpdate->execute();

            // Insertar movimiento
            $stmtInsertMov->bind_param("isss", $id, $attuid_anterior, $nuevo_attuid, $admin_attuid);
            $stmtInsertMov->execute();

            $updated++;
        }
    }

    $conn->commit();
    $response['success'] = true;
    $response['message'] = "$updated aspirante(s) reasignado(s) correctamente.";
} catch (Exception $e) {
    $conn->rollback();
    $response['message'] = 'Error: ' . $e->getMessage();
}

echo json_encode($response);
