<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once 'config/database.php';
require_once 'includes/access_control.php';

echo "<h1>Auto-Assign Teacher to Classes</h1>";

// Check if user is logged in and is a teacher
if (!isset($_SESSION['user_id']) || !is_teacher()) {
    echo "<p style='color: red;'>❌ You must be logged in as a teacher to use this tool</p>";
    exit;
}

echo "<p>✓ User is logged in as teacher</p>";
echo "<p>User ID: " . $_SESSION['user_id'] . "</p>";
echo "<p>User Name: " . ($_SESSION['user_name'] ?? $_SESSION['username'] ?? 'Unknown') . "</p>";

// Get teacher ID
$stmt = $pdo->prepare("SELECT id, first_name, last_name FROM teachers WHERE user_id = ?");
$stmt->execute([$_SESSION['user_id']]);
$teacher = $stmt->fetch();

if (!$teacher) {
    echo "<p style='color: red;'>❌ No teacher record found for this user. You need to be registered as a teacher first.</p>";
    exit;
}

$teacher_id = $teacher['id'];
echo "<p>✓ Teacher ID: $teacher_id ({$teacher['first_name']} {$teacher['last_name']})</p>";

// Check current class assignments
$assigned_class_ids = get_teacher_assigned_classes($teacher_id);
echo "<p>Currently assigned to " . count($assigned_class_ids) . " classes</p>";

if (!empty($assigned_class_ids)) {
    echo "<p>Teacher is already assigned to classes. Here are the classes:</p>";
    $placeholders = str_repeat('?,', count($assigned_class_ids) - 1) . '?';
    $stmt = $pdo->prepare("SELECT id, name, section FROM classes WHERE id IN ($placeholders) AND status = 'active'");
    $stmt->execute($assigned_class_ids);
    $assigned_classes = $stmt->fetchAll();
    
    foreach ($assigned_classes as $class) {
        echo "<p>- {$class['name']} {$class['section']} (ID: {$class['id']})</p>";
    }
    
    // Check students in assigned classes
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM students WHERE class_id IN ($placeholders) AND status = 'active'");
    $stmt->execute($assigned_class_ids);
    $student_count = $stmt->fetch();
    
    echo "<p>Students in assigned classes: {$student_count['count']}</p>";
    
    echo "<p style='color: green;'>✅ Teacher already has class assignments. The my_students.php page should work.</p>";
    echo "<p><a href='teachers/my_students.php' style='font-size: 16px;'>Go to My Students Page</a></p>";
    exit;
}

// If no assignments, show available classes and offer to assign
echo "<p style='color: orange;'>⚠️ Teacher has no class assignments</p>";

// Get all active classes
$stmt = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active'");
$all_classes = $stmt->fetchAll();

if (empty($all_classes)) {
    echo "<p style='color: red;'>❌ No active classes found in the system</p>";
    echo "<p>You need to create classes first in the admin panel.</p>";
    exit;
}

echo "<p>Available classes (" . count($all_classes) . "):</p>";
foreach ($all_classes as $class) {
    echo "<p>- {$class['name']} {$class['section']} (ID: {$class['id']})</p>";
}

// Auto-assign teacher to all active classes
echo "<h2>Auto-Assigning Teacher to All Classes</h2>";

$assigned_count = 0;
foreach ($all_classes as $class) {
    try {
        $stmt = $pdo->prepare("
            INSERT IGNORE INTO class_teachers (class_id, teacher_id, assignment_type, status, assigned_at)
            VALUES (?, ?, 'primary', 'active', NOW())
        ");
        $stmt->execute([$class['id'], $teacher_id]);
        
        if ($stmt->rowCount() > 0) {
            $assigned_count++;
        }
    } catch (Exception $e) {
        echo "<p style='color: red;'>Error assigning to class {$class['id']}: " . $e->getMessage() . "</p>";
    }
}

echo "<p style='color: green;'>✅ Auto-assignment completed!</p>";
echo "<p>Assigned teacher to $assigned_count classes</p>";

// Verify assignments
$assigned_class_ids = get_teacher_assigned_classes($teacher_id);
echo "<p>Now assigned to " . count($assigned_class_ids) . " classes</p>";

// Check if students exist in these classes
if (!empty($assigned_class_ids)) {
    $placeholders = str_repeat('?,', count($assigned_class_ids) - 1) . '?';
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM students WHERE class_id IN ($placeholders) AND status = 'active'");
    $stmt->execute($assigned_class_ids);
    $student_count = $stmt->fetch();
    
    echo "<p>Students in assigned classes: {$student_count['count']}</p>";
    
    if ($student_count['count'] > 0) {
        echo "<p style='color: green;'>🎉 Success! The teacher should now see students on the my_students.php page.</p>";
    } else {
        echo "<p style='color: orange;'>⚠️ Teacher has classes assigned but no students in those classes.</p>";
        echo "<p>You may need to add students to these classes.</p>";
    }
}

echo "<p><a href='teachers/my_students.php' style='font-size: 16px;'>Go to My Students Page</a></p>";
echo "<p><a href='teachers/dashboard.php' style='font-size: 16px;'>Go to Teacher Dashboard</a></p>";
?>