<?php
// Enable error reporting for debugging the original error
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();

// Include access control functions
require_once '../includes/access_control.php';
require_once '../config/database.php';

// Check if user is logged in and is a teacher
require_teacher();

$user_role = $_SESSION['user_role'];
$user_id = $_SESSION['user_id'];
$user_name = $_SESSION['user_name'] ?? $_SESSION['username'] ?? 'শিক্ষক';

// Initialize messages
$success_message = '';
$error_message = '';

// Handle delete requests
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['delete_students'])) {
    $student_ids = $_POST['student_ids'] ?? [];

    if (!empty($student_ids) && is_array($student_ids)) {
        try {
            // Validate that teacher can delete these students (only from their assigned classes)
            $teacher_id = null;
            $stmt = $pdo->prepare("SELECT id FROM teachers WHERE user_id = ?");
            $stmt->execute([$user_id]);
            $teacher = $stmt->fetch();
            if ($teacher) {
                $teacher_id = $teacher['id'];
            }

            if ($teacher_id) {
                // Validate that teacher has access to all selected students
                $all_students_valid = true;
                foreach ($student_ids as $student_id) {
                    if (!teacher_has_student_access($teacher_id, $student_id)) {
                        $all_students_valid = false;
                        break;
                    }
                }

                if ($all_students_valid) {
                    // All students are valid, proceed with deletion
                    $pdo->beginTransaction();

                        // Soft delete students (set status to 'inactive')
                        $placeholders = str_repeat('?,', count($student_ids) - 1) . '?';
                        $stmt = $pdo->prepare("UPDATE students SET status = 'inactive', updated_at = NOW() WHERE id IN ($placeholders)");
                        $stmt->execute($student_ids);

                        $deleted_count = $stmt->rowCount();
                        $pdo->commit();

                        $success_message = "$deleted_count জন ছাত্র-ছাত্রী সফলভাবে মুছে ফেলা হয়েছে";
                    } else {
                        $error_message = 'আপনি কেবল আপনার নির্ধারিত ক্লাসের ছাত্র-ছাত্রীদের মুছে ফেলতে পারবেন';
                    }
                } else {
                    $error_message = 'আপনার কোন ক্লাসে নির্ধারিত ছাত্র-ছাত্রী নেই';
                }
            } else {
                $error_message = 'অবৈধ শিক্ষক অ্যাকাউন্ট';
            }
        } catch (Exception $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $error_message = 'ছাত্র-ছাত্রীদের মুছে ফেলতে সমস্যা হয়েছে: ' . $e->getMessage();
        }
    } else {
        $error_message = 'অনুগ্রহ করে মুছে ফেলার জন্য অন্তত একজন ছাত্র-ছাত্রী নির্বাচন করুন';
    }
}

// Only teachers can access this page
if ($user_role !== 'teacher') {
    header('Location: ../index.php');
    exit();
}

// Get teacher ID
$teacher_id = null;
$stmt = $pdo->prepare("SELECT id FROM teachers WHERE user_id = ?");
$stmt->execute([$user_id]);
$teacher = $stmt->fetch();
if ($teacher) {
    $teacher_id = $teacher['id'];
} else {
    // Redirect if not a valid teacher
    header('Location: dashboard.php');
    exit();
}

// Get teacher's assigned classes
$assigned_classes = [];
$assigned_class_ids = [];
if ($teacher_id) {
    $assigned_class_ids = get_teacher_assigned_classes($teacher_id);

    // If no classes are assigned, auto-assign the teacher to all available classes (temporary fix)
    if (empty($assigned_class_ids)) {
        try {
            // Auto-assign teacher to all active classes as primary teacher
            $stmt = $pdo->query("SELECT id FROM classes WHERE status = 'active'");
            $all_classes = $stmt->fetchAll(PDO::FETCH_COLUMN);

            if (!empty($all_classes)) {
                foreach ($all_classes as $class_id) {
                    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]);
                    } catch (Exception $e) {
                        // Ignore duplicate key errors
                    }
                }
                $assigned_class_ids = $all_classes;
                $success_message = "আপনাকে সব ক্লাসে অটো-অ্যাসাইন করা হয়েছে। এখন আপনি সব ছাত্র-ছাত্রী দেখতে পারবেন।";

                // Re-fetch assigned classes with details after auto-assignment
                $placeholders = str_repeat('?,', count($assigned_class_ids) - 1) . '?';
                $stmt = $pdo->prepare("
                    SELECT DISTINCT c.id, c.name, c.section, 'assigned' as assignment_type
                    FROM classes c
                    WHERE c.id IN ($placeholders) AND c.status = 'active'
                    ORDER BY c.name, c.section
                ");
                $stmt->execute($assigned_class_ids);
                $assigned_classes = $stmt->fetchAll();
            }
        } catch (Exception $e) {
            // Ignore errors during auto-assignment
        }
    } else {
        // Get detailed class information for already assigned classes
        $placeholders = str_repeat('?,', count($assigned_class_ids) - 1) . '?';
        $stmt = $pdo->prepare("
            SELECT DISTINCT c.id, c.name, c.section, 'assigned' as assignment_type
            FROM classes c
            WHERE c.id IN ($placeholders) AND c.status = 'active'
            ORDER BY c.name, c.section
        ");
        $stmt->execute($assigned_class_ids);
        $assigned_classes = $stmt->fetchAll();
    }
}

// Get class IDs for filtering
$class_ids = array_column($assigned_classes, 'id');

// Pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
$offset = ($page - 1) * $limit;

