<?php
/**
 * Emergency Fix: Create ALL missing student user accounts
 * This will create user accounts for all 214 missing students
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "<!DOCTYPE html>
<html>
<head>
    <title>Emergency Student Account Creation</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }
        .container { max-width: 800px; margin: 0 auto; background: white; padding: 20px; border-radius: 10px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
        .success { color: green; }
        .error { color: red; }
        .warning { color: orange; }
        .info { color: blue; }
        .progress { background: #e9ecef; border-radius: 5px; padding: 15px; margin: 15px 0; }
        button { background: #006747; color: white; border: none; padding: 12px 20px; border-radius: 5px; cursor: pointer; font-size: 16px; }
        button:hover { background: #004d35; }
        .log { background: #f8f9fa; border: 1px solid #dee2e6; padding: 10px; margin: 10px 0; border-radius: 5px; max-height: 300px; overflow-y: auto; }
    </style>
</head>
<body>
<div class='container'>";

echo "<h1>🚨 Emergency Student Account Creation</h1>";
echo "<p>Creating user accounts for all missing students (214 students need accounts)</p>";

try {
    // Database connection
    try {
        require_once 'config/database.php';
    } catch (Exception $e) {
        $host = 'localhost';
        $dbname = 'school_management';
        $username = 'root';
        $password = 'root';
        
        try {
            $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password, [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            ]);
        } catch (Exception $e2) {
            $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, '', [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            ]);
        }
    }
    
    echo "<div class='progress'>";
    echo "<h3>📊 Current Status Check</h3>";
    
    // Get current status
    $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'];
    
    $stmt = $pdo->query("SELECT COUNT(*) as count FROM users WHERE role = 'student'");
    $student_users = $stmt->fetch()['count'];
    
    $missing_count = $total_students - $students_with_user;
    
    echo "<p><strong>Total Students:</strong> $total_students</p>";
    echo "<p><strong>Students with Accounts:</strong> $students_with_user</p>";
    echo "<p><strong>Missing Accounts:</strong> $missing_count</p>";
    echo "<p><strong>Current User Records:</strong> $student_users</p>";
    echo "</div>";
    
    if ($missing_count == 0) {
        echo "<div class='success'>";
        echo "<h3>✅ All Students Have Accounts!</h3>";
        echo "<p>No action needed. All students already have user accounts.</p>";
        echo "<p><a href='admin/users.php?role_filter=student&per_page=100'>View Complete Student List</a></p>";
        echo "</div>";
        exit;
    }
    
    // Get all students without user accounts
    $stmt = $pdo->query("
        SELECT id, first_name, last_name, student_id, customer_number
        FROM students 
        WHERE user_id IS NULL OR user_id = 0 OR user_id = '' 
        ORDER BY id
    ");
    $missing_students = $stmt->fetchAll();
    
    echo "<div class='warning'>";
    echo "<h3>⚠️ Missing Student Accounts Found</h3>";
    echo "<p>Found <strong>$missing_count</strong> students without user accounts.</p>";
    echo "<p>This process will create user accounts for all of them.</p>";
    echo "</div>";
    
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['create_all'])) {
        echo "<div class='progress'>";
        echo "<h3>🛠️ Creating User Accounts...</h3>";
        echo "<div class='log' id='logOutput'>";
        
        $created_count = 0;
        $errors = [];
        $batch_size = 10; // Process in batches to avoid timeouts
        
        foreach (array_chunk($missing_students, $batch_size) as $batch_index => $batch) {
            echo "<p><strong>Processing batch " . ($batch_index + 1) . " of " . ceil(count($missing_students)/$batch_size) . "</strong></p>";
            
            foreach ($batch as $student) {
                try {
                    // Create unique username
                    $clean_name = preg_replace('/[^a-zA-Z0-9]/', '', $student['first_name'] . $student['last_name']);
                    $base_username = strtolower(substr($clean_name, 0, 12));
                    
                    if (empty($base_username)) {
                        $base_username = 'stu' . $student['id'];
                    }
                    
                    $username = $base_username;
                    $counter = 1;
                    
                    // Ensure username uniqueness
                    while (true) {
                        $stmt_check = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = ?");
                        $stmt_check->execute([$username]);
                        if ($stmt_check->fetchColumn() == 0) {
                            break;
                        }
                        $username = $base_username . $counter;
                        $counter++;
                        if ($counter > 50) {
                            $username = 'student' . $student['id'] . rand(1000, 9999);
                            break;
                        }
                    }
                    
                    // Create account details
                    $email = $username . '@school.edu';
                    $password_raw = $student['student_id'] ?: $username;
                    $password = password_hash($password_raw, PASSWORD_DEFAULT);
                    
                    // Create user account
                    $pdo->beginTransaction();
                    
                    $stmt_insert = $pdo->prepare("
                        INSERT INTO users (username, email, password, role, status, created_at) 
                        VALUES (?, ?, ?, 'student', 'active', NOW())
                    ");
                    $stmt_insert->execute([$username, $email, $password]);
                    
                    $user_id = $pdo->lastInsertId();
                    
                    // Link to student record
                    $stmt_update = $pdo->prepare("UPDATE students SET user_id = ? WHERE id = ?");
                    $stmt_update->execute([$user_id, $student['id']]);
                    
                    $pdo->commit();
                    
                    echo "<p class='success'>✓ Created '$username' for {$student['first_name']} {$student['last_name']} (ID: {$student['id']})</p>";
                    $created_count++;
                    
                    // Flush output to show progress
                    if ($created_count % 5 == 0) {
                        echo "<script>document.getElementById('logOutput').scrollTop = document.getElementById('logOutput').scrollHeight;</script>";
                        flush();
                    }
                    
                } catch (Exception $e) {
                    if ($pdo->inTransaction()) {
                        $pdo->rollback();
                    }
                    $error_msg = "✗ Failed for student ID {$student['id']}: " . $e->getMessage();
                    echo "<p class='error'>$error_msg</p>";
                    $errors[] = $error_msg;
                }
            }
            
            // Small delay between batches to prevent server overload
            usleep(100000); // 0.1 second
        }
        
        echo "</div>"; // Close log div
        echo "</div>"; // Close progress div
        
        echo "<div class='success'>";
        echo "<h3>📊 Completion Summary</h3>";
        echo "<p><strong>Successfully Created:</strong> $created_count accounts</p>";
        echo "<p><strong>Errors Encountered:</strong> " . count($errors) . "</p>";
        
        if (!empty($errors)) {
            echo "<h4>Errors:</h4>";
            echo "<div style='background: #ffe6e6; padding: 10px; border-radius: 5px;'>";
            foreach (array_slice($errors, 0, 10) as $error) {
                echo "<p style='margin: 5px 0; color: #d00;'>$error</p>";
            }
            if (count($errors) > 10) {
                echo "<p>... and " . (count($errors) - 10) . " more errors</p>";
            }
            echo "</div>";
        }
        
        echo "<h4>🎉 Success!</h4>";
        echo "<p>All missing student user accounts have been created.</p>";
        echo "<p><a href='admin/users.php?role_filter=student&per_page=100' target='_blank'><button>View Complete Student List</button></a></p>";
        echo "<p><a href='?refresh=1'><button>Refresh Status</button></a></p>";
        echo "</div>";
        
    } else {
        echo "<form method='POST' onsubmit='return confirm(\"This will create $missing_count user accounts. Are you sure?\");'>";
        echo "<button type='submit' name='create_all'>";
        echo "🚀 Create All $missing_count Missing User Accounts NOW";
        echo "</button>";
        echo "</form>";
        
        echo "<div class='info'>";
        echo "<h4>What This Will Do:</h4>";
        echo "<ul>";
        echo "<li>Create user accounts for all $missing_count students without accounts</li>";
        echo "<li>Generate unique usernames based on student names</li>";
        echo "<li>Set default passwords to student IDs</li>";
        echo "<li>Link students to their new user accounts</li>";
        echo "<li>Make all students visible in admin user list</li>";
        echo "</ul>";
        echo "<p><strong>Estimated time:</strong> 2-5 minutes depending on server speed</p>";
        echo "</div>";
    }
    
    // Auto-refresh
    if (isset($_GET['refresh'])) {
        echo "<script>setTimeout(function(){ location.href = '?'; }, 3000);</script>";
        echo "<p class='info'>Refreshing page in 3 seconds...</p>";
    }
    
} catch (Exception $e) {
    echo "<div class='error'>";
    echo "<h3>❌ Critical Error</h3>";
    echo "<p>" . htmlspecialchars($e->getMessage()) . "</p>";
    echo "</div>";
}

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