<?php
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'] ?? 'শিক্ষক';

// 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();
}

$success_message = '';
$error_message = '';

// Get student ID from URL
$student_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($student_id <= 0) {
    header('Location: my_students.php');
    exit();
}

// Get student data
$stmt = $pdo->prepare("SELECT * FROM students WHERE id = ?");
$stmt->execute([$student_id]);
$student = $stmt->fetch();

if (!$student) {
    header('Location: my_students.php');
    exit();
}

// Check if teacher has access to this student (student must be in teacher's assigned classes)
$assigned_classes = [];
if ($teacher_id) {
    // Get classes where this teacher is assigned as class teacher
    $stmt = $pdo->prepare("
        SELECT c.id, c.name, c.section
        FROM classes c
        WHERE c.class_teacher_id = ? AND c.status = 'active'
        ORDER BY c.name, c.section
    ");
    $stmt->execute([$teacher_id]);
    $assigned_classes = $stmt->fetchAll();
    
    // If no classes found through class teacher assignment, check if they teach subjects
    if (empty($assigned_classes)) {
        $stmt = $pdo->prepare("
            SELECT DISTINCT c.id, c.name, c.section
            FROM classes c
            JOIN class_subjects cs ON c.id = cs.class_id
            WHERE cs.teacher_id = ? AND c.status = 'active'
            ORDER BY c.name, c.section
        ");
        $stmt->execute([$teacher_id]);
        $assigned_classes = $stmt->fetchAll();
    }
}

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

// Check if student is in one of teacher's assigned classes
if (!in_array($student['class_id'], $class_ids)) {
    $error_message = 'আপনি এই ছাত্র-ছাত্রীর তথ্য সম্পাদনা করতে পারবেন না।';
}

// Get classes for dropdown (only assigned classes)
$classes = $assigned_classes;

// Get academic sessions
$stmt = $pdo->query("SELECT session_name FROM academic_sessions WHERE status = 'active' ORDER BY session_name DESC");
$sessions = $stmt->fetchAll();

// Get student groups
$stmt = $pdo->query("SELECT group_name, group_code, description FROM student_groups WHERE status = 'active' ORDER BY group_name");
$groups = $stmt->fetchAll();

// Get all subjects for the student's class
$class_subjects_map = [];
if (!empty($class_ids)) {
    $placeholders = str_repeat('?,', count($class_ids) - 1) . '?';
    $stmt = $pdo->prepare("
        SELECT cs.class_id, cs.subject_id, s.name, s.code 
        FROM class_subjects cs 
        JOIN subjects s ON cs.subject_id = s.id 
        WHERE cs.class_id IN ($placeholders) AND s.status = 'active'
        ORDER BY s.name
    ");
    $stmt->execute($class_ids);
    $class_subjects_data = $stmt->fetchAll();
    foreach ($class_subjects_data as $cs) {
        $class_subjects_map[$cs['class_id']][] = $cs;
    }
}

// Get student's current subjects
$stmt = $pdo->prepare("SELECT subject_id FROM student_subjects WHERE student_id = ?");
$stmt->execute([$student_id]);
$current_subjects = $stmt->fetchAll(PDO::FETCH_COLUMN);

if ($_SERVER['REQUEST_METHOD'] == 'POST' && !$error_message) {
    $first_name = trim($_POST['first_name']);
    $last_name = trim($_POST['last_name']);
    $father_name = trim($_POST['father_name'] ?? '');
    $mother_name = trim($_POST['mother_name'] ?? '');
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);
    $address = trim($_POST['address']);
    $date_of_birth = $_POST['date_of_birth'];
    $gender = $_POST['gender'];
    $religion = trim($_POST['religion'] ?? ''); // Add religion field
    $blood_group = $_POST['blood_group'] ?? null;
    $class_id = $_POST['class_id'];
    $session = $_POST['session'];
    $group_name = $_POST['group_name'];
    $roll_number = $_POST['roll_number'];
    $previous_class = trim($_POST['previous_class'] ?? '');
    $previous_school = trim($_POST['previous_school'] ?? '');
    $admission_date = $_POST['admission_date'];
    $guardian_name = trim($_POST['guardian_name']);
    $guardian_phone = trim($_POST['guardian_phone']);
    $guardian_email = trim($_POST['guardian_email']);
    $status = $_POST['status'];
    $scholarship = $_POST['scholarship'] ?? 'no';
    $selected_subjects = $_POST['subjects'] ?? [];
    
    // Validation
    if (empty($first_name) || empty($last_name) || empty($class_id) || empty($session) || empty($roll_number)) {
        $error_message = 'প্রয়োজনীয় ক্ষেত্রগুলো পূরণ করুন (নাম, ক্লাস, সেশন, রোল নম্বর)';
    } else if (!in_array($class_id, $class_ids)) {
        // Additional validation to ensure teacher can only assign student to their classes
        $error_message = 'আপনি এই ক্লাসে ছাত্র-ছাত্রী নিয়োগ করতে পারবেন না।';
    } else {
        try {
            $pdo->beginTransaction();
            
            // Check if roll number already exists in the class, session and group (excluding current student)
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM students WHERE class_id = ? AND session = ? AND COALESCE(group_name, '') = ? AND roll_number = ? AND status = 'active' AND id != ?");
            $stmt->execute([$class_id, $session, $group_name ?: '', $roll_number, $student_id]);
            if ($stmt->fetchColumn() > 0) {
                $group_text = $group_name ? " ($group_name গ্রুপে)" : '';
                throw new Exception("এই ক্লাস ও সেশনে$group_text এই রোল নম্বর ইতিমধ্যে ব্যবহৃত হয়েছে");
            }
            
            // Update user account if email is provided and changed
            if (!empty($email) && $email != $student['email']) {
                // Validate email format
                if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                    throw new Exception("ইমেইল ঠিকানা সঠিক নয়");
                }
                
                // Check if email already exists (but allow if it's NULL or empty)
                $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email = ? AND email IS NOT NULL AND email != '' AND id != (SELECT user_id FROM students WHERE id = ?)");
                $stmt->execute([$email, $student_id]);
                if ($stmt->fetchColumn() > 0) {
                    throw new Exception("এই ইমেইল ঠিকানা ইতিমধ্যে ব্যবহৃত হয়েছে");
                }
                
                // Update user email if user exists
                if ($student['user_id']) {
                    $stmt = $pdo->prepare("UPDATE users SET email = ? WHERE id = ?");
                    $stmt->execute([$email, $student['user_id']]);
                }
            }
            
            // Handle photo upload
            $photo_path = $student['photo']; // Keep existing photo by default
            if (isset($_FILES['photo']) && $_FILES['photo']['error'] == 0) {
                $upload_dir = '../uploads/students/';
                if (!is_dir($upload_dir)) {
                    mkdir($upload_dir, 0755, true);
                }
                
                $file_extension = strtolower(pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION));
                $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif'];
                
                if (in_array($file_extension, $allowed_extensions)) {
                    $new_filename = 'student_' . $student_id . '_' . time() . '.' . $file_extension;
                    $upload_path = $upload_dir . $new_filename;
                    
                    if (move_uploaded_file($_FILES['photo']['tmp_name'], $upload_path)) {
                        // Delete old photo if exists
                        if ($student['photo'] && file_exists('../' . $student['photo'])) {
                            unlink('../' . $student['photo']);
                        }
                        $photo_path = 'uploads/students/' . $new_filename;
                    }
                }
            }
            
            // Update student information
            $stmt = $pdo->prepare("
                UPDATE students SET 
                first_name = ?, last_name = ?, father_name = ?, mother_name = ?, 
                email = ?, phone = ?, address = ?, date_of_birth = ?, gender = ?, religion = ?,
                blood_group = ?, class_id = ?, session = ?, group_name = ?, 
                roll_number = ?, previous_class = ?, previous_school = ?,
                admission_date = ?, guardian_name = ?, guardian_phone = ?, 
                guardian_email = ?, status = ?, scholarship = ?,
                updated_at = NOW()
                WHERE id = ?
            ");
            $stmt->execute([
                $first_name, $last_name, $father_name, $mother_name,
                $email, $phone, $address, $date_of_birth, $gender, $religion,
                $blood_group, $class_id, $session, $group_name,
                $roll_number, $previous_class, $previous_school,
                $admission_date, $guardian_name, $guardian_phone,
                $guardian_email, $status, $scholarship,
                $student_id
            ]);
            
            // Update student subjects
            // First, delete existing subjects
            $stmt = $pdo->prepare("DELETE FROM student_subjects WHERE student_id = ?");
            $stmt->execute([$student_id]);
            
            // Then, insert new subjects
            if (!empty($selected_subjects)) {
                $stmt = $pdo->prepare("INSERT INTO student_subjects (student_id, subject_id, is_fourth_subject) VALUES (?, ?, ?)");
                foreach ($selected_subjects as $subject_id) {
                    $stmt->execute([$student_id, $subject_id, 0]);
                }
            }
            
            $pdo->commit();
            $success_message = 'ছাত্র-ছাত্রীর তথ্য সফলভাবে আপডেট হয়েছে';
            
            // Refresh student data
            $stmt = $pdo->prepare("SELECT * FROM students WHERE id = ?");
            $stmt->execute([$student_id]);
            $student = $stmt->fetch();
            
            // Refresh current subjects
            $stmt = $pdo->prepare("SELECT subject_id FROM student_subjects WHERE student_id = ?");
            $stmt->execute([$student_id]);
            $current_subjects = $stmt->fetchAll(PDO::FETCH_COLUMN);
            
        } catch (Exception $e) {
            $pdo->rollBack();
            $error_message = $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ছাত্র-ছাত্রী সম্পাদনা - স্কুল ম্যানেজমেন্ট সিস্টেম</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>
        .form-section {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .student-photo {
            width: 150px;
            height: 150px;
            object-fit: cover;
            border: 3px solid #dee2e6;
        }
        .no-photo {
            width: 150px;
            height: 150px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #e9ecef;
            border: 3px solid #dee2e6;
            font-size: 4rem;
            color: #6c757d;
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="<?php echo ($user_role == 'teacher') ? 'dashboard.php' : '../index.php'; ?>">
                <i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট সিস্টেম
            </a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="<?php echo ($user_role == 'teacher') ? 'my_students.php' : '../students/list.php'; ?>">
                    <i class="fas fa-arrow-left"></i> ছাত্র-ছাত্রী তালিকা
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-user-edit"></i> ছাত্র-ছাত্রী সম্পাদনা</h5>
                    </div>
                    <div class="card-body">
                        <?php if ($success_message): ?>
                            <div class="alert alert-success alert-dismissible fade show" role="alert">
                                <i class="fas fa-check-circle"></i> <?php echo $success_message; ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        <?php endif; ?>
                        <?php if ($error_message): ?>
                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                <i class="fas fa-exclamation-triangle"></i> <?php echo $error_message; ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        <?php endif; ?>

                        <?php if ($student && !$error_message): ?>
                        <form method="POST" action="" enctype="multipart/form-data" class="needs-validation" novalidate>
                            <div class="row">
                                <!-- Student Photo -->
                                <div class="col-md-3 mb-3">
                                    <div class="text-center">
                                        <?php if (!empty($student['photo']) && file_exists('../' . $student['photo'])): ?>
                                            <img src="../<?php echo $student['photo']; ?>" alt="ছাত্র/ছাত্রীর ছবি" class="student-photo rounded">
                                        <?php else: ?>
                                            <div class="no-photo rounded">
                                                <i class="fas fa-user"></i>
                                            </div>
                                        <?php endif; ?>
                                        <div class="mt-2">
                                            <label for="photo" class="form-label">ছবি পরিবর্তন করুন</label>
                                            <input type="file" class="form-control" id="photo" name="photo" accept="image/*">
                                        </div>
                                    </div>
                                </div>

                                <!-- Basic Information -->
                                <div class="col-md-9">
                                    <div class="form-section">
                                        <h6><i class="fas fa-user"></i> মৌলিক তথ্য</h6>
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label for="first_name" class="form-label">নাম (প্রথম) <span class="text-danger">*</span></label>
                                                <input type="text" class="form-control" id="first_name" name="first_name" value="<?php echo htmlspecialchars($student['first_name']); ?>" required>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label for="last_name" class="form-label">নাম (শেষ) <span class="text-danger">*</span></label>
                                                <input type="text" class="form-control" id="last_name" name="last_name" value="<?php echo htmlspecialchars($student['last_name']); ?>" required>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label for="father_name" class="form-label">পিতার নাম</label>
                                                <input type="text" class="form-control" id="father_name" name="father_name" value="<?php echo htmlspecialchars($student['father_name']); ?>">
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label for="mother_name" class="form-label">মাতার নাম</label>
                                                <input type="text" class="form-control" id="mother_name" name="mother_name" value="<?php echo htmlspecialchars($student['mother_name']); ?>">
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label for="date_of_birth" class="form-label">জন্ম তারিখ</label>
                                                <input type="date" class="form-control" id="date_of_birth" name="date_of_birth" value="<?php echo $student['date_of_birth']; ?>">
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label for="religion" class="form-label">ধর্ম</label>
                                                <select class="form-select" id="religion" name="religion">
                                                    <option value="">নির্বাচন করুন</option>
                                                    <option value="islam" <?php echo ($student['religion'] == 'islam') ? 'selected' : ''; ?>>ইসলাম</option>
                                                    <option value="hinduism" <?php echo ($student['religion'] == 'hinduism') ? 'selected' : ''; ?>>হিন্দু</option>
                                                    <option value="buddhism" <?php echo ($student['religion'] == 'buddhism') ? 'selected' : ''; ?>>বৌদ্ধ</option>
                                                    <option value="christianity" <?php echo ($student['religion'] == 'christianity') ? 'selected' : ''; ?>>খ্রিস্টান</option>
                                                    <option value="other" <?php echo ($student['religion'] == 'other') ? 'selected' : ''; ?>>অন্যান্য</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label for="gender" class="form-label">লিঙ্গ</label>
                                                <select class="form-select" id="gender" name="gender">
                                                    <option value="">নির্বাচন করুন</option>
                                                    <option value="male" <?php echo ($student['gender'] == 'male') ? 'selected' : ''; ?>>পুরুষ</option>
                                                    <option value="female" <?php echo ($student['gender'] == 'female') ? 'selected' : ''; ?>>মহিলা</option>
                                                    <option value="other" <?php echo ($student['gender'] == 'other') ? 'selected' : ''; ?>>অন্যান্য</option>
                                                </select>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label for="blood_group" class="form-label">রক্তের গ্রুপ</label>
                                                <select class="form-select" id="blood_group" name="blood_group">
                                                    <option value="">নির্বাচন করুন</option>
                                                    <option value="A+" <?php echo ($student['blood_group'] == 'A+') ? 'selected' : ''; ?>>A+</option>
                                                    <option value="A-" <?php echo ($student['blood_group'] == 'A-') ? 'selected' : ''; ?>>A-</option>
                                                    <option value="B+" <?php echo ($student['blood_group'] == 'B+') ? 'selected' : ''; ?>>B+</option>
                                                    <option value="B-" <?php echo ($student['blood_group'] == 'B-') ? 'selected' : ''; ?>>B-</option>
                                                    <option value="O+" <?php echo ($student['blood_group'] == 'O+') ? 'selected' : ''; ?>>O+</option>
                                                    <option value="O-" <?php echo ($student['blood_group'] == 'O-') ? 'selected' : ''; ?>>O-</option>
                                                    <option value="AB+" <?php echo ($student['blood_group'] == 'AB+') ? 'selected' : ''; ?>>AB+</option>
                                                    <option value="AB-" <?php echo ($student['blood_group'] == 'AB-') ? 'selected' : ''; ?>>AB-</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label for="scholarship" class="form-label">উপবৃত্তি</label>
                                                <select class="form-select" id="scholarship" name="scholarship">
                                                    <option value="no" <?php echo ($student['scholarship'] == 'no') ? 'selected' : ''; ?>>না</option>
                                                    <option value="yes" <?php echo ($student['scholarship'] == 'yes') ? 'selected' : ''; ?>>হ্যাঁ</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Contact Information -->
                                    <div class="form-section">
                                        <h6><i class="fas fa-phone"></i> যোগাযোগের তথ্য</h6>
                                        <div class="row">
                                            <div class="col-md-12">
                                                <table class="table table-bordered">
                                                    <tr>
                                                        <td>
                                                            <label for="email" class="form-label">ইমেইল</label>
                                                            <input type="email" class="form-control" id="email" name="email" value="<?php echo htmlspecialchars($student['email']); ?>">
                                                        </td>
                                                        <td>
                                                            <label for="phone" class="form-label">ফোন</label>
                                                            <input type="text" class="form-control" id="phone" name="phone" value="<?php echo htmlspecialchars($student['phone']); ?>">
                                                        </td>
                                                        <td>
                                                            <label for="guardian_name" class="form-label">অভিভাবকের নাম</label>
                                                            <input type="text" class="form-control" id="guardian_name" name="guardian_name" value="<?php echo htmlspecialchars($student['guardian_name']); ?>">
                                                        </td>
                                                        <td>
                                                            <label for="guardian_phone" class="form-label">অভিভাবকের ফোন</label>
                                                            <input type="text" class="form-control" id="guardian_phone" name="guardian_phone" value="<?php echo htmlspecialchars($student['guardian_phone']); ?>">
                                                        </td>
                                                    </tr>
                                                    <tr>
                                                        <td>
                                                            <label for="guardian_email" class="form-label">অভিভাবকের ইমেইল</label>
                                                            <input type="email" class="form-control" id="guardian_email" name="guardian_email" value="<?php echo htmlspecialchars($student['guardian_email']); ?>">
                                                        </td>
                                                        <td colspan="3">
                                                            <label for="address" class="form-label">ঠিকানা</label>
                                                            <textarea class="form-control" id="address" name="address" rows="2"><?php echo htmlspecialchars($student['address']); ?></textarea>
                                                        </td>
                                                    </tr>
                                                </table>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Academic Information -->
                                    <div class="form-section">
                                        <h6><i class="fas fa-graduation-cap"></i> একাডেমিক তথ্য</h6>
                                        <div class="row">
                                            <div class="col-md-12">
                                                <table class="table table-bordered">
                                                    <tr>
                                                        <td>
                                                            <label for="class_id" class="form-label">ক্লাস <span class="text-danger">*</span></label>
                                                            <select class="form-select" id="class_id" name="class_id" required>
                                                                <option value="">নির্বাচন করুন</option>
                                                                <?php foreach ($classes as $class): ?>
                                                                    <option value="<?php echo $class['id']; ?>" <?php echo ($student['class_id'] == $class['id']) ? 'selected' : ''; ?>>
                                                                        <?php echo htmlspecialchars($class['name'] . ' - ' . $class['section']); ?>
                                                                    </option>
                                                                <?php endforeach; ?>
                                                            </select>
                                                        </td>
                                                        <td>
                                                            <label for="session" class="form-label">সেশন <span class="text-danger">*</span></label>
                                                            <select class="form-select" id="session" name="session" required>
                                                                <option value="">নির্বাচন করুন</option>
                                                                <?php foreach ($sessions as $sess): ?>
                                                                    <option value="<?php echo $sess['session_name']; ?>" <?php echo ($student['session'] == $sess['session_name']) ? 'selected' : ''; ?>>
                                                                        <?php echo htmlspecialchars($sess['session_name']); ?>
                                                                    </option>
                                                                <?php endforeach; ?>
                                                            </select>
                                                        </td>
                                                        <td>
                                                            <label for="roll_number" class="form-label">রোল নম্বর <span class="text-danger">*</span></label>
                                                            <input type="text" class="form-control" id="roll_number" name="roll_number" value="<?php echo htmlspecialchars($student['roll_number']); ?>" required>
                                                        </td>
                                                        <td>
                                                            <label for="group_name" class="form-label">গ্রুপ</label>
                                                            <select class="form-select" id="group_name" name="group_name">
                                                                <option value="">নির্বাচন করুন</option>
                                                                <option value="" <?php echo (empty($student['group_name'])) ? 'selected' : ''; ?>>কোন গ্রুপ নেই</option>
                                                                <?php foreach ($groups as $group): ?>
                                                                    <option value="<?php echo $group['group_name']; ?>" <?php echo ($student['group_name'] == $group['group_name']) ? 'selected' : ''; ?>>
                                                                        <?php echo htmlspecialchars($group['group_name']); ?>
                                                                    </option>
                                                                <?php endforeach; ?>
                                                            </select>
                                                        </td>
                                                    </tr>
                                                    <tr>
                                                        <td>
                                                            <label for="admission_date" class="form-label">ভর্তি তারিখ</label>
                                                            <input type="date" class="form-control" id="admission_date" name="admission_date" value="<?php echo $student['admission_date']; ?>">
                                                        </td>
                                                        <td>
                                                            <label for="previous_class" class="form-label">পূর্ববর্তী শ্রেণি</label>
                                                            <input type="text" class="form-control" id="previous_class" name="previous_class" value="<?php echo htmlspecialchars($student['previous_class'] ?? ''); ?>" placeholder="উদাহরণ: পঞ্চম শ্রেণী">
                                                        </td>
                                                        <td>
                                                            <label for="previous_school" class="form-label">পূর্ববর্তী স্কুল</label>
                                                            <input type="text" class="form-control" id="previous_school" name="previous_school" value="<?php echo htmlspecialchars($student['previous_school'] ?? ''); ?>" placeholder="পূর্ববর্তী স্কুলের নাম">
                                                        </td>
                                                        <td>
                                                            <label for="status" class="form-label">অবস্থা</label>
                                                            <select class="form-select" id="status" name="status">
                                                                <option value="active" <?php echo ($student['status'] == 'active') ? 'selected' : ''; ?>>সক্রিয়</option>
                                                                <option value="inactive" <?php echo ($student['status'] == 'inactive') ? 'selected' : ''; ?>>নিষ্ক্রিয়</option>
                                                                <option value="graduated" <?php echo ($student['status'] == 'graduated') ? 'selected' : ''; ?>>স্নাতক</option>
                                                                <option value="transferred" <?php echo ($student['status'] == 'transferred') ? 'selected' : ''; ?>>স্থানান্তরিত</option>
                                                            </select>
                                                        </td>
                                                    </tr>
                                                </table>
                                            </div>
                                        </div>
                                        
                                        <!-- Subjects -->
                                        <?php if (isset($class_subjects_map[$student['class_id']]) && !empty($class_subjects_map[$student['class_id']])): ?>
                                            <div class="mb-3">
                                                <label class="form-label">বিষয়সমূহ</label>
                                                <div class="row">
                                                    <?php foreach ($class_subjects_map[$student['class_id']] as $subject): ?>
                                                        <div class="col-md-4 mb-2">
                                                            <div class="form-check">
                                                                <input class="form-check-input" type="checkbox" name="subjects[]" value="<?php echo $subject['subject_id']; ?>" id="subject_<?php echo $subject['subject_id']; ?>" <?php echo in_array($subject['subject_id'], $current_subjects) ? 'checked' : ''; ?>>
                                                                <label class="form-check-label" for="subject_<?php echo $subject['subject_id']; ?>">
                                                                    <?php echo htmlspecialchars($subject['name'] . ' (' . $subject['code'] . ')'); ?>
                                                                </label>
                                                            </div>
                                                        </div>
                                                    <?php endforeach; ?>
                                                </div>
                                            </div>
                                        <?php endif; ?>
                                    </div>

                                    <div class="d-flex justify-content-between">
                                        <a href="my_students.php" class="btn btn-secondary">
                                            <i class="fas fa-arrow-left"></i> তালিকায় ফিরুন
                                        </a>
                                        <button type="submit" class="btn btn-primary">
                                            <i class="fas fa-save"></i> আপডেট করুন
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </form>
                        <?php else: ?>
                            <div class="text-center">
                                <a href="my_students.php" class="btn btn-primary">
                                    <i class="fas fa-arrow-left"></i> ছাত্র-ছাত্রী তালিকায় ফিরুন
                                </a>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Form validation
        (function () {
            'use strict'
            var forms = document.querySelectorAll('.needs-validation')
            Array.prototype.slice.call(forms)
                .forEach(function (form) {
                    form.addEventListener('submit', function (event) {
                        if (!form.checkValidity()) {
                            event.preventDefault()
                            event.stopPropagation()
                        }
                        form.classList.add('was-validated')
                    }, false)
                })
        })()
    </script>
</body>
</html>