<?php
// register_student.php
// This page is for an admin/instructor to register new students.
// FIXED: User registration now sends an email with an OTP. The student will use their email as both username and password for the first login, and the OTP for verification.

// Ensure the session is started only once.
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Include necessary files.
require_once 'config/database.php';
require_once 'vendor/autoload.php'; // Path to PHPMailer via Composer
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// --- 1. EMAIL-SENDING FUNCTION ---
// This function sends an email with the OTP.
function sendRegistrationEmail(string $student_email, string $student_name, string $otp): bool {
    try {
        $mail = new PHPMailer(true);
        $mail->isSMTP();
        $mail->Host       = 'smtp.gmail.com'; 
        $mail->SMTPAuth   = true;
        $mail->Username   = 'bazithali95@gmail.com'; 
        $mail->Password   = 'sqkt opow cvao fiac'; 
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; 
        $mail->Port       = 587;
        
        $mail->setFrom('bazithali95@gmail.com', 'Orinsto LMS');
        $mail->addAddress($student_email, $student_name);
        
        $mail->isHTML(true);
        $mail->Subject = "Welcome to Orinsto LMS - Your One-Time Login Code";
        $mail->Body    = "
            <p>Dear " . htmlspecialchars($student_name) . ",</p>
            <p>Welcome to Orinsto LMS! An account has been created for you.</p>
            <p>To complete your first login, please follow these steps:</p>
            <ol>
                <li>Go to the login page.</li>
                <li>Enter your **email address** as both your username and password.</li>
                <li>When prompted, enter the following one-time password (OTP) to verify your identity:</li>
            </ol>
            <p style='text-align: center; font-size: 24px; font-weight: bold; color: #007bff; background-color: #f0f8ff; padding: 20px; border-radius: 5px; margin: 30px 0;'>
                " . htmlspecialchars($otp) . "
            </p>
            <p>This code is for one-time use only. After your first successful login, you will be prompted to set a new, permanent password.</p>
            <p style='margin-top: 30px;'>Thank you,<br>The Orinsto LMS Team</p>
        ";
        $mail->AltBody = "Welcome to Orinsto LMS. Your username is your email address. For your first login, use your email as the password. Your one-time login code (OTP) is: " . htmlspecialchars($otp) . ". You will be prompted to set a new password after you log in.";
        
        $mail->send();
        return true;
    } catch (Exception $e) {
        error_log("Registration email failed for {$student_email}. Mailer Error: {$mail->ErrorInfo}");
        return false;
    }
}
// --- END OF EMAIL-SENDING FUNCTION ---

$message = ''; 
$is_error = false; 
$username = '';
$email = '';
$full_name = '';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = trim($_POST['username'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $full_name = trim($_POST['full_name'] ?? '');
    $role = 'student'; 

    if (empty($username) || empty($email) || empty($full_name)) {
        $message = "Please fill in all required fields.";
        $is_error = true;
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $message = "Invalid email format.";
        $is_error = true;
    } else {
        try {
            $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
            $stmt->execute([$username, $email]); 

            if ($stmt->fetch()) {
                $message = "Username or email already exists. Please choose a different one.";
                $is_error = true;
            } else {
                // --- 2. Use the email as the temporary password and generate an OTP ---
                // The student's email will be used as the initial password
                $initial_password = $email;
                $hashed_password = password_hash($initial_password, PASSWORD_DEFAULT);

                // Generate a strong, random OTP
                $otp = bin2hex(random_bytes(16)); 
                $otp_expiry = date('Y-m-d H:i:s', strtotime('+15 minutes')); // OTP valid for 15 minutes

                $pdo->beginTransaction();

                // Insert the new student into the `users` table
                $stmt = $pdo->prepare("INSERT INTO users (username, password, email, full_name, role, otp, otp_expiry) VALUES (?, ?, ?, ?, ?, ?, ?)");
                
                if (!$stmt->execute([$username, $hashed_password, $email, $full_name, $role, $otp, $otp_expiry])) {
                    throw new Exception("Error inserting student into the database.");
                }

                // --- 3. Send the registration email with the OTP ---
                if (sendRegistrationEmail($email, $full_name, $otp)) {
                    $pdo->commit();
                    $message = "Student '<strong>" . htmlspecialchars($full_name) . "</strong>' registered successfully!<br>" .
                               "An email with a one-time login code has been sent to <strong>" . htmlspecialchars($email) . "</strong>.";
                    $is_error = false; 

                    $username = '';
                    $email = '';
                    $full_name = '';
                } else {
                    throw new Exception("Student registered, but the registration email failed to send.");
                }
            }
        } catch (Exception $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $message = "Error: " . $e->getMessage();
            $is_error = true;
            error_log("Student Registration Error: " . $e->getMessage());
        } catch (PDOException $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $message = "Database error: " . $e->getMessage();
            $is_error = true;
        }
    }
}
?>

<div class="bg-white p-8 rounded-lg shadow-md w-full max-w-lg">
    <h2 class="text-2xl font-bold mb-6 text-center text-gray-800">Register New Student</h2>

    <?php if (!empty($message)): ?>
        <div class="mb-4 p-3 rounded-md text-center
            <?php echo $is_error ? 'bg-red-100 text-red-700' : 'bg-green-100 text-green-700'; ?>">
            <?php echo $message; ?>
        </div>
    <?php endif; ?>

    <form action="index.php?page=register_student" method="POST" class="space-y-4">
        <div>
            <label for="username" class="block text-gray-700 text-sm font-semibold mb-2">Username:</label>
            <input type="text" id="username" name="username" value="<?php echo htmlspecialchars($username); ?>" required
                   class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
        </div>
        <div>
            <label for="email" class="block text-gray-700 text-sm font-semibold mb-2">Email:</label>
            <input type="email" id="email" name="email" value="<?php echo htmlspecialchars($email); ?>" required
                   class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
        </div>
        <div>
            <label for="full_name" class="block text-gray-700 text-sm font-semibold mb-2">Full Name:</label>
            <input type="text" id="full_name" name="full_name" value="<?php echo htmlspecialchars($full_name); ?>" required
                   class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
        </div>
        <button type="submit"
                class="w-full py-2 px-4 bg-blue-600 text-white font-semibold rounded-md hover:bg-blue-700 transition duration-300">Register Student</button>
    </form>

    <p class="mt-6 text-center text-gray-600">
        <a href="index.php?page=dashboard" class="text-blue-600 hover:underline">Back to Dashboard</a>
    </p>
</div>