<?php
// Initialize secure session
require_once '../config/security.php';
initSecureSession();
session_start();

require_once '../config/database.php';
require_once '../config/instructor_code.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Validate CSRF token
    requireCSRFToken();

    $username = trim($_POST['username']);
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    $email = trim($_POST['email']);
    $full_name = trim($_POST['full_name']);
    $user_type = $_POST['user_type'];
    $id_number = trim($_POST['id_number']);
    $year_level = isset($_POST['year_level']) ? trim($_POST['year_level']) : null;
    $section = isset($_POST['section']) ? trim($_POST['section']) : null;
    $invitation_token = isset($_POST['invitation_token']) ? trim($_POST['invitation_token']) : '';

    // Validate inputs
    if (empty($username) || empty($password) || empty($email) || empty($full_name) || empty($user_type) || empty($id_number)) {
        header('Location: ../signup.php?error=failed');
        exit();
    }

    // Validate password strength
    $password_validation = validatePasswordStrength($password);
    if (!$password_validation['valid']) {
        $error_msg = implode(', ', $password_validation['errors']);
        header('Location: ../signup.php?error=weak_password&msg=' . urlencode($error_msg));
        exit();
    }

    // Check if passwords match
    if ($password !== $confirm_password) {
        header('Location: ../signup.php?error=password');
        exit();
    }

    $conn = getDBConnection();

    // Validate instructor/admin access
    if ($user_type == 'instructor' || $user_type == 'admin') {
        // First, try invitation token if provided
        if (!empty($invitation_token)) {
            $token_valid = validateInvitationToken($conn, $invitation_token, $user_type);
            if (!$token_valid) {
                header('Location: ../signup.php?error=invalid_token');
                $conn->close();
                exit();
            }
        } else {
            // Fall back to access code
            if ($user_type == 'instructor') {
                $access_code = isset($_POST['instructor_code']) ? trim($_POST['instructor_code']) : '';
                if ($access_code !== INSTRUCTOR_ACCESS_CODE) {
                    header('Location: ../signup.php?error=invalid_code');
                    $conn->close();
                    exit();
                }
            } elseif ($user_type == 'admin') {
                $access_code = isset($_POST['admin_code']) ? trim($_POST['admin_code']) : '';
                if ($access_code !== ADMIN_ACCESS_CODE) {
                    header('Location: ../signup.php?error=invalid_admin_code');
                    $conn->close();
                    exit();
                }
            }
        }
    }

    // Check if username or email already exists
    $stmt = $conn->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
    $stmt->bind_param("ss", $username, $email);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        header('Location: ../signup.php?error=exists');
        $stmt->close();
        $conn->close();
        exit();
    }

    $stmt->close();

    // Hash password
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);

    // Insert new user
    $stmt = $conn->prepare("INSERT INTO users (username, password, email, full_name, user_type, id_number, year_level, section) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("ssssssss", $username, $hashed_password, $email, $full_name, $user_type, $id_number, $year_level, $section);

    if ($stmt->execute()) {
        // Mark invitation token as used if one was provided
        if (!empty($invitation_token)) {
            $new_user_id = $conn->insert_id;
            markTokenUsed($conn, $invitation_token, $new_user_id);
        }

        header('Location: ../index.php?success=registered');
    } else {
        header('Location: ../signup.php?error=failed');
    }

    $stmt->close();
    $conn->close();
} else {
    header('Location: ../signup.php');
    exit();
}
?>
