
<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/../includes/helpers.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

check_role('administrador');

$user = get_logged_in_user();

$error = '';
$success = '';
$csrf_token = get_csrf_token();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (!validate_csrf_token($_POST['csrf_token'] ?? '')) {
        $error = 'Token de seguridad inválido.';
    } else {
    $username = trim($_POST['username']);
    $email = trim($_POST['email']);
    $password = $_POST['password'];
    $role_id = $_POST['role_id'];
    $first_name = trim($_POST['first_name']);
    $last_name = trim($_POST['last_name']);

    // Handle photo upload
    $photo_path = null;
    if (isset($_FILES['photo']) && $_FILES['photo']['error'] == 0) {
        $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
        $max_size = 2 * 1024 * 1024; // 2MB

        if (!in_array($_FILES['photo']['type'], $allowed_types)) {
            $error = 'Invalid file type. Only JPG, PNG, and GIF are allowed.';
        } elseif ($_FILES['photo']['size'] > $max_size) {
            $error = 'File too large. Maximum size is 2MB.';
        } else {
            $upload_dir = '../uploads/photos/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }

            $file_extension = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
            $file_name = uniqid('user_') . '.' . $file_extension;
            $file_path = $upload_dir . $file_name;

            if (move_uploaded_file($_FILES['photo']['tmp_name'], $file_path)) {
                $photo_path = 'uploads/photos/' . $file_name;
            } else {
                // Try alternative approach - copy file instead of move
                if (copy($_FILES['photo']['tmp_name'], $file_path)) {
                    $photo_path = 'uploads/photos/' . $file_name;
                } else {
                    $error = 'Failed to upload photo. Directory permissions issue. Please run: chmod -R 777 uploads/ or contact system administrator.';
                }
            }
        }
    }

    if (empty($username) || empty($email) || empty($password) || empty($role_id)) {
        $error = 'Por favor, rellene todos los campos obligatorios.';
    }

    if (!$error) {
        // Check if username or email exists
        $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
        $stmt->execute([$username, $email]);
        if ($stmt->fetch()) {
            $error = 'El nombre de usuario o correo electrónico ya existe.';
        } else {
            // Insert user
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("INSERT INTO users (username, password, email, role_id, first_name, last_name, photo) VALUES (?, ?, ?, ?, ?, ?, ?)");
            if ($stmt->execute([$username, $hashed_password, $email, $role_id, $first_name, $last_name, $photo_path])) {
                $user_id = $pdo->lastInsertId();

                // Log user creation
                audit_user_creation([
                    'id' => $user_id,
                    'username' => $username,
                    'email' => $email,
                    'role_id' => $role_id,
                    'first_name' => $first_name,
                    'last_name' => $last_name
                ]);

                // Handle file upload for logo
                $logo_path = null;
                if (isset($_FILES['logo']) && $_FILES['logo']['error'] == 0) {
                    $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
                    if (in_array($_FILES['logo']['type'], $allowed_types)) {
                        $ext = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
                        $filename = 'company_' . $user_id . '_' . time() . '.' . $ext;
                        $upload_path = '../uploads/logos/' . $filename;
                        if (move_uploaded_file($_FILES['logo']['tmp_name'], $upload_path)) {
                            $logo_path = 'uploads/logos/' . $filename;
                        }
                    }
                }

                // Insert into specific table based on role
                $role_stmt = $pdo->prepare("SELECT name FROM roles WHERE id = ?");
                $role_stmt->execute([$role_id]);
                $role_name = $role_stmt->fetch()['name'];
                switch ($role_name) {
                    case 'empresa':
                        $stmt = $pdo->prepare("INSERT INTO companies (user_id, company_name, logo) VALUES (?, ?, ?)");
                        $stmt->execute([$user_id, $_POST['company_name'] ?? '', $logo_path]);
                        break;
                    case 'alumno':
                        $career_id = !empty($_POST['career_id']) ? $_POST['career_id'] : null;
                        $graduation_year = !empty($_POST['graduation_year']) ? $_POST['graduation_year'] : null;


                        $stmt = $pdo->prepare("INSERT INTO students (user_id, career_id, graduation_year, resume) VALUES (?, ?, ?, ?)");
                        $stmt->execute([$user_id, $career_id, $graduation_year, $_POST['resume'] ?? '']);
                        break;
                    case 'egresado':
                        $career_id = !empty($_POST['career_id']) ? $_POST['career_id'] : null;
                        $graduation_year = !empty($_POST['graduation_year']) ? $_POST['graduation_year'] : null;
                        try {
                            $stmt = $pdo->prepare("INSERT INTO graduates (user_id, career_id, dni, birth_date, address, phone, graduation_year, resume) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                            $stmt->execute([$user_id, $career_id, $_POST['dni'] ?? null, $_POST['birth_date'] ?? null, $_POST['address'] ?? null, $_POST['phone'] ?? null, $graduation_year, $_POST['resume'] ?? '']);
                        } catch (PDOException $e) {
                            // If columns don't exist yet, insert only the existing columns
                            if (strpos($e->getMessage(), 'Unknown column') !== false) {
                                $stmt = $pdo->prepare("INSERT INTO graduates (user_id, career_id, graduation_year, resume) VALUES (?, ?, ?, ?)");
                                $stmt->execute([$user_id, $career_id, $graduation_year, $_POST['resume'] ?? '']);
                            } else {
                                throw $e; // Re-throw if it's a different error
                            }
                        }
                        break;
                    case 'profesor':
                        $career_id = !empty($_POST['career_id']) ? $_POST['career_id'] : null;
                        $stmt = $pdo->prepare("INSERT INTO teachers (user_id, career_id, dni, birth_date, address, phone, bio) VALUES (?, ?, ?, ?, ?, ?, ?)");
                        $stmt->execute([
                            $user_id,
                            $career_id,
                            $_POST['teacher_dni'] ?? null,
                            $_POST['teacher_birth_date'] ?? null,
                            $_POST['teacher_address'] ?? null,
                            $_POST['teacher_phone'] ?? null,
                            $_POST['teacher_bio'] ?? null
                        ]);
                        break;
                }
                $success = 'Usuario agregado exitosamente.';
            } else {
                $error = 'No se pudo agregar el usuario.';
            }
            }
        }
        }
    }

