<?php
/**
 * Fix Student User Accounts - Robust version
 * Creates user accounts for all students without them
 */

// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "<!DOCTYPE html>
<html>
<head>
    <title>Fix Student User Accounts</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .success { color: green; }
        .error { color: red; }
        .info { color: blue; }
        .warning { color: orange; }
        pre { background: #f5f5f5; padding: 10px; }
    </style>
</head>
<body>";

echo "<h1>🔧 Fixing Student User Accounts</h1>";

try {
    // Try different database connection methods
    $pdo = null;
    
    // Method 1: Try the standard config
    try {
        require_once 'config/database.php';
    } catch (Exception $e) {
        echo "<p class='warning'>Warning: Standard database config failed - " . $e->getMessage() . "</p>";
    }
    
    // Method 2: Try direct connection if $pdo not set
    if (!isset($pdo) || $pdo === null) {
        echo "<p class='info'>Attempting direct database connection...</p>";
        
        $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,
                PDO::ATTR_EMULATE_PREPARES => false,
            ]);
            echo "<p class='success'>✅ Direct database connection successful</p>";
        } catch (Exception $e) {
            echo "<p class='error'>❌ Direct connection failed: " . $e->getMessage() . "</p>";
            
            // Try with empty password
            try {
                $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,
                    PDO::ATTR_EMULATE_PREPARES => false,
                ]);
                echo "<p class='success'>✅ Connected with empty password</p>";
            } catch (Exception $e2) {
                echo "<p class='error'>❌ Empty password also failed: " . $e2->getMessage() . "</p>";
                throw new Exception("Could not connect to database with any method");
            }
        }
    }
    
    echo "<h2>📊 Current Database Status</h2>";
    
    // Check 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'];
    
    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>";
    echo "<p><strong>Existing Student Users:</strong> $student_users</p>";
    
    if ($total_students == $students_with_user) {
        echo "<p class='success'>✅ All students already have user accounts!</p>";
        echo "<p><a href='admin/users.php?role_filter=student' target='_blank'>View Student Users</a></p>";
        exit;
    }
    
    echo "<h2>🛠️ Creating User Accounts</h2>";
    
    // 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 = '' 
        ORDER BY id 
        LIMIT 50
    ");
    $students_needing_accounts = $stmt->fetchAll();
    
    echo "<p>Found " . count($students_needing_accounts) . " students needing user accounts</p>";
    
    if (empty($students_needing_accounts)) {
        echo "<p class='info'>No students found needing user accounts.</p>";
        exit;
    }
    
    $created_count = 0;
    $errors = [];
    
    echo "<h3>Processing Students:</h3>";
    
    foreach ($students_needing_accounts as $student) {
        try {
            // Create clean username from student name
            $clean_name = preg_replace('/[^a-zA-Z0-9]/', '', $student['first_name'] . $student['last_name']);
            $base_username = strtolower(substr($clean_name, 0, 15)); // Limit length
            
            if (empty($base_username)) {
                $base_username = 'student' . $student['id'];
            }
            
            $username = $base_username;
            $counter = 1;
            
            // Ensure username is unique
            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++;
                
                // Prevent infinite loop
                if ($counter > 100) {
                    $username = 'student' . $student['id'] . '_' . time();
                    break;
                }
            }
            
            // Create email
            $email = $username . '@school.edu';
            
            // Create simple password (student ID or username)
            $password_raw = $student['student_id'] ?: $username;
            $password = password_hash($password_raw, PASSWORD_DEFAULT);
            
            // Insert user with transaction
            $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();
            
            // Update 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 user '$username' for {$student['first_name']} {$student['last_name']} (ID: {$student['id']})</p>";
            $created_count++;
            
            // Show progress every 10 students
            if ($created_count % 10 == 0) {
                echo "<p class='info'><strong>Progress:</strong> $created_count accounts created so far...</p>";
            }
            
        } 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;
        }
    }
    
    echo "<h2>📊 Summary</h2>";
    echo "<p><strong>Successfully Created:</strong> $created_count user accounts</p>";
    echo "<p><strong>Errors Encountered:</strong> " . count($errors) . "</p>";
    
    if (!empty($errors)) {
        echo "<h3>Errors:</h3>";
        echo "<pre>" . implode("\n", array_slice($errors, 0, 5)) . "</pre>";
        if (count($errors) > 5) {
            echo "<p>... and " . (count($errors) - 5) . " more errors</p>";
        }
    }
    
    if ($created_count > 0) {
        echo "<div class='success'>";
        echo "<h3>🎉 Success!</h3>";
        echo "<p>Created $created_count student user accounts.</p>";
        echo "<p>Passwords are set to student IDs (or usernames if ID unavailable).</p>";
        echo "</div>";
        
        echo "<h3>Next Steps:</h3>";
        echo "<ol>";
        echo "<li><a href='admin/users.php?role_filter=student' target='_blank'>View Student Users Page</a></li>";
        echo "<li><a href='diagnose_admin_users.php' target='_blank'>Run Diagnostic Again</a> to verify fix</li>";
        echo "<li>Test filtering by 'ছাত্র-ছাত্রী' (Student) role</li>";
        echo "</ol>";
        
        echo "<h3>Important Notes:</h3>";
        echo "<ul>";
        echo "<li>Students can now log in with their usernames and student IDs as passwords</li>";
        echo "<li>You may want to change passwords for security</li>";
        echo "<li>If you have more than 50 students, run this script again to process remaining students</li>";
        echo "</ul>";
    } else {
        echo "<p class='error'>❌ No user accounts were created. Check the errors above.</p>";
    }
    
} catch (Exception $e) {
    echo "<div class='error'>";
    echo "<h3>❌ Critical Error</h3>";
    echo "<p>" . htmlspecialchars($e->getMessage()) . "</p>";
    echo "<pre>" . htmlspecialchars($e->getTraceAsString()) . "</pre>";
    echo "</div>";
}

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