<?php
/**
 * SAC 2026 - NUCLEAR BULK LOAD USERS v2.0
 * REPARACIÓN: Soporte para migración de IDs de Telegram masivos.
 */
require_once 'config.php';
checkAccess(['admin', 'programmer']);

$data = $REQUEST_DATA;

if (!isset($data['rows']) || !is_array($data['rows'])) {
    response(["error" => "Estructura de datos inválida"], 400);
}

try {
    $pdo->beginTransaction();
    $count = 0;

    $stmt = $pdo->prepare("INSERT INTO users 
        (username, full_name, email, phone, role, cedula, status, password, telegram_chat_id) 
        VALUES (:user, :name, :mail, :phone, :role, :ced, :stat, :pass, :tgid)
        ON DUPLICATE KEY UPDATE 
        full_name = VALUES(full_name), 
        email = VALUES(email), 
        phone = VALUES(phone), 
        role = VALUES(role), 
        status = VALUES(status),
        telegram_chat_id = VALUES(telegram_chat_id)");

    foreach ($data['rows'] as $row) {
        $cedula = trim($row['cedula']);
        $passHash = password_hash($cedula, PASSWORD_DEFAULT);

        $stmt->execute([
            ':user'  => $cedula,
            ':name'  => strtoupper(trim($row['nombre_completo'])),
            ':mail'  => strtolower(trim($row['correo'])),
            ':phone' => trim($row['telefono']),
            ':role'  => strtolower(trim($row['rol'])), 
            ':ced'   => $cedula,
            ':stat'  => 'active',
            ':pass'  => $passHash,
            ':tgid'  => trim($row['telegram_id'] ?? '') // Se captura el nuevo campo del CSV
        ]);
        $count++;
    }

    $pdo->commit();
    logSystemAction("CARGA MASIVA USUARIOS v2.0: $count procesados.", "USUARIOS");
    response(["success" => true, "total" => $count]);

} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    response(["error" => "Fallo Nuclear en Carga: " . $e->getMessage()], 500);
}
?>