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

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

echo "<!DOCTYPE html>";
echo "<html lang='bn'>";
echo "<head>";
echo "<meta charset='UTF-8'>";
echo "<title>শিক্ষার্থী সেশন ও গ্রুপ আপডেট</title>";
echo "<link href='https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css' rel='stylesheet'>";
echo "<link href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css' rel='stylesheet'>";
echo "</head>";
echo "<body class='bg-light'>";

echo "<div class='container mt-4'>";
echo "<div class='row justify-content-center'>";
echo "<div class='col-md-10'>";

echo "<div class='card'>";
echo "<div class='card-header bg-warning text-dark'>";
echo "<h3><i class='fas fa-tools'></i> শিক্ষার্থী সেশন ও গ্রুপ আপডেট</h3>";
echo "</div>";
echo "<div class='card-body'>";

try {
    $pdo->beginTransaction();
    
    // Check students without session or group_name
    echo "<h5>১. সমস্যাযুক্ত শিক্ষার্থী চেক করা হচ্ছে...</h5>";
    
    $stmt = $pdo->query("
        SELECT COUNT(*) as total,
               SUM(CASE WHEN session IS NULL OR session = '' THEN 1 ELSE 0 END) as no_session,
               SUM(CASE WHEN group_name IS NULL OR group_name = '' THEN 1 ELSE 0 END) as no_group
        FROM students 
        WHERE status = 'active'
    ");
    $stats = $stmt->fetch();
    
    echo "<div class='alert alert-info'>";
    echo "<p><strong>মোট active শিক্ষার্থী:</strong> {$stats['total']} জন</p>";
    echo "<p><strong>সেশন ছাড়া:</strong> {$stats['no_session']} জন</p>";
    echo "<p><strong>গ্রুপ ছাড়া:</strong> {$stats['no_group']} জন</p>";
    echo "</div>";
    
    if ($stats['no_session'] == 0 && $stats['no_group'] == 0) {
        echo "<div class='alert alert-success'>";
        echo "<h5><i class='fas fa-check-circle'></i> সব শিক্ষার্থীর সেশন ও গ্রুপ ঠিক আছে!</h5>";
        echo "<p>কোন আপডেটের প্রয়োজন নেই।</p>";
        echo "</div>";
    } else {
        echo "<h5>২. শিক্ষার্থী আপডেট করা হচ্ছে...</h5>";
        
        // Get all students without session or group
        $stmt = $pdo->query("
            SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number, 
                   s.session, s.group_name, s.class_id,
                   c.name as class_name, c.section as class_section
            FROM students s 
            LEFT JOIN classes c ON s.class_id = c.id 
            WHERE s.status = 'active' 
            AND (s.session IS NULL OR s.session = '' OR s.group_name IS NULL OR s.group_name = '')
            ORDER BY s.id
        ");
        $students = $stmt->fetchAll();
        
        $updated_count = 0;
        
        foreach ($students as $student) {
            $new_session = $student['session'];
            $new_group = $student['group_name'];
            
            // Set default session if empty
            if (empty($new_session)) {
                $new_session = '2024'; // Default current session
            }
            
            // Set default group based on class if empty
            if (empty($new_group)) {
                $class_name = $student['class_name'];
                
                // Assign group based on class level
                if (in_array($class_name, ['৬ষ্ঠ', '৭ম', '৮ম'])) {
                    $new_group = 'সাধারণ';
                } elseif (in_array($class_name, ['৯ম', '১০ম'])) {
                    // For SSC level, assign based on student ID pattern or randomly
                    $groups = ['বিজ্ঞান', 'মানবিক', 'ব্যবসায় শিক্ষা'];
                    $index = ($student['id'] % 3); // Simple distribution
                    $new_group = $groups[$index];
                } elseif (in_array($class_name, ['১১শ', '১২শ'])) {
                    // For HSC level, assign based on student ID pattern or randomly
                    $groups = ['বিজ্ঞান', 'মানবিক', 'ব্যবসায় শিক্ষা'];
                    $index = ($student['id'] % 3); // Simple distribution
                    $new_group = $groups[$index];
                } else {
                    $new_group = 'সাধারণ';
                }
            }
            
            // Update student
            $stmt = $pdo->prepare("
                UPDATE students 
                SET session = ?, group_name = ? 
                WHERE id = ?
            ");
            $stmt->execute([$new_session, $new_group, $student['id']]);
            
            echo "<p class='text-success'>";
            echo "<i class='fas fa-check'></i> ";
            echo "{$student['first_name']} {$student['last_name']} ";
            echo "({$student['class_name']}-{$student['class_section']}) ";
            echo "→ সেশন: <strong>$new_session</strong>, গ্রুপ: <strong>$new_group</strong>";
            echo "</p>";
            
            $updated_count++;
        }
        
        echo "<div class='alert alert-success mt-3'>";
        echo "<h5><i class='fas fa-check-circle'></i> আপডেট সম্পন্ন!</h5>";
        echo "<p><strong>$updated_count</strong> জন শিক্ষার্থীর তথ্য আপডেট করা হয়েছে।</p>";
        echo "</div>";
    }
    
    // Show updated statistics
    echo "<h5>৩. আপডেটের পর পরিসংখ্যান:</h5>";
    
    $stmt = $pdo->query("
        SELECT 
            session,
            group_name,
            COUNT(*) as count
        FROM students 
        WHERE status = 'active' 
        AND session IS NOT NULL 
        AND session != ''
        AND group_name IS NOT NULL 
        AND group_name != ''
        GROUP BY session, group_name
        ORDER BY session, group_name
    ");
    $final_stats = $stmt->fetchAll();
    
    if (count($final_stats) > 0) {
        echo "<div class='table-responsive'>";
        echo "<table class='table table-striped'>";
        echo "<thead>";
        echo "<tr><th>সেশন</th><th>গ্রুপ</th><th>শিক্ষার্থী সংখ্যা</th></tr>";
        echo "</thead>";
        echo "<tbody>";
        
        foreach ($final_stats as $stat) {
            echo "<tr>";
            echo "<td><strong>{$stat['session']}</strong></td>";
            echo "<td>{$stat['group_name']}</td>";
            echo "<td><span class='badge bg-primary'>{$stat['count']} জন</span></td>";
            echo "</tr>";
        }
        
        echo "</tbody></table>";
        echo "</div>";
    }
    
    $pdo->commit();
    
    echo "<hr>";
    echo "<div class='alert alert-success'>";
    echo "<h5><i class='fas fa-thumbs-up'></i> সব কিছু ঠিক হয়ে গেছে!</h5>";
    echo "<p>এখন বিষয় নির্বাচন সিস্টেম সঠিকভাবে কাজ করবে।</p>";
    echo "<div class='mt-3'>";
    echo "<a href='subjects/subject_selection.php' class='btn btn-success me-2'>";
    echo "<i class='fas fa-tasks'></i> বিষয় নির্বাচন ব্যবহার করুন";
    echo "</a>";
    echo "<a href='debug_students.php' class='btn btn-info me-2'>";
    echo "<i class='fas fa-bug'></i> আবার চেক করুন";
    echo "</a>";
    echo "<a href='index.php' class='btn btn-primary'>";
    echo "<i class='fas fa-home'></i> হোমে ফিরে যান";
    echo "</a>";
    echo "</div>";
    echo "</div>";
    
} catch (Exception $e) {
    $pdo->rollBack();
    echo "<div class='alert alert-danger'>";
    echo "<h5><i class='fas fa-exclamation-triangle'></i> ত্রুটি!</h5>";
    echo "<p>আপডেট করতে সমস্যা: " . $e->getMessage() . "</p>";
    echo "</div>";
}

echo "</div>";
echo "</div>";

echo "</div>";
echo "</div>";
echo "</div>";

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