// Get cached roles and careers for better performance
$roles = get_roles_cached();
$careers = get_careers_cached();

// Build role options
$role_options = '<option value="">Select Role</option>';
foreach ($roles as $role) {
    $role_options .= '<option value="' . $role['id'] . '" data-name="' . $role['name'] . '">' . ucfirst($role['name']) . '</option>';
}

// Build career options
$student_career_options = '<option value="">Seleccionar programa</option>';
foreach ($careers as $career) {
    $student_career_options .= '<option value="' . $career['id'] . '">' . htmlspecialchars($career['name']) . '</option>';
}
$graduate_career_options = $student_career_options;
$teacher_career_options = '<option value="">Select Career</option>';
foreach ($careers as $career) {
    $teacher_career_options .= '<option value="' . $career['id'] . '">' . htmlspecialchars($career['name']) . '</option>';
}

$page_title = 'Agregar Usuario';

$error_alert = $error ? '<div class="alert alert-danger">' . htmlspecialchars($error) . '</div>' : '';
$success_alert = $success ? '<div class="alert alert-success">' . htmlspecialchars($success) . '</div>' : '';

$cancel_url = route_url('admin_users');

$content = <<<HTML
<div class="row">
    <div class="col-md-6">
        <div class="card card-primary">
            <div class="card-header">
                <h3 class="card-title" id="form-title">Agregar nuevo usuario</h3>
            </div>
            <form method="post" enctype="multipart/form-data">
                <input type="hidden" name="csrf_token" value="{$csrf_token}" />
                <div class="card-body">
                    {$error_alert}
                    {$success_alert}
                    <div class="form-group">
                        <label for="username">Username</label>
                        <input type="text" class="form-control" id="username" name="username" required>
                    </div>
                    <div class="form-group">
                        <label for="email">Email</label>
                        <input type="email" class="form-control" id="email" name="email" required>
                    </div>
                    <div class="form-group">
                        <label for="password">Password</label>
                        <input type="password" class="form-control" id="password" name="password" required>
                    </div>
                    <div class="form-group">
                        <label for="first_name">Nombres</label>
                        <input type="text" class="form-control" id="first_name" name="first_name">
                    </div>
                    <div class="form-group">
                        <label for="last_name">Apellidos</label>
                        <input type="text" class="form-control" id="last_name" name="last_name">
                    </div>
                    <div class="form-group">
                        <label for="photo">Foto</label>
                        <input type="file" class="form-control" id="photo" name="photo" accept="image/*">
                    </div>
                    <div class="form-group">
                        <label for="role_id">Role</label>
                        <select class="form-control" id="role_id" name="role_id" required>
                            {$role_options}
                        </select>
                    </div>
                    <div class="form-group" id="company_fields" style="display:none;">
                        <label for="company_name">Nombre de la Empresa</label>
                        <input type="text" class="form-control" id="company_name" name="company_name">
                        <label for="logo">Logo</label>
                        <input type="file" class="form-control" id="logo" name="logo" accept="image/*">
                    </div>
                    <div class="form-group" id="student_fields" style="display:none;">
                        <label for="career_id">Programa de Estudio</label>
                        <select class="form-control" id="career_id" name="career_id">
                            {$student_career_options}
                        </select>
                        <label for="graduation_year">Año de graduación esperador</label>
                        <input type="number" class="form-control" id="graduation_year" name="graduation_year" min="2020" max="2030" placeholder="e.g., 2025">
                        <label for="resume">Resume/CV</label>
                        <textarea class="form-control" id="resume" name="resume" rows="3" placeholder="Student\'s academic background, achievements, etc."></textarea>
                    </div>
                    <div class="form-group" id="graduate_fields" style="display:none;">
                        <label for="career_id">Programa de Estudio</label>
                        <select class="form-control" id="graduate_career_id" name="career_id">
                            {$graduate_career_options}
                        </select>
                        <label for="dni">DNI</label>
                        <input type="text" class="form-control" id="graduate_dni" name="dni" placeholder="Número de DNI">
                        <label for="birth_date">Fecha de Nacimiento</label>
                        <input type="date" class="form-control" id="graduate_birth_date" name="birth_date">
                        <label for="address">Dirección</label>
                        <textarea class="form-control" id="graduate_address" name="address" rows="2" placeholder="Dirección completa"></textarea>
                        <label for="phone">Teléfono</label>
                        <input type="tel" class="form-control" id="graduate_phone" name="phone" placeholder="Número de teléfono">
                        <label for="graduation_year">Año de Egreso</label>
                        <input type="number" class="form-control" id="graduate_graduation_year" name="graduation_year" min="1950" max="' . date('Y') . '" placeholder="e.g., 2023">
                        <label for="resume">Resumen/CV</label>
                        <textarea class="form-control" id="graduate_resume" name="resume" rows="3" placeholder="Professional background, achievements, etc."></textarea>
                    </div>
                    <div class="form-group" id="teacher_fields" style="display:none;">
                        <label for="teacher_career_id">Programa de Estudio</label>
                        <select class="form-control" id="teacher_career_id" name="career_id">
                            {$teacher_career_options}
                        </select>
                        <label for="teacher_dni">DNI</label>
                        <input type="text" class="form-control" id="teacher_dni" name="teacher_dni" placeholder="Número de DNI">
                        <label for="teacher_birth_date">Fecha de Nacimiento</label>
                        <input type="date" class="form-control" id="teacher_birth_date" name="teacher_birth_date">
                        <label for="teacher_address">Dirección</label>
                        <textarea class="form-control" id="teacher_address" name="teacher_address" rows="2" placeholder="Dirección completa"></textarea>
                        <label for="teacher_phone">Teléfono</label>
                        <input type="tel" class="form-control" id="teacher_phone" name="teacher_phone" placeholder="Número de teléfono">
                        <label for="teacher_bio">Bio</label>
                        <textarea class="form-control" id="teacher_bio" name="teacher_bio" rows="3" placeholder="Biografía breve..."></textarea>
                    </div>
                </div>
                <div class="card-footer">
                    <button type="submit" class="btn btn-primary">Agregar usuario</button>
                    <a href="{$cancel_url}" id="cancel-btn" class="btn btn-secondary">Cancelar</a>
                </div>
            </form>
        </div>
    </div>
</div>
HTML;

?>

<?php include '../includes/layout.php'; ?>
?>