<?php
session_start();
require '../includes/config.php';

// To enable email confirmation, install PHPMailer via Composer:
// 1. Run: composer require phpmailer/phpmailer
// 2. Uncomment PHPMailer requires and email code below
// 3. Update SMTP settings (Host, Port, etc.) for your mail server
// 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;

// Restrict to admins
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header('Location: index.php');
    exit;
}

// Fetch available roles
$roles_query = "SELECT role_id, role_name FROM roles ORDER BY role_name";
$roles_result = mysqli_query($conn, $roles_query);
$roles = mysqli_fetch_all($roles_result, MYSQLI_ASSOC);

$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'];
    $designation = $_POST['designation'];
    $role_id = $_POST['role_id'];
    $id = isset($_POST['id']) ? trim($_POST['id']) : '';
    $role = 'staff'; // Fixed role

    // Validate inputs
    if (empty($first_name) || empty($last_name) || empty($email) || empty($password) || empty($designation) || empty($role_id)) {
        $error = "All fields are required.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Invalid email format.";
    } elseif (!in_array($designation, ['Teaching Staff', 'Non-Teaching Staff'])) {
        $error = "Invalid designation 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 = 'T';
                $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 custom ID.";
                }
            } else {
                // Validate custom ID
                if (strlen($id) > 50) {
                    $error = "ID must be 50 characters or less.";
                } elseif (!preg_match('/^[a-zA-Z0-9-_]+$/', $id)) {
                    $error = "ID can only contain letters, numbers, hyphens, and underscores.";
                } else {
                    $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.";
                    }
                }
            }

            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, designation) VALUES (?, ?, ?, ?, ?, ?, ?)";
                $stmt = mysqli_prepare($conn, $query);
                mysqli_stmt_bind_param($stmt, 'sssssss', $id, $first_name, $last_name, $email, $hashed_password, $role, $designation);
                if (mysqli_stmt_execute($stmt)) {
                    // Insert user-role mapping
                    $query = "INSERT INTO user_roles (user_id, role_id) VALUES (?, ?)";
                    $stmt = mysqli_prepare($conn, $query);
                    mysqli_stmt_bind_param($stmt, 'si', $id, $role_id);
                    if (mysqli_stmt_execute($stmt)) {
                        $generated_id = $id;
                        $success = "Staff registered successfully! User ID: $id";
                        // To enable email confirmation, uncomment and configure PHPMailer:
                        /*
                        $mail = new PHPMailer(true);
                        try {
                            $mail->isSMTP();
                            $mail->Host = 'localhost';
                            $mail->Port = 1025;
                            $mail->SMTPAuth = false;
                            $mail->SMTPSecure = '';
                            $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 staff account has been created successfully.\nID: $id\nDesignation: $designation\nRole: " . ($roles[array_search($role_id, array_column($roles, 'role_id'))]['role_name']) . "\n\nLogin at http://localhost/appraisal/public\n\nBest regards,\nAppraisal System";
                            $mail->AltBody = $mail->Body;
                            $mail->send();
                            $success = "Staff registered successfully! A confirmation email has been sent. User ID: $id";
                        } catch (Exception $e) {
                            $success = "Staff registered successfully, but failed to send email: " . $mail->ErrorInfo . " User ID: $id";
                        }
                        */
                    } else {
                        $error = "Failed to assign role: " . mysqli_error($conn);
                    }
                } else {
                    $error = "Failed to register: " . mysqli_error($conn);
                }
            }
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Register Staff</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="../css/register.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <h2>Register Staff</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>ID (Optional, e.g., STAFF123 or T00001)</label>
                <input type="text" name="id" class="form-control" value="<?php echo isset($_POST['id']) ? htmlspecialchars($_POST['id']) : ''; ?>" placeholder="Leave blank to auto-generate or enter a unique ID">
            </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>Designation</label>
                <select name="designation" class="form-control" required>
                    <option value="">Select Designation</option>
                    <option value="Teaching Staff">Teaching Staff</option>
                    <option value="Non-Teaching Staff">Non-Teaching Staff</option>
                </select>
            </div>
            <div class="form-group mb-3">
                <label>Role</label>
                <select name="role_id" class="form-control" required>
                    <option value="">Select Role</option>
                    <?php foreach ($roles as $role): ?>
                        <option value="<?php echo $role['role_id']; ?>" <?php echo isset($_POST['role_id']) && $_POST['role_id'] == $role['role_id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($role['role_name']); ?>
                        </option>
                    <?php endforeach; ?>
                </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>