<?php
/**
 * Create sample student users for testing
 * This script creates sample user accounts for existing students
 */

require_once 'config/database.php';

echo "<!DOCTYPE html>
<html>
<head>
    <title>Create Sample Student Users</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .success { color: green; }
        .error { color: red; }
        .info { color: blue; }
    </style>
</head>
<body>";

echo "<h1>🎓 Create Sample Student Users</h1>";

try {
    // Check how many students exist
    $stmt = $pdo->query("SELECT COUNT(*) as total FROM students");
    $total_students = $stmt->fetch()['total'];
    
    $stmt = $pdo->query("SELECT COUNT(*) as count FROM students WHERE user_id IS NOT NULL AND user_id != 0 AND user_id != ''");
    $students_with_user = $stmt->fetch()['count'];
    
    echo "<p><strong>Total Students:</strong> $total_students</p>";
    echo "<p><strong>Students with User Accounts:</strong> $students_with_user</p>";
    echo "<p><strong>Students Needing User Accounts:</strong> " . ($total_students - $students_with_user) . "</p>";
    
    if ($total_students == 0) {
        echo "<p class='error'>❌ No students found in database. Please add some students first.</p>";
        exit;
    }
    
    if ($total_students == $students_with_user) {
        echo "<p class='success'>✅ All students already have user accounts.</p>";
        exit;
    }
    
    // Get students without user accounts
    $stmt = $pdo->query("
        SELECT id, first_name, last_name, student_id 
        FROM students 
        WHERE user_id IS NULL OR user_id = 0 OR user_id = '' 
        LIMIT 10
    ");
    $students_needing_accounts = $stmt->fetchAll();
    
    if (empty($students_needing_accounts)) {
        echo "<p class='info'>ℹ️ No students found needing user accounts.</p>";
        exit;
    }
    
    echo "<h2>Creating User Accounts for Students:</h2>";
    
    $created_count = 0;
    
    foreach ($students_needing_accounts as $student) {
        try {
            // Create username from student name and ID
            $base_username = strtolower(str_replace(' ', '', $student['first_name'] . $student['last_name']));
            $username = $base_username;
            $counter = 1;
            
            // Check if username exists and make it unique
            while (true) {
                $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = ?");
                $stmt->execute([$username]);
                if ($stmt->fetchColumn() == 0) {
                    break;
                }
                $username = $base_username . $counter;
                $counter++;
            }
            
            // Create email
            $email = $username . '@school.edu';
            
            // Create password (same as username for testing)
            $password = password_hash($username, PASSWORD_DEFAULT);
            
            // Insert user
            $stmt = $pdo->prepare("
                INSERT INTO users (username, email, password, role, status, created_at) 
                VALUES (?, ?, ?, 'student', 'active', NOW())
            ");
            $stmt->execute([$username, $email, $password]);
            
            $user_id = $pdo->lastInsertId();
            
            // Update student record with user_id
            $stmt = $pdo->prepare("UPDATE students SET user_id = ? WHERE id = ?");
            $stmt->execute([$user_id, $student['id']]);
            
            echo "<p class='success'>✅ Created user '$username' for student {$student['first_name']} {$student['last_name']} (ID: {$student['id']})</p>";
            $created_count++;
            
        } catch (Exception $e) {
            echo "<p class='error'>❌ Failed to create user for student ID {$student['id']}: " . $e->getMessage() . "</p>";
        }
    }
    
    echo "<h2>📊 Summary</h2>";
    echo "<p><strong>Users Created:</strong> $created_count</p>";
    
    if ($created_count > 0) {
        echo "<p class='success'>🎉 Successfully created $created_count student user accounts!</p>";
        echo "<p><a href='admin/users.php?role_filter=student' target='_blank'>View Student Users</a></p>";
        echo "<p><a href='diagnose_admin_users.php' target='_blank'>Run Diagnostic Again</a></p>";
    }
    
} catch (Exception $e) {
    echo "<div class='error'>";
    echo "<h3>❌ Error</h3>";
    echo "<p>" . htmlspecialchars($e->getMessage()) . "</p>";
    echo "</div>";
}

echo "</body></html>";
?>