<?php
session_start();
header('Content-Type: application/json');

include('../db/conexion.php');

// Validar que se reciban los datos por POST
if (!isset($_POST['attuid']) || !isset($_POST['password'])) {
    echo json_encode(['success' => false, 'message' => 'Datos incompletos']);
    exit;
}

$attuid = trim($_POST['attuid']);
$password = trim($_POST['password']);

$sql = "SELECT id, attuid, nombre, apellido_paterno, apellido_materno, password_hash, rol FROM reclutadores WHERE attuid = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $attuid);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 1) {
    $user = $result->fetch_assoc();
    if (password_verify($password, $user['password_hash'])) {
        // Guardar toda la información necesaria en sesión
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['attuid'] = $user['attuid'];
        $_SESSION['rol'] = $user['rol'];
        $_SESSION['nombre'] = $user['nombre'];
        $_SESSION['apellido_paterno'] = $user['apellido_paterno'];
        $_SESSION['apellido_materno'] = $user['apellido_materno'];

        // Validar posiciones vencidas
        $expiredPositions = false;
        $today = date('Y-m-d');
        $sqlPos = "SELECT COUNT(*) AS total FROM Posiciones WHERE fechaCierre <= ?";
        $stmtPos = $conn->prepare($sqlPos);
        $stmtPos->bind_param("s", $today);
        $stmtPos->execute();
        $resPos = $stmtPos->get_result();
        if ($resPos && $rowPos = $resPos->fetch_assoc()) {
            if ((int)$rowPos['total'] > 0) {
                $expiredPositions = true;
            }
        }
        $stmtPos->close();

        // Determinar redirección según rol
        if ($user['rol'] === 'admin') {
            $redirectUrl = 'frontend/admin/panel-admin.php';
        } elseif ($user['rol'] === 'adminTi') {
            $redirectUrl = 'frontend/admin/panel-admin.php';
        } elseif ($user['rol'] === 'coordinador') {
            $redirectUrl = 'frontend/admin/panel-admin.php';
        } elseif ($user['rol'] === 'reclutador') {
            $redirectUrl = 'frontend/recruiter/dashboard.php';
        } elseif ($user['rol'] === 'capturista') {
            $redirectUrl = 'frontend/capturista/capture.php';
        } elseif ($user['rol'] === 'capturistaRH') {
            $redirectUrl = 'frontend/capturista/capture.php';
        } elseif ($user['rol'] === 'capturista_rrhh') {
            $redirectUrl = 'frontend/capturista/mis-aspirantes.php';
        } elseif ($user['rol'] === 'contabilidad') {
            $redirectUrl = 'frontend/contabilidad/altas.php';
        } elseif ($user['rol'] === 'subdistribuidor') {
            $redirectUrl = 'frontend/subdistribuidor/candidatos.php';
        } else {
            // Rol desconocido, por seguridad cerrar sesión
            session_destroy();
            echo json_encode(['success' => false, 'message' => 'Rol no autorizado']);
            exit;
        }

        echo json_encode([
            'success' => true,
            'redirect' => $redirectUrl,
            'expiredPositions' => $expiredPositions
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Contraseña incorrecta']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Usuario no encontrado']);
}
?>
