<?php
// supervisor/process_bulk_supervisor.php

require_once('../includes/supervisor_check.php');
require_once('../config/database.php'); 
require_once('../includes/functions.php');

// Inicializar variables de sesión para los resultados
$_SESSION['sv_bulk_upload_message_display'] = null;
$_SESSION['sv_bulk_upload_error_message_display'] = null;
$_SESSION['sv_bulk_upload_info_message_display'] = null;
$_SESSION['sv_bulk_upload_summary_display'] = [];
$_SESSION['sv_bulk_upload_errors_details_display'] = [];
$_SESSION['sv_bulk_upload_success_count_display'] = 0; // Creados
$_SESSION['sv_bulk_upload_updated_count_display'] = 0; // Actualizados
$_SESSION['sv_bulk_upload_skipped_count_display'] = 0; // Omitidos (duplicados no actualizados)
$_SESSION['sv_bulk_upload_error_count_display'] = 0;   // Errores de fila

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["user_csv"])) {
    if (!isset($_POST['csrf_token']) || !validate_csrf_token($_POST['csrf_token'])) {
        $_SESSION['sv_bulk_upload_error_message_display'] = "Error de validación de seguridad (CSRF token). Por favor, intente de nuevo.";
        header("Location: bulk_upload_supervisor.php");
        exit;
    }
    
    $update_existing_users = isset($_POST['update_existing_sv']) ? true : false; // Leer el checkbox

    $file = $_FILES["user_csv"];
    $success_count = 0; $updated_count = 0; $skipped_count = 0; $error_count = 0;
    $users_processed_details = []; $errors_details = []; 

    // ... (Validaciones de archivo: error, tipo, tamaño - SIN CAMBIOS, como las tenías antes) ...
    if ($file["error"] !== UPLOAD_ERR_OK) {
        $_SESSION['sv_bulk_upload_error_message_display'] = "Error al subir el archivo (Código: " . $file["error"] . ")";
    } elseif (!in_array(strtolower($file["type"]), ["text/csv", "application/vnd.ms-excel", "application/csv", "text/plain"])) {
        $_SESSION['sv_bulk_upload_error_message_display'] = "Tipo de archivo inválido ('" . htmlspecialchars($file["type"]) . "'). Solo se permiten archivos CSV.";
    } elseif ($file["size"] > 5000000) { 
        $_SESSION['sv_bulk_upload_error_message_display'] = "El archivo es demasiado grande (Máx 5MB).";
    } else {
        $tmp_name = $file["tmp_name"];
        $row_number = 1;
        $header_validated = false;
        $expected_header = ['codigo', 'nombre_completo', 'username', 'email']; 
        $header_map = [];                                                              

        if (($handle = fopen($tmp_name, "r")) !== FALSE) {
            setlocale(LC_ALL, 'es_ES.UTF-8', 'C.UTF-8', 'en_US.UTF-8', 'UTF-8');
            mb_internal_encoding('UTF-8');

            $conn->begin_transaction();
            try {
                while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                    if ($row_number === 1) { 
                        // ... (Lógica de validación y mapeo de cabecera - SIN CAMBIOS, como la tenías antes) ...
                        $temp_header_csv = $data;
                        if (isset($temp_header_csv[0]) && strpos($temp_header_csv[0], "\xEF\xBB\xBF") === 0) { $temp_header_csv[0] = substr($temp_header_csv[0], 3); }
                        $csv_header_processed = array_map('strtolower', array_map('trim', $temp_header_csv));
                        $expected_header_lower = array_map('strtolower', $expected_header);
                        $missing_cols = [];
                        foreach($expected_header_lower as $expected_col) { if (!in_array($expected_col, $csv_header_processed)) $missing_cols[] = $expected_col; }
                        if (!empty($missing_cols)) throw new Exception("Cabecera del CSV inválida. Faltan: '" . implode("', '", $missing_cols) . "'. Esperadas: '" . implode(', ', $expected_header) . "'. Encontrada: '".implode(', ', $data)."'.");
                        foreach ($expected_header_lower as $col_name_expected) { $header_map[$col_name_expected] = array_search($col_name_expected, $csv_header_processed); }
                        $header_validated = true; $row_number++; continue;
                    }

                    if (!$header_validated) throw new Exception("Cabecera no validada.");
                    
                    $codigo = trim($data[$header_map['codigo']] ?? '');
                    $nombre_completo = trim($data[$header_map['nombre_completo']] ?? '');
                    $username = trim($data[$header_map['username']] ?? '');
                    $email_csv = trim($data[$header_map['email']] ?? '');

                    if (empty($codigo) || empty($nombre_completo) || empty($username)) {
                        $errors_details[] = "Fila {$row_number}: Faltan datos (código, nombre, username). Se omite.";
                        $error_count++; $row_number++; continue;
                    }
                    
                    $email_a_guardar = null;
                    if (!empty($email_csv)) {
                        $emails_array = explode(';', $email_csv); $emails_validos_para_guardar = [];
                        foreach ($emails_array as $e_single) {
                            $e_limpio = trim($e_single);
                            if (filter_var($e_limpio, FILTER_VALIDATE_EMAIL)) $emails_validos_para_guardar[] = $e_limpio;
                            elseif(!empty($e_limpio)) $errors_details[] = "Fila {$row_number}: Email inválido omitido '".htmlspecialchars($e_limpio)."' para ".htmlspecialchars($username).".";
                        }
                        if (!empty($emails_validos_para_guardar)) $email_a_guardar = implode(';', $emails_validos_para_guardar);
                    }

                    // Verificar si el usuario ya existe (por username O employee_id)
                    $existing_user_id = null;
                    $stmt_check = $conn->prepare("SELECT id FROM user WHERE username = ? OR employee_id = ?");
                    if(!$stmt_check) throw new Exception("Error preparando verificación de usuario: ".$conn->error);
                    $stmt_check->bind_param("ss", $username, $codigo);
                    $stmt_check->execute();
                    $result_check = $stmt_check->get_result();
                    if($user_row = $result_check->fetch_assoc()) $existing_user_id = $user_row['id'];
                    $stmt_check->close();

                    $process_status_detail = '';
                    $generated_password_for_report = null;

                    if ($existing_user_id) { // Usuario ya existe
                        if ($update_existing_users) {
                            // Actualizar nombre_completo y email. NO la contraseña.
                            // Supervisores no pueden cambiar roles.
                            $sql_update = "UPDATE user SET full_name = ?, email = ? WHERE id = ?";
                            $stmt_update = $conn->prepare($sql_update);
                            if ($stmt_update) {
                                $stmt_update->bind_param("ssi", $nombre_completo, $email_a_guardar, $existing_user_id);
                                if ($stmt_update->execute()) {
                                    $updated_count++;
                                    $process_status_detail = 'Actualizado';
                                } else {
                                    $errors_details[] = "Fila {$row_number}: Error DB al actualizar usuario existente ".htmlspecialchars($username).": " . $stmt_update->error;
                                    $error_count++;
                                    $process_status_detail = 'Error al actualizar';
                                }
                                $stmt_update->close();
                            } else {
                                 $errors_details[] = "Fila {$row_number}: Error preparando UPDATE para ".htmlspecialchars($username).": ".$conn->error;
                                 $error_count++;
                                 $process_status_detail = 'Error preparando act.';
                            }
                        } else { // No actualizar, solo omitir
                            $skipped_count++;
                            $process_status_detail = 'Omitido (ya existe)';
                        }
                         $users_processed_details[] = [
                            'username' => $username, 'full_name' => $nombre_completo,
                            'employee_id' => $codigo, 'email' => $email_a_guardar ?? 'N/A',
                            'generated_password' => 'N/A (Existente)',
                            'process_status' => $process_status_detail
                        ];
                    } else { // Nuevo usuario
                        $generated_password_plain = generarPasswordSeguro(12);
                        $hashed_password = password_hash($generated_password_plain, PASSWORD_DEFAULT);
                        $force_password_change = 1; 
                        $is_admin_val = 0; 
                        $is_supervisor_val = 0;

                        if ($hashed_password === false) {
                            $errors_details[] = "Fila {$row_number}: Error al hashear password para ".htmlspecialchars($username).". Se omite.";
                            $error_count++; $row_number++; continue;
                        }

                        $sql_insert = "INSERT INTO user (employee_id, full_name, username, password_hash, email, is_admin, is_supervisor, force_password_change) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
                        $stmt_insert = $conn->prepare($sql_insert);
                        if ($stmt_insert) {
                            $stmt_insert->bind_param("sssssiii", $codigo, $nombre_completo, $username, $hashed_password, $email_a_guardar, $is_admin_val, $is_supervisor_val, $force_password_change);
                            if ($stmt_insert->execute()) {
                                $success_count++;
                                $process_status_detail = 'Creado';
                                $generated_password_for_report = $generated_password_plain;
                            } else {
                                // Error específico para duplicados si el INSERT falla por eso (aunque ya lo verificamos antes)
                                $db_error_msg = ($stmt_insert->errno == 1062) ? "Username o ID Empleado ya existe (error en INSERT)." : htmlspecialchars($stmt_insert->error);
                                $errors_details[] = "Fila {$row_number}: Error DB (" . $stmt_insert->errno . ") " . $db_error_msg . " (Usuario: ".htmlspecialchars($username).").";
                                $error_count++;
                                $process_status_detail = 'Error al crear';
                            }
                            $stmt_insert->close();
                        } else {
                            $errors_details[] = "Fila {$row_number}: Error preparando INSERT para ".htmlspecialchars($username).": ".$conn->error;
                            $error_count++;
                            $process_status_detail = 'Error preparando ins.';
                        }
                        $users_processed_details[] = [
                            'username' => $username, 'full_name' => $nombre_completo,
                            'employee_id' => $codigo, 'email' => $email_a_guardar ?? 'N/A',
                            'generated_password' => $generated_password_for_report,
                            'process_status' => $process_status_detail
                        ];
                    }
                    $row_number++;
                } 
                fclose($handle);

                // Decidir transacción general
                if ($error_count > 0 && ($success_count + $updated_count) == 0) { 
                    $conn->rollback();
                    $_SESSION['sv_bulk_upload_error_message_display'] = "Proceso con errores críticos. No se importó ni actualizó ningún usuario. Ver detalles.";
                } elseif ($error_count > 0) { 
                     $conn->commit();
                     $_SESSION['sv_bulk_upload_message_display'] = "Carga parcialmente completada. " 
                        . ($success_count > 0 ? "{$success_count} usuarios creados. " : "")
                        . ($updated_count > 0 ? "{$updated_count} usuarios actualizados. " : "")
                        . "{$error_count} filas tuvieron errores. "
                        . ($skipped_count > 0 ? "{$skipped_count} usuarios existentes fueron omitidos. " : "");
                } elseif (($success_count + $updated_count) > 0 || $skipped_count > 0) { 
                    $conn->commit();
                    $_SESSION['sv_bulk_upload_message_display'] = "¡Carga completada! "
                        . ($success_count > 0 ? "{$success_count} usuarios creados. " : "")
                        . ($updated_count > 0 ? "{$updated_count} usuarios actualizados. " : "")
                        . ($skipped_count > 0 ? "{$skipped_count} usuarios existentes fueron omitidos. " : "");
                     if ($success_count == 0 && $updated_count == 0 && $skipped_count > 0) { // Si solo se omitieron
                        $_SESSION['sv_bulk_upload_info_message_display'] = "Todos los usuarios del archivo ya existían y fueron omitidos.";
                        $_SESSION['sv_bulk_upload_message_display'] = null; // No mostrar mensaje de "éxito"
                     }
                } else { 
                     $conn->rollback(); 
                     $_SESSION['sv_bulk_upload_info_message_display'] = "El archivo CSV estaba vacío, solo contenía la cabecera, o no se procesaron filas válidas.";
                }
            } catch (Exception $e) {
                $conn->rollback();
                $_SESSION['sv_bulk_upload_error_message_display'] = "Error crítico durante el proceso: " . $e->getMessage();
                if (isset($handle) && is_resource($handle)) fclose($handle);
                error_log("Error en carga masiva SUPERVISOR: " . $e->getMessage());
            }
        } else {
            $_SESSION['sv_bulk_upload_error_message_display'] = "No se pudo abrir el archivo CSV subido para lectura.";
        }
        
        $_SESSION['sv_bulk_upload_summary_display'] = $users_processed_details;
        $_SESSION['sv_bulk_upload_errors_details_display'] = $errors_details;
        $_SESSION['sv_bulk_upload_success_count_display'] = $success_count;
        $_SESSION['sv_bulk_upload_updated_count_display'] = $updated_count;
        $_SESSION['sv_bulk_upload_skipped_count_display'] = $skipped_count;
        $_SESSION['sv_bulk_upload_error_count_display'] = $error_count;

        if (!empty($users_processed_details)) { // Guardar para descarga CSV solo si hay algo que mostrar en el resumen
            $_SESSION['bulk_upload_summary_data_sv'] = $users_processed_details; 
        }
    }
    if (isset($conn) && $conn instanceof mysqli) $conn->close();
    header("Location: bulk_upload_supervisor.php"); // Redirigir a la página del formulario
    exit;
} else { 
    // Si no es POST o no hay archivo, y se accede directamente a process_bulk_supervisor.php
    $_SESSION['sv_bulk_upload_error_message_display'] = "Acceso inválido al script de procesamiento.";
    header("Location: bulk_upload_supervisor.php");
    exit;
}
?>