<?php
// FILE PATH: Project/admin/users/add_staff.php
session_start();

// Pathing logic to reach the config folder from the users subfolder
$projectRoot = dirname(dirname(__DIR__));
require_once $projectRoot . '/config/database.php';
require_once $projectRoot . '/config/config.php';

// 1. SECURITY: Only 'admin' (Super Admin) can create staff accounts
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../dashboard.php");
    exit();
}

$message = "";

/**
 * DATABASE REPAIR LOGIC
 * This fixes the "Unknown column username" or "Duplicate entry" errors automatically.
 */
try {
    // Check if column exists
    $pdo->query("SELECT username FROM users LIMIT 1");
} catch (PDOException $e) {
    try {
        // Step A: Add column without UNIQUE constraint first to avoid crashing on existing empty rows
        $pdo->exec("ALTER TABLE users ADD COLUMN username VARCHAR(100) AFTER fullname");
        
        // Step B: Update existing users so they have a username (prevents duplicate empty strings)
        // We use their fullname (lowercase, no spaces) as a temporary username
        $pdo->exec("UPDATE users SET username = LOWER(REPLACE(fullname, ' ', '')) WHERE username IS NULL OR username = ''");
        
        // Step C: Now that data is clean, apply the UNIQUE and NOT NULL constraints
        $pdo->exec("ALTER TABLE users MODIFY username VARCHAR(100) NOT NULL UNIQUE");
    } catch (PDOException $innerError) {
        $message = "<div class='alert error'>Migration Failed: " . $innerError->getMessage() . "</div>";
    }
}

// 2. PROCESS FORM SUBMISSION
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $fullname = trim($_POST['fullname']);
    $username = trim($_POST['username']); 
    $password = $_POST['password'];
    $role     = $_POST['role'];

    if (empty($fullname) || empty($username) || empty($password)) {
        $message = "<div class='alert error'>All fields are required!</div>";
    } else {
        try {
            // Check if username is already taken by another staff member
            $check_stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
            $check_stmt->execute([$username]);

            if ($check_stmt->rowCount() > 0) {
                $message = "<div class='alert error'>Error: Username '$username' is already taken.</div>";
            } else {
                // Securely hash the password
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);

                // Insert the new staff member
                $insert_sql = "INSERT INTO users (fullname, username, password, role) VALUES (?, ?, ?, ?)";
                $insert_stmt = $pdo->prepare($insert_sql);
                
                if ($insert_stmt->execute([$fullname, $username, $hashed_password, $role])) {
                    $message = "<div class='alert success'>Success! $role account created for $fullname.</div>";
                }
            }
        } catch (PDOException $e) {
            $message = "<div class='alert error'>Database Error: " . $e->getMessage() . "</div>";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Staff | Portal</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { 
            --primary: #1a252f; 
            --accent: #3498db; 
            --success: #27ae60;
            --error: #e74c3c;
            --bg: #f4f7f6; 
        }
        
        body { 
            font-family: 'Inter', 'Segoe UI', sans-serif; 
            background: var(--bg); 
            display: flex; 
            align-items: center; 
            justify-content: center; 
            min-height: 100vh; 
            margin: 0; 
        }
        
        .container { 
            background: white; 
            padding: 40px; 
            border-radius: 15px; 
            box-shadow: 0 10px 30px rgba(0,0,0,0.1); 
            width: 100%; 
            max-width: 450px; 
            box-sizing: border-box;
        }

        .header { text-align: center; margin-bottom: 30px; }
        .header i { font-size: 50px; color: var(--accent); margin-bottom: 15px; }
        .header h2 { margin: 0; color: var(--primary); font-size: 24px; }
        .header p { color: #7f8c8d; font-size: 14px; margin-top: 5px; }

        .form-group { margin-bottom: 20px; }
        label { display: block; font-weight: 600; margin-bottom: 8px; color: #444; font-size: 14px; }
        input, select { 
            width: 100%; 
            padding: 12px; 
            border: 2px solid #eee; 
            border-radius: 8px; 
            font-size: 15px; 
            transition: 0.3s; 
            box-sizing: border-box; 
        }
        input:focus, select:focus { border-color: var(--accent); outline: none; background: #fff; }

        .btn-submit { 
            background: var(--primary); 
            color: white; 
            border: none; 
            padding: 15px; 
            width: 100%; 
            border-radius: 8px; 
            font-weight: bold; 
            cursor: pointer; 
            font-size: 16px; 
            transition: 0.3s; 
            margin-top: 10px;
        }
        .btn-submit:hover { background: var(--accent); transform: translateY(-2px); box-shadow: 0 5px 15px rgba(52, 152, 219, 0.3); }

        .alert { padding: 15px; border-radius: 8px; margin-bottom: 20px; text-align: center; font-weight: bold; font-size: 14px; }
        .success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }

        .back-link { text-align: center; margin-top: 25px; border-top: 1px solid #eee; padding-top: 20px; }
        .back-link a { color: #7f8c8d; text-decoration: none; font-size: 14px; transition: 0.3s; }
        .back-link a:hover { color: var(--accent); }
    </style>
</head>
<body>

<div class="container">
    <div class="header">
        <i class="fa fa-user-shield"></i>
        <h2>Staff Registration</h2>
        <p>Create access for Teachers or Sub-Admins</p>
    </div>

    <?php echo $message; ?>

    <form method="POST" action="">
        <div class="form-group">
            <label><i class="fa fa-id-card"></i> Full Name</label>
            <input type="text" name="fullname" placeholder="e.g. Mr. Samuel Jackson" required>
        </div>

        <div class="form-group">
            <label><i class="fa fa-user-tag"></i> Login Username</label>
            <input type="text" name="username" placeholder="e.g. samjackson24" required>
        </div>

        <div class="form-group">
            <label><i class="fa fa-key"></i> Temporary Password</label>
            <input type="password" name="password" placeholder="Min 6 characters" required>
        </div>

        <div class="form-group">
            <label><i class="fa fa-user-cog"></i> System Role</label>
            <select name="role" required>
                <option value="teacher">Teacher (Results Only)</option>
                <option value="subadmin">Sub-Admin (Operations)</option>
                <option value="admin">Super Admin (Full Access)</option>
            </select>
        </div>

        <button type="submit" class="btn-submit">Register Staff Member</button>
    </form>

    <div class="back-link">
        <a href="../dashboard.php"><i class="fa fa-arrow-left"></i> Back to Dashboard</a>
    </div>
</div>

</body>
</html>