<?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'];
        $first_name = trim($_POST['first_name']);
        $last_name = trim($_POST['last_name']);
        $career_id = $_POST['career_id'];
        $dni = trim($_POST['dni']);
        $birth_date = $_POST['birth_date'];
        $address = trim($_POST['address']);
        $phone = trim($_POST['phone']);
        $bio = trim($_POST['bio']);
        $gender = $_POST['gender'];

        // 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($career_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 (?, ?, ?, 5, ?, ?, ?)");
                if ($stmt->execute([$username, $hashed_password, $email, $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' => 5,
                        'first_name' => $first_name,
                        'last_name' => $last_name
                    ]);

                    // Insert into teachers table
                    $stmt = $pdo->prepare("INSERT INTO teachers (user_id, career_id, dni, birth_date, address, phone, bio, gender) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                    $stmt->execute([$user_id, $career_id, $dni, $birth_date, $address, $phone, $bio, $gender]);

                    $success = 'Profesor agregado exitosamente.';
                } else {
                    $error = 'No se pudo agregar el profesor.';
                }
            }
        }
    }
}

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

$page_title = 'Agregar Profesor';

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

$content = <<<HTML
<div class="row">
    <div class="col-md-8">
        <div class="card card-primary">
            <div class="card-header">
                <h3 class="card-title">Agregar nuevo profesor</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="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="username">Nombre de Usuario *</label>
                                <input type="text" class="form-control" id="username" name="username" required>
                                <small class="form-text text-muted">Nombre único para iniciar sesión</small>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="email">Correo Electrónico *</label>
                                <input type="email" class="form-control" id="email" name="email" required>
                                <small class="form-text text-muted">Será usado para notificaciones</small>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="first_name">Nombres *</label>
                                <input type="text" class="form-control" id="first_name" name="first_name" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="last_name">Apellidos *</label>
                                <input type="text" class="form-control" id="last_name" name="last_name" required>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="password">Contraseña *</label>
                                <input type="password" class="form-control" id="password" name="password" required>
                                <small class="form-text text-muted">Mínimo 6 caracteres</small>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="photo">Foto de Perfil</label>
                                <input type="file" class="form-control" id="photo" name="photo" accept="image/*">
                                <small class="form-text text-muted">JPG, PNG, GIF. Máx 2MB</small>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="career_id">Programa de Estudio *</label>
                                <select class="form-control" id="career_id" name="career_id" required>
                                    <option value="">Seleccionar programa</option>
HTML;

foreach ($careers as $career) {
    $content .= '<option value="' . $career['id'] . '">' . htmlspecialchars($career['name']) . '</option>';
}

$content .= <<<HTML
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="dni">DNI</label>
                                <input type="text" class="form-control" id="dni" name="dni" placeholder="Número de DNI">
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="birth_date">Fecha de Nacimiento</label>
                                <input type="date" class="form-control" id="birth_date" name="birth_date">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="phone">Teléfono</label>
                                <input type="tel" class="form-control" id="phone" name="phone" placeholder="Número de teléfono">
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="address">Dirección</label>
                        <input type="text" class="form-control" id="address" name="address" placeholder="Dirección completa">
                    </div>

                    <div class="form-group">
                        <label for="bio">Biografía</label>
                        <textarea class="form-control" id="bio" name="bio" rows="4" placeholder="Biografía breve del profesor..."></textarea>
                        <small class="form-text text-muted">Describe la experiencia y especialización del profesor</small>
                    </div>

                    <div class="form-group">
                        <label for="gender">Género</label>
                        <select class="form-control" id="gender" name="gender">
                            <option value="">Seleccionar género</option>
                            <option value="masculino">Masculino</option>
                            <option value="femenino">Femenino</option>
                            <option value="otro">Otro</option>
                        </select>
                    </div>
                </div>

                <div class="card-footer">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> Agregar Profesor
                    </button>
                    <button type="button" onclick="window.history.back()" class="btn btn-secondary">
                        <i class="fas fa-arrow-left"></i> Volver
                    </button>
                </div>
            </form>
        </div>
    </div>

    <div class="col-md-4">
        <div class="card card-info">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-info-circle"></i> Información
                </h3>
            </div>
            <div class="card-body">
                <h5>Campos Obligatorios</h5>
                <ul class="list-unstyled">
                    <li><i class="fas fa-check text-success"></i> Nombre de usuario</li>
                    <li><i class="fas fa-check text-success"></i> Correo electrónico</li>
                    <li><i class="fas fa-check text-success"></i> Contraseña</li>
                    <li><i class="fas fa-check text-success"></i> Nombres y apellidos</li>
                    <li><i class="fas fa-check text-success"></i> Programa de estudio</li>
                </ul>

                <h5 class="mt-3">Campos Opcionales</h5>
                <ul class="list-unstyled">
                    <li><i class="fas fa-circle text-muted"></i> Foto de perfil</li>
                    <li><i class="fas fa-circle text-muted"></i> DNI</li>
                    <li><i class="fas fa-circle text-muted"></i> Fecha de nacimiento</li>
                    <li><i class="fas fa-circle text-muted"></i> Teléfono</li>
                    <li><i class="fas fa-circle text-muted"></i> Dirección</li>
                    <li><i class="fas fa-circle text-muted"></i> Biografía</li>
                    <li><i class="fas fa-circle text-muted"></i> Género</li>
                </ul>

                <div class="alert alert-warning mt-3">
                    <i class="fas fa-exclamation-triangle"></i>
                    <strong>Nota:</strong> El profesor podrá completar su perfil más tarde desde su panel de profesor.
                </div>
            </div>
        </div>
    </div>
</div>

<script src="<?php echo url('assets/js/add-user.js'); ?>"></script>
<script>
// Additional teacher-specific JavaScript
document.addEventListener('DOMContentLoaded', function() {
    // Enhanced form validation for teacher
    const form = document.querySelector('form');
    form.addEventListener('submit', function(e) {
        const careerId = document.getElementById('career_id').value;

        if (!careerId) {
            e.preventDefault();
            alert('Por favor, seleccione un programa de estudio.');
            document.getElementById('career_id').focus();
            return false;
        }

        return true;
    });

    console.log('Add Teacher JavaScript loaded successfully');
});
</script>
HTML;

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