// Search and filter
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$class_filter = isset($_GET['class_id']) ? (int)$_GET['class_id'] : 0;

// Only allow filtering by assigned classes
if ($class_filter > 0 && !in_array($class_filter, $class_ids)) {
    $class_filter = 0;
}

// Sorting
$sort_by = isset($_GET['sort_by']) ? $_GET['sort_by'] : 'roll_number';
$sort_order = isset($_GET['sort_order']) ? $_GET['sort_order'] : 'ASC';

// Validate sort parameters
$allowed_sort_fields = ['first_name', 'last_name', 'student_id', 'roll_number', 'created_at'];
$allowed_sort_orders = ['ASC', 'DESC'];

if (!in_array($sort_by, $allowed_sort_fields)) {
    $sort_by = 'roll_number';
}
if (!in_array($sort_order, $allowed_sort_orders)) {
    $sort_order = 'ASC';
}

// Build query for teacher's students only
$where_conditions = ["s.status = 'active'"];
$params = [];

// Filter by teacher's assigned classes
if (!empty($class_ids)) {
    $placeholders = str_repeat('?,', count($class_ids) - 1) . '?';
    $where_conditions[] = "s.class_id IN ($placeholders)";
    $params = array_merge($params, $class_ids);
} else {
    // If no classes assigned, show no students
    $where_conditions[] = "1=0"; // Always false condition
}

// Search condition
if (!empty($search)) {
    $where_conditions[] = "(s.first_name LIKE ? OR s.last_name LIKE ? OR s.student_id LIKE ? OR s.roll_number LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

$where_clause = implode(' AND ', $where_conditions);

// Get total count
$count_sql = "SELECT COUNT(*) FROM students s LEFT JOIN classes c ON s.class_id = c.id WHERE $where_clause";
$count_stmt = $pdo->prepare($count_sql);
$count_stmt->execute($params);
$total_records = $count_stmt->fetchColumn();
$total_pages = ceil($total_records / $limit);

$order_clause = "";
if ($sort_by && $sort_order) {
    $order_clause = "ORDER BY $sort_by $sort_order";
}

// ORIGINAL BROKEN QUERY - This will cause HTTP 500 error
// The issue: trying to select 'session' from students table, but it doesn't exist there anymore
$sql = "SELECT s.*, c.name as class_name, c.section as class_section, s.session FROM students s LEFT JOIN classes c ON s.class_id = c.id WHERE $where_clause $order_clause LIMIT ? OFFSET ?";
$stmt = $pdo->prepare($sql);
$execute_params = array_merge($params, [$limit, $offset]);
$stmt->execute($execute_params);
$students = $stmt->fetchAll();

// Get classes for dropdown (only assigned classes)
if (!empty($class_ids)) {
    $placeholders = str_repeat('?,', count($class_ids) - 1) . '?';
    $classes_stmt = $pdo->prepare("SELECT id, name, section FROM classes WHERE id IN ($placeholders) AND status = 'active' ORDER BY name, section");
    $classes_stmt->execute($class_ids);
} else {
    // If no class IDs, just get an empty result
    $classes_stmt = $pdo->prepare("SELECT id, name, section FROM classes WHERE id IN (0) AND status = 'active' ORDER BY name, section");
    $classes_stmt->execute();
}
$classes = $classes_stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>আমার ছাত্র-ছাত্রী - DEBUG: Original Error Version</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="../assets/css/jessoreboard-theme.css" rel="stylesheet">
    <style>
        .student-photo {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            object-fit: cover;
        }
        .no-photo {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #6c757d;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
        }
        .table-responsive {
            max-height: 600px;
            overflow-y: auto;
        }
        .error-notice {
            background: #ffebee;
            border: 1px solid #f44336;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-danger">
        <div class="container-fluid">
            <a class="navbar-brand" href="my_students.php">
                <i class="fas fa-bug"></i> DEBUG: Original Error Version
            </a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="my_students.php">
                    <i class="fas fa-check"></i> Go to Fixed Version
                </a>
            </div>
        </div>
    </nav>
    <div class="container-fluid mt-4">
        <div class="row">
            <div class="col-12">
                <div class="error-notice">
                    <h4 class="text-danger"><i class="fas fa-exclamation-triangle"></i> DEBUG MODE: This page reproduces the original HTTP 500 error</h4>
                    <p><strong>Problem:</strong> The code tries to select <code>s.session</code> from the students table, but this column doesn't exist anymore. The database was updated to use <code>session_id</code> with a foreign key to <code>academic_sessions</code> table.</p>
                    <p><strong>Expected Result:</strong> This page should show HTTP 500 error because of the SQL query error.</p>
                    <p><strong>Fixed Version:</strong> <a href="my_students.php">Click here to see the working version</a></p>
                </div>
                <h2><i class="fas fa-user-graduate"></i> আমার ছাত্র-ছাত্রী (Original Error Version)</h2>
                <p class="text-muted">এই পেজটি মূল ত্রুটি প্রদর্শন করে - HTTP 500 error দেখানো উচিত</p>
            </div>
        </div>

        <!-- This content won't load due to the SQL error above -->
        <div class="row">
            <div class="col-12">
                <p>যদি এই লেখাটি দেখা যায়, তাহলে ত্রুটি ঠিক হয়ে গেছে। নইলে HTTP 500 error দেখাবে।</p>
                <p>If you can see this text, the error has been fixed. Otherwise, you'll see HTTP 500 error.</p>
            </div>
        </div>
    </div>

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