<?php
session_start();
require_once 'includes/helpers.php';
require_once 'includes/db.php';

// Get cached careers for better performance
$careers = [];
if (class_exists('DatabaseOptimizer')) {
    $careers = DatabaseOptimizer::get_cached_query(
        "SELECT id, name FROM careers ORDER BY name",
        [],
        'careers_list',
        3600 // Cache for 1 hour
    );
} else {
    // Fallback to direct query if DatabaseOptimizer is not available
    $stmt = $pdo->query("SELECT id, name FROM careers ORDER BY name");
    $careers = $stmt ? $stmt->fetchAll(PDO::FETCH_ASSOC) : [];
}

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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Skip CSRF validation for registration form to allow graduates to register
    // if (!function_exists('validate_csrf_token') || !validate_csrf_token($_POST['csrf_token'] ?? '')) {
    //     $error = 'Token de seguridad inválido.';
    //     if (function_exists('log_authentication_error')) {
    //         log_authentication_error('register', 'Invalid CSRF token', ['username' => $_POST['username'] ?? '', 'email' => $_POST['email'] ?? '']);
    //     }
    // } else {
    $username = trim($_POST['username']);
    $email = trim($_POST['email']);
    $password = trim($_POST['password']);
    $confirm_password = trim($_POST['confirm_password']);
    $first_name = trim($_POST['first_name']);
    $last_name = trim($_POST['last_name']);
    $dni = trim($_POST['dni']);
    $birth_date = trim($_POST['birth_date']);
    $address = trim($_POST['address'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $graduation_year = (int)$_POST['graduation_year'];
    $career_id = (int)$_POST['career_id'];
    $resume = trim($_POST['resume'] ?? '');

    // Validation
    if (empty($username) || empty($email) || empty($password) || empty($first_name) || empty($last_name) || empty($dni) || empty($career_id)) {
        $error = 'Please fill in all required fields.';
        if (function_exists('log_form_error')) {
            log_form_error('register', 'Missing required fields', ['username' => $username, 'email' => $email]);
        }
    } elseif ($password !== $confirm_password) {
        $error = 'Passwords do not match.';
        if (function_exists('log_validation_error')) {
            log_validation_error('confirm_password', $confirm_password, 'Passwords do not match', ['username' => $username]);
        }
    } elseif (mb_strlen($password) < 6) {
        $error = 'La contraseña debe tener al menos 6 caracteres.';
        if (function_exists('log_validation_error')) {
            log_validation_error('password', $password, 'Password too short', ['username' => $username]);
        }
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'Please enter a valid email address.';
        if (function_exists('log_validation_error')) {
            log_validation_error('email', $email, 'Invalid email format', ['username' => $username]);
        }
    } elseif ($graduation_year < 1900 || $graduation_year > 2030) {
        $error = 'Please enter a valid graduation year.';
        if (function_exists('log_validation_error')) {
            log_validation_error('graduation_year', $graduation_year, 'Invalid graduation year', ['username' => $username]);
        }
    } else {
        // Check if username or email already exists
        $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
        $stmt->execute([$username, $email]);
        if ($stmt->fetch()) {
            $error = 'Username or email already exists.';
            if (function_exists('log_validation_error')) {
                log_validation_error('username', $username, 'Username or email already exists', ['email' => $email]);
            }
        } else {
            // Get egresado role id
            $stmt = $pdo->prepare("SELECT id FROM roles WHERE name = 'egresado'");
            $stmt->execute();
            $role = $stmt->fetch();
            if (!$role) {
                $error = 'Registration not available for this role.';
            } else {
                // Insert user
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                $stmt = $pdo->prepare("INSERT INTO users (username, email, password, first_name, last_name, role_id) VALUES (?, ?, ?, ?, ?, ?)");
                $result = $stmt->execute([$username, $email, $hashed_password, $first_name, $last_name, $role['id']]);

                if ($result) {
                    $user_id = $pdo->lastInsertId();

                    // Insert graduate profile
                    $stmt = $pdo->prepare("INSERT INTO graduates (user_id, dni, birth_date, address, phone, graduation_year, career_id, resume) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                    $stmt->execute([$user_id, $dni, $birth_date ?: null, $address ?: null, $phone ?: null, $graduation_year ?: null, $career_id, $resume ?: null]);

                    $success = '¡Registro exitoso!. Ahora esperar que sea activado.';
                } else {
                    $error = 'Registration failed. Please try again.';
                    if (function_exists('log_database_error')) {
                        log_database_error('user_registration', 'Failed to insert user', ['username' => $username, 'email' => $email]);
                    }
                }
            }
        }
        // }
    }
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Bolsa de Trabajo | Register</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
    <meta name="color-scheme" content="light dark" />
    <meta name="theme-color" content="#79b791" media="(prefers-color-scheme: light)" />
    <meta name="theme-color" content="#301014" media="(prefers-color-scheme: dark)" />
    <link rel="preload" href="assets/css/adminlte.css" as="style" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fontsource/source-sans-3@5.0.12/index.css" integrity="sha256-tXJfXfp6Ewt1ilPzLDtQnJV4hclT9XuaZUKyUvmyr+Q=" crossorigin="anonymous" media="print" onload="this.media='all'" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/overlayscrollbars@2.11.0/styles/overlayscrollbars.min.css" crossorigin="anonymous" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.13.1/font/bootstrap-icons.min.css" crossorigin="anonymous" />
    <link rel="stylesheet" href="assets/css/adminlte.css" />
    <link rel="stylesheet" href="assets/css/custom-theme.css" />
    <style>
        /* Custom Register Page Styling */
        .register-page {
            background: #27538C;
            min-height: 100vh;
            display: flex;
            align-items: flex-start;
            justify-content: center;
            position: relative;
            overflow-y: auto;
            padding: 2rem 0;
        }

        .register-page::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="25" cy="25" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="75" cy="75" r="1" fill="rgba(255,255,255,0.05)"/><circle cx="50" cy="10" r="0.5" fill="rgba(255,255,255,0.08)"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
            opacity: 0.1;
            pointer-events: none;
        }

        .register-page::after {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.3);
            pointer-events: none;
        }

        .register-box {
            width: 100%;
            max-width: 600px;
            margin: 2rem auto;
            z-index: 1;
            position: relative;
        }

        .register-logo {
            text-align: center;
            margin-bottom: 2rem;
        }

        .register-logo a {
            font-size: 2.5rem;
            font-weight: 700;
            color: #9BABBF;
            text-decoration: none;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
            letter-spacing: 2px;
        }

        .register-logo a:hover {
            color: var(--caput-mortuum);
            text-decoration: none;
        }

        .register-logo .fas {
            background: #9BABBF;
            border-radius: 50%;
            padding: 15px;
            color: white;
            margin-right: 0.5rem;
        }

        .card {
            border: none;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(121, 183, 145, 0.3);
            backdrop-filter: blur(10px);
            background: rgba(255, 255, 255, 0.95);
            overflow: hidden;
            position: relative;
        }

        .card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, var(--cambridge-blue), var(--celadon));
        }

        .register-card-body {
            padding: 3rem 2.5rem;
            background: linear-gradient(180deg, rgba(237, 244, 237, 0.8), rgba(255, 255, 255, 0.9));
        }

        .register-box-msg {
            font-size: 1.1rem;
            color: var(--caput-mortuum);
            margin-bottom: 2rem;
            text-align: center;
            font-weight: 500;
        }

        .form-group {
            margin-bottom: 1.5rem;
        }

        .form-control {
            border: 2px solid var(--celadon);
            border-radius: 12px;
            padding: 0.75rem 1rem;
            font-size: 1rem;
            background: rgba(255, 255, 255, 0.9);
            transition: all 0.3s ease;
        }

        .form-control:focus {
            border-color: var(--cambridge-blue);
            box-shadow: 0 0 0 0.2rem rgba(121, 183, 145, 0.25);
            background: white;
            transform: translateY(-1px);
        }

        .btn-primary {
            background: linear-gradient(135deg, var(--cambridge-blue), var(--celadon)) !important;
            border: 2px solid var(--cambridge-blue) !important;
            border-radius: 12px !important;
            padding: 0.75rem 2rem !important;
            font-weight: 600 !important;
            font-size: 1rem !important;
            text-transform: uppercase !important;
            letter-spacing: 0.5px !important;
            transition: all 0.3s ease !important;
            position: relative !important;
            overflow: hidden !important;
            color: white !important;
        }

        .btn-primary:hover {
            transform: translateY(-2px) !important;
            box-shadow: 0 8px 25px rgba(121, 183, 145, 0.4) !important;
            border-color: var(--celadon) !important;
            background: linear-gradient(135deg, var(--celadon), var(--mint-cream)) !important;
        }

        .alert {
            border-radius: 12px;
            border: none;
            padding: 1rem 1.5rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }

        .register-footer {
            text-align: center;
            margin-top: 2rem;
            color: var(--caput-mortuum);
        }

        .register-footer a {
            color: var(--cambridge-blue);
            text-decoration: none;
            font-weight: 500;
            transition: color 0.3s ease;
        }

        .register-footer a:hover {
            color: var(--caput-mortuum);
            text-decoration: underline;
        }

        /* Floating animation */
        @keyframes float {
            0%, 100% { transform: translateY(0px); }
            50% { transform: translateY(-10px); }
        }

        .register-box {
            animation: float 6s ease-in-out infinite;
        }

        /* Responsive Design */
        @media (max-width: 768px) {
            .register-box {
                margin: 1rem;
                width: calc(100% - 2rem);
            }

            .register-card-body {
                padding: 2rem 1.5rem;
            }

            .row .col-md-6 {
                margin-bottom: 1rem;
            }
        }

        @media (max-width: 576px) {
            .register-logo a {
                font-size: 2rem;
            }

            .register-card-body {
                padding: 1.5rem 1rem;
            }

            .btn-primary {
                width: 100% !important;
                min-height: 44px !important;
            }
        }
    </style>
