<?php
session_start();
require '../includes/config.php';
require '../vendor/phpmailer/src/PHPMailer.php';
require '../vendor/phpmailer/src/SMTP.php';
require '../vendor/phpmailer/src/Exception.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

$error = '';
$success = '';
$generated_id = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $first_name = trim($_POST['first_name']);
    $last_name = trim($_POST['last_name']);
    $email = trim($_POST['email']);
    $password = $_POST['password'];
    $role = $_POST['role'];
    $id = isset($_POST['id']) ? trim($_POST['id']) : ''; // Optional manual ID

    // Validate inputs
    if (empty($first_name) || empty($last_name) || empty($email) || empty($password) || empty($role)) {
        $error = "All fields are required.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Invalid email format.";
    } elseif (!in_array($role, ['admin', 'staff', 'student'])) {
        $error = "Invalid role selected.";
    } else {
        // Check if email exists
        $query = "SELECT id FROM users WHERE email = ?";
        $stmt = mysqli_prepare($conn, $query);
        mysqli_stmt_bind_param($stmt, 's', $email);
        mysqli_stmt_execute($stmt);
        if (mysqli_stmt_get_result($stmt)->num_rows > 0) {
            $error = "Email already registered.";
        } else {
            // Generate or validate ID
            if (empty($id)) {
                // Auto-generate unique ID
                $prefix = $role == 'admin' ? 'A' : ($role == 'staff' ? 'T' : 'S');
                $attempts = 0;
                $max_attempts = 10;
                do {
                    $random_num = mt_rand(1, 99999);
                    $id = $prefix . str_pad($random_num, 5, '0', STR_PAD_LEFT);
                    $query = "SELECT id FROM users WHERE id = ?";
                    $stmt = mysqli_prepare($conn, $query);
                    mysqli_stmt_bind_param($stmt, 's', $id);
                    mysqli_stmt_execute($stmt);
                    $result = mysqli_stmt_get_result($stmt);
                    $attempts++;
                } while ($result->num_rows > 0 && $attempts < $max_attempts);
                
                if ($attempts >= $max_attempts) {
                    $error = "Unable to generate a unique ID. Please try again or enter a manual ID.";
                }
            } else {
                // Validate manual ID
                $query = "SELECT id FROM users WHERE id = ?";
                $stmt = mysqli_prepare($conn, $query);
                mysqli_stmt_bind_param($stmt, 's', $id);
                mysqli_stmt_execute($stmt);
                if (mysqli_stmt_get_result($stmt)->num_rows > 0) {
                    $error = "ID already exists. Choose another.";
                } elseif (!preg_match('/^[ATS][0-9]{5}$/', $id)) {
                    $error = "ID must be in format: A/T/S followed by 5 digits (e.g., T00001).";
                }
            }

            if (empty($error)) {
                // Hash password
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);

                // Insert user
                $query = "INSERT INTO users (id, first_name, last_name, email, password, role) VALUES (?, ?, ?, ?, ?, ?)";
                $stmt = mysqli_prepare($conn, $query);
                mysqli_stmt_bind_param($stmt, 'ssssss', $id, $first_name, $last_name, $email, $hashed_password, $role);
                if (mysqli_stmt_execute($stmt)) {
                    $generated_id = $id; // Store for success message
                    // Send confirmation email
                    $mail = new PHPMailer(true);
                    try {
                        // SMTP settings (MailHog for local testing)
                        $mail->isSMTP();
                        $mail->Host = 'localhost';
                        $mail->Port = 1025;
                        $mail->SMTPAuth = false;
                        $mail->SMTPSecure = '';

                        // For production, use Gmail SMTP (uncomment and configure):
                        /*
                        $mail->Host = 'smtp.gmail.com';
                        $mail->Port = 587;
                        $mail->SMTPAuth = true;
                        $mail->Username = 'your_email@gmail.com';
                        $mail->Password = 'your_app_password';
                        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
                        */

                        // Email settings
                        $mail->setFrom('no-reply@appraisal.local', 'Appraisal System');
                        $mail->addAddress($email, "$first_name $last_name");
                        $mail->Subject = 'Registration Confirmation';
                        $mail->Body = "Dear $first_name $last_name,\n\nYour account has been created successfully.\nID: $id\nRole: $role\n\nLogin at http://localhost/appraisal/public\n\nBest regards,\nAppraisal System";
                        $mail->AltBody = $mail->Body;

                        $mail->send();
                        $success = "Registration successful! A confirmation email has been sent. User ID: $id";
                    } catch (Exception $e) {
                        $success = "Registration successful, but failed to send email: " . $mail->ErrorInfo . " User ID: $id";
                    }
                } else {
                    $error = "Failed to register: " . mysqli_error($conn);
                }
            }
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Register</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="../css/style.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <h2>Register</h2>
        <?php if ($success): ?>
            <div class="alert alert-success"><?php echo htmlspecialchars($success); ?></div>
        <?php endif; ?>
        <?php if ($error): ?>
            <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>

        <form method="POST">
            <div class="form-group mb-3">
                <label>Student/Staff ID </label>
                <input type="text" name="id" class="form-control" value="<?php echo isset($_POST['id']) ? htmlspecialchars($_POST['id']) : ''; ?>" placeholder="Leave blank to auto-generate">
            </div>
            <div class="form-group mb-3">
                <label>First Name</label>
                <input type="text" name="first_name" class="form-control" value="<?php echo isset($_POST['first_name']) ? htmlspecialchars($_POST['first_name']) : ''; ?>" required>
            </div>
            <div class="form-group mb-3">
                <label>Last Name</label>
                <input type="text" name="last_name" class="form-control" value="<?php echo isset($_POST['last_name']) ? htmlspecialchars($_POST['last_name']) : ''; ?>" required>
            </div>
            <div class="form-group mb-3">
                <label>Email</label>
                <input type="email" name="email" class="form-control" value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>" required>
            </div>
            <div class="form-group mb-3">
                <label>Password</label>
                <input type="password" name="password" class="form-control" required>
            </div>
            <div class="form-group mb-3">
                <label>Role</label>
                <select name="role" class="form-control" required>
                    <option value="">Select Role</option>
                    <option value="admin">Admin</option>
                    <option value="staff">Staff</option>
                    <option value="student">Student</option>
                </select>
            </div>
            <button type="submit" class="btn btn-primary">Register</button>
            <a href="dashboard.php" class="btn btn-secondary">Back to Dashboard</a>
        </form>
    </div>
</body>
</html>