<?php
/**
 * Admin Panel Student Account Fix Tool
 * Simple one-click solution for fixing missing student user accounts
 */

session_start();
require_once '../config/database.php';

// Check admin access
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] != 'admin') {
    header('Location: ../login.php');
    exit();
}

// Get system name for branding
$stmt = $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'site_name' LIMIT 1");
$site_name = $stmt->fetchColumn() ?: 'School Management System';

echo "<!DOCTYPE html>
<html lang='bn'>
<head>
    <meta charset='UTF-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <title>শিক্ষার্থী অ্যাকাউন্ট ফিক্স - " . htmlspecialchars($site_name) . "</title>
    <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css' rel='stylesheet'>
    <link href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css' rel='stylesheet'>
    <link href='https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap' rel='stylesheet'>
    <style>
        body { 
            font-family: 'Hind Siliguri', sans-serif; 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .fix-container {
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            overflow: hidden;
            max-width: 800px;
            margin: 0 auto;
        }
        .header {
            background: linear-gradient(135deg, #006747 0%, #004d35 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        .content {
            padding: 30px;
        }
        .btn-fix {
            background: linear-gradient(135deg, #006747 0%, #004d35 100%);
            border: none;
            padding: 15px 30px;
            font-size: 18px;
            font-weight: 600;
            border-radius: 10px;
            transition: all 0.3s ease;
        }
        .btn-fix:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(0,103,71,0.4);
        }
        .status-box {
            padding: 20px;
            border-radius: 10px;
            margin: 15px 0;
        }
        .complete { background-color: #d4edda; border: 1px solid #c3e6cb; }
        .incomplete { background-color: #f8d7da; border: 1px solid #f5c6cb; }
        .progress-display { background-color: #fff3cd; border: 1px solid #ffeaa7; }
        .log-output {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 15px;
            height: 300px;
            overflow-y: auto;
            font-family: monospace;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <div class='fix-container'>
        <div class='header'>
            <i class='fas fa-user-graduate fa-3x mb-3'></i>
            <h2>শিক্ষার্থী অ্যাকাউন্ট ফিক্স</h2>
            <p class='mb-0'>সকল শিক্ষার্থীকে ইউজার অ্যাকাউন্টে রূপান্তর করুন</p>
        </div>
        
        <div class='content'>";

try {
    // 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;
    $completion_rate = $total_students > 0 ? round(($students_with_user / $total_students) * 100, 1) : 0;
    
    echo "<div class='status-box " . ($completion_rate == 100 ? 'complete' : ($completion_rate > 0 ? 'progress-display' : 'incomplete')) . "'>";
    echo "<h4><i class='fas fa-chart-pie'></i> বর্তমান অবস্থা</h4>";
    echo "<div class='row'>";
    echo "<div class='col-md-4'><strong>মোট শিক্ষার্থী:</strong><br>$total_students জন</div>";
    echo "<div class='col-md-4'><strong>অ্যাকাউন্ট সহ:</strong><br>$students_with_user জন</div>";
    echo "<div class='col-md-4'><strong>অ্যাকাউন্ট ছাড়া:</strong><br>$missing_count জন</div>";
    echo "</div>";
    echo "<div class='mt-3'><strong>সম্পূর্ণতা হার:</strong> $completion_rate%</div>";
    echo "</div>";
    
    if ($missing_count == 0) {
        echo "<div class='alert alert-success'>";
        echo "<h4><i class='fas fa-check-circle'></i> সবকিছু ঠিক আছে!</h4>";
        echo "<p>সকল $total_students জন শিক্ষার্থীর ইউজার অ্যাকাউন্ট রয়েছে।</p>";
        echo "<a href='users.php?role_filter=student&per_page=100' class='btn btn-success'>শিক্ষার্থী তালিকা দেখুন</a>";
        echo "</div>";
    } else {
        if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['fix_accounts'])) {
            echo "<div class='alert alert-info'>";
            echo "<h4><i class='fas fa-cogs'></i> অ্যাকাউন্ট তৈরি হচ্ছে...</h4>";
            echo "<p>$missing_count জন শিক্ষার্থীর জন্য ইউজার অ্যাকাউন্ট তৈরি হচ্ছে। অনুগ্রহ করে অপেক্ষা করুন...</p>";
            echo "</div>";
            
            echo "<div class='log-output' id='logOutput'>";
            flush();
            
            $created_count = 0;
            $errors = [];
            
            // Get students without 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
            ");
            $missing_students = $stmt->fetchAll();
            
            foreach ($missing_students as $index => $student) {
                try {
                    // Create 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 unique username
                    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
                    $email = $username . '@school.edu';
                    $password_raw = $student['student_id'] ?: $username;
                    $password = password_hash($password_raw, PASSWORD_DEFAULT);
                    
                    $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();
                    
                    $stmt_update = $pdo->prepare("UPDATE students SET user_id = ? WHERE id = ?");
                    $stmt_update->execute([$user_id, $student['id']]);
                    
                    $pdo->commit();
                    
                    $log_message = "✓ '$username' তৈরি হয়েছে - {$student['first_name']} {$student['last_name']} (ID: {$student['id']})\n";
                    echo "<div style='color: green;'>" . htmlspecialchars($log_message) . "</div>";
                    flush();
                    
                    $created_count++;
                    
                } catch (Exception $e) {
                    if ($pdo->inTransaction()) {
                        $pdo->rollback();
                    }
                    $error_msg = "✗ ত্রুটি - শিক্ষার্থী ID {$student['id']}: " . $e->getMessage() . "\n";
                    echo "<div style='color: red;'>" . htmlspecialchars($error_msg) . "</div>";
                    flush();
                    $errors[] = $error_msg;
                }
                
                // Periodic flush to show progress
                if ($index % 5 == 0) {
                    echo "<script>document.getElementById('logOutput').scrollTop = document.getElementById('logOutput').scrollHeight;</script>";
                    flush();
                }
            }
            
            echo "</div>"; // Close log div
            
            echo "<div class='alert alert-" . (empty($errors) ? 'success' : 'warning') . " mt-3'>";
            echo "<h4>" . (empty($errors) ? '<i class="fas fa-check-circle"></i> সম্পূর্ণ!' : '<i class="fas fa-exclamation-triangle"></i> সম্পূর্ণ হয়েছে') . "</h4>";
            echo "<p><strong>তৈরি হয়েছে:</strong> $created_count টি অ্যাকাউন্ট</p>";
            echo "<p><strong>ত্রুটি:</strong> " . count($errors) . " টি</p>";
            
            if (!empty($errors)) {
                echo "<p class='text-muted'>কিছু অ্যাকাউন্ট তৈরি হয়নি। উপরের লগ দেখুন।</p>";
            }
            
            echo "<div class='mt-3'>";
            echo "<a href='?refresh=1' class='btn btn-primary me-2'>অবস্থা চেক করুন</a>";
            echo "<a href='users.php?role_filter=student&per_page=100' class='btn btn-success'>শিক্ষার্থী তালিকা দেখুন</a>";
            echo "</div>";
            echo "</div>";
            
        } else {
            echo "<div class='alert alert-warning'>";
            echo "<h4><i class='fas fa-exclamation-triangle'></i> অ্যাকাউন্ট সমস্যা সনাক্ত হয়েছে</h4>";
            echo "<p>$missing_count জন শিক্ষার্থীর ইউজার অ্যাকাউন্ট নেই।</p>";
            echo "<p>এক ক্লিকে সব অ্যাকাউন্ট তৈরি করুন:</p>";
            echo "</div>";
            
            echo "<form method='POST' onsubmit='return confirm(\"$missing_count জন শিক্ষার্থীর জন্য ইউজার অ্যাকাউন্ট তৈরি করতে চান?\");'>";
            echo "<button type='submit' name='fix_accounts' class='btn btn-fix w-100'>";
            echo "<i class='fas fa-bolt'></i> এখনই সব অ্যাকাউন্ট তৈরি করুন ($missing_count জন শিক্ষার্থী)";
            echo "</button>";
            echo "</form>";
            
            echo "<div class='mt-3 text-center'>";
            echo "<small class='text-muted'>সময় লাগবে: " . ceil($missing_count / 20) . "-" . ceil($missing_count / 10) . " মিনিট</small>";
            echo "</div>";
        }
    }
    
    // Auto-refresh
    if (isset($_GET['refresh'])) {
        echo "<script>setTimeout(function(){ location.href = '?'; }, 3000);</script>";
        echo "<div class='alert alert-info mt-3'>পেজ ৩ সেকেন্ডের মধ্যে রিফ্রেশ হবে...</div>";
    }
    
} catch (Exception $e) {
    echo "<div class='alert alert-danger'>";
    echo "<h4><i class='fas fa-exclamation-circle'></i> ত্রুটি</h4>";
    echo "<p>" . htmlspecialchars($e->getMessage()) . "</p>";
    echo "</div>";
}

echo "        </div>
    </div>
    
    <script src='https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js'></script>
</body>
</html>";
?>