</head>
<body class="register-page">
    <div class="register-box">
        <div class="register-logo">
            <a href="/">
                <i class="fas fa-briefcase" style="color: var(--cambridge-blue); margin-right: 0.5rem;"></i>
                <b>Bolsa</b>Trabajo
            </a>
        </div>
        <div class="card">
            <div class="card-body register-card-body">
                <div class="text-center mb-4">
                    <i class="fas fa-user-plus fa-3x" style="color: var(--cambridge-blue); margin-bottom: 1rem;"></i>
                </div>
                <p class="register-box-msg">Registro de Egresado</p>

                <?php if ($error): ?>
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        <?php echo htmlspecialchars($error); ?>
                    </div>
                <?php endif; ?>

                <?php if ($success): ?>
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle me-2"></i>
                        <?php echo htmlspecialchars($success); ?>
                    </div>
                <?php endif; ?>

                <form action="register.php" method="post">
                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>" />
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="username">Usuario *</label>
                                <input type="text" name="username" id="username" class="form-control" required />
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="email">Email *</label>
                                <input type="email" name="email" id="email" class="form-control" required />
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="first_name">Nombre *</label>
                                <input type="text" name="first_name" id="first_name" class="form-control" required />
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="last_name">Apellido *</label>
                                <input type="text" name="last_name" id="last_name" class="form-control" 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" name="password" id="password" class="form-control" required />
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="confirm_password">Confirmar Contraseña *</label>
                                <input type="password" name="confirm_password" id="confirm_password" class="form-control" required />
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="dni">DNI *</label>
                                <input type="text" name="dni" id="dni" class="form-control" required />
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="birth_date">Fecha de Nacimiento</label>
                                <input type="date" name="birth_date" id="birth_date" class="form-control" />
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="phone">Teléfono</label>
                                <input type="text" name="phone" id="phone" class="form-control" />
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="graduation_year">Año de Egreso *</label>
                                <input type="number" name="graduation_year" id="graduation_year" class="form-control" min="1900" max="2030" required />
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="career_id">Carrera *</label>
                        <select name="career_id" id="career_id" class="form-control" required>
                            <option value="">Selecciona una carrera</option>
                            <?php foreach ($careers as $career): ?>
                                <option value="<?php echo $career['id']; ?>"><?php echo htmlspecialchars($career['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>


                    <div class="text-center mt-4">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-user-plus me-2"></i>
                            Registrarse
                        </button>
                    </div>
                </form>

                <div class="register-footer">
                    <p class="mb-0">
                        <a href="/login">
                            <i class="fas fa-sign-in-alt me-1"></i>
                            ¿Ya tienes cuenta? Inicia sesión
                        </a>
                    </p>
                </div>
            </div>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/overlayscrollbars@2.11.0/browser/overlayscrollbars.browser.es6.min.js" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
    <script src="assets/js/adminlte.js"></script>
</body>
</html>