<?php
// register_user.php
// Unified page for Admin to register new users (Admin, Instructor, Student)
// All new accounts are provisioned with a secure initial password (the user's email) 
// and require email verification via a One-Time Password (OTP) on first login.

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Ensure the user is logged in and is an admin.
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true || $_SESSION['user_role'] !== 'admin') {
    header("Location: index.php?page=login");
    exit();
}

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

// --- EMAIL-SENDING FUNCTION ---
/**
 * Sends an email with the OTP for first-time login and verification.
 */
function sendRegistrationEmail(string $user_email, string $user_name, string $otp, string $role): bool {
    try {
        $mail = new PHPMailer(true);
        $mail->isSMTP();
        
        // 🚨 IMPORTANT: CONFIGURE YOUR SMTP SETTINGS HERE 🚨
        $mail->Host       = 'smtp.gmail.com'; 
        $mail->SMTPAuth   = true;
        $mail->Username   = 'bazithali95@gmail.com'; // Your SMTP Username
        $mail->Password   = 'sqkt opow cvao fiac';   // Your App Password/SMTP Password
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; 
        $mail->Port       = 587;
        
        $mail->setFrom('bazithali95@gmail.com', 'Orinsto LMS');
        $mail->addAddress($user_email, $user_name);
        
        $role_title = ucwords($role);
        $login_url = 'https://orinsto.lk/olms'; // The specified login link

        $mail->isHTML(true);
        $mail->Subject = "Welcome to Orinsto LMS - Your One-Time Login Code";
        $mail->Body    = "
            <p>Dear " . htmlspecialchars($user_name) . ",</p>
            <p>Welcome to Orinsto LMS! An account with the role **$role_title** has been created for you.</p>
            <p>To complete your first login, please follow these steps:</p>
            <ol>
                <li>Click here to go to the login page: <a href=\"{$login_url}\">{$login_url}</a></li>
                <li>Enter your **email address** as both your initial 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 and is valid for **15 minutes**. After your first successful login and OTP verification, you will be required 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 role is $role_title. For your first login, use your email address as both the username and password. Your one-time login code (OTP) is: " . htmlspecialchars($otp) . ". Click the link to log in: {$login_url}. You will be prompted to set a new password after you log in.";
        
        $mail->send();
        return true;
    } catch (Exception $e) {
        // Log the error for administrator review
        error_log("Registration email failed for {$user_email} (Role: $role). Mailer Error: {$mail->ErrorInfo}");
        return false;
    }
}
// --- END OF EMAIL-SENDING FUNCTION ---

$message = '';
$is_error = false;

// Initialize form fields for sticky form behavior.
$username = '';
$email = '';
$full_name = '';

// --- Determine the Role and Title based on the 'role' parameter ---
$role_param = $_GET['role'] ?? 'student';

// Sanitize and validate the role
$allowed_roles = ['admin', 'instructor', 'student'];
$role = in_array($role_param, $allowed_roles) ? $role_param : 'student';

$title = 'Register New ' . ucwords($role);

// --- Form Submission Logic ---
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = trim($_POST['username'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $full_name = trim($_POST['full_name'] ?? '');
    
    // Role is carried over from the hidden field
    $role = $_POST['role'] ?? $role; 

    // --- Input Validation ---
    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 {
        // --- Check for existing username or email ---
        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 {
                // --- Set Initial Password (Email) and Generate OTP ---
                // Initial password is set to the email address and is hashed immediately.
                $initial_password = $email;
                $hashed_password = password_hash($initial_password, PASSWORD_DEFAULT);

                // Generate a strong, random OTP (e.g., 32-char hex string)
                $otp = bin2hex(random_bytes(16)); 
                // OTP valid for 15 minutes
                $otp_expiry = date('Y-m-d H:i:s', strtotime('+1,440 minutes'));

                $pdo->beginTransaction();

                // --- Insert user into database ---
                // verified=0 means the account is pending OTP verification.
                // The users table must have columns: username, password, email, full_name, role, otp, otp_expiry, verified
                $stmt = $pdo->prepare("INSERT INTO users (username, password, email, full_name, role, otp, otp_expiry, verified) VALUES (?, ?, ?, ?, ?, ?, ?, 0)"); 
                
                if (!$stmt->execute([$username, $hashed_password, $email, $full_name, $role, $otp, $otp_expiry])) {
                    throw new Exception("Error inserting user into the database.");
                }

                // --- Send the registration email with the OTP ---
                if (sendRegistrationEmail($email, $full_name, $otp, $role)) {
                    $pdo->commit();
                    $display_role = ucwords($role);
                    $success_message = "$display_role '<strong>" . htmlspecialchars($full_name) . "</strong>' registered successfully! ";
                    $success_message .= "An email with a one-time login code has been sent to <strong>" . htmlspecialchars($email) . "</strong>. The new user must use this code for their first login.";

                    // Store success message for redirect
                    $_SESSION['message'] = $success_message;
                    $_SESSION['is_error'] = false;
                    
                    // Clear fields for a new entry on the form
                    $username = $email = $full_name = '';

                    header("Location: index.php?page=manage_users");
                    exit();
                } else {
                    // Rollback if the database insert worked but the email failed
                    throw new Exception("User registered, but the welcome email failed to send. Database changes have been rolled back.");
                }
            }
        } catch (Exception $e) {
            if (isset($pdo) && $pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $message = "Error: " . $e->getMessage();
            $is_error = true;
            error_log("Registration Error: " . $e->getMessage());
        } catch (PDOException $e) {
            if (isset($pdo) && $pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $message = "Database error: " . $e->getMessage();
            $is_error = true;
            error_log("Registration PDO Error: " . $e->getMessage());
        }
    }
}
?>

<div class="bg-white p-8 rounded-lg shadow-md w-full max-w-lg mx-auto">
    <h2 class="text-2xl font-bold mb-6 text-center text-gray-800"><?php echo htmlspecialchars($title); ?></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_user&role=<?php echo htmlspecialchars($role); ?>" method="POST" class="space-y-4">
        <input type="hidden" name="role" value="<?php echo htmlspecialchars($role); ?>">

        <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 shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
        </div>
        <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 shadow-sm 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 shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
        </div>
        
        <div class="p-3 bg-yellow-50 border-l-4 border-yellow-500 text-yellow-700 text-sm">
            <p><strong>Note:</strong> A temporary password (the user's email) and a One-Time Password (OTP) will be sent to the email address for the first login and verification. The user must navigate to **<?php echo $login_url; ?>**.</p>
        </div>

        <button type="submit"
                     class="w-full py-2 px-4 bg-blue-600 text-white font-semibold rounded-md shadow-md hover:bg-blue-700 transition duration-300">Register <?php echo ucwords($role); ?></button>
    </form>

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