<?php
// Increase PHP limits for handling large forms with many students
ini_set('max_input_vars', 5000);
ini_set('max_input_time', 300);
ini_set('max_execution_time', 300);
ini_set('memory_limit', '256M');

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

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

// Get teacher's assigned classes if user is a teacher
$teacher_id = null;
$assigned_class_ids = [];
if ($_SESSION['user_role'] == 'teacher') {
    // Get teacher ID
    $stmt = $pdo->prepare("SELECT id FROM teachers WHERE user_id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $teacher = $stmt->fetch();
    if ($teacher) {
        $teacher_id = $teacher['id'];
        
        // Get assigned class IDs
        $stmt = $pdo->prepare("SELECT DISTINCT c.id FROM classes c JOIN class_subjects cs ON c.id = cs.class_id WHERE cs.teacher_id = ? AND c.status = 'active'");
        $stmt->execute([$teacher_id]);
        $assigned_classes = $stmt->fetchAll();
        $assigned_class_ids = array_column($assigned_classes, 'id');
    }
}

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

// Check for success message from redirect
if (isset($_GET['saved']) && $_GET['saved'] == '1') {
    $success_message = "মার্কস সফলভাবে সেভ করা হয়েছে!";
}
$students = [];
$mark_distribution = null;
$sort_by = 'roll_asc'; // Default sorting

// Get data for dropdowns
$subjects = $pdo->query("SELECT id, name, code FROM subjects WHERE status = 'active' ORDER BY name")->fetchAll();

// Get total students count for the selected class and session (for information display)
$total_students = 0;
$enrolled_students = 0;
if (isset($_GET['search']) && $_GET['search'] == '1' && !empty($_GET['class_id']) && !empty($_GET['session']) && !empty($_GET['subject_id'])) {
    $class_id = $_GET['class_id'];
    $session = $_GET['session'];
    $subject_id = $_GET['subject_id'];
    
    // Get total students in class
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM students WHERE class_id = ? AND session = ? AND status = 'active'");
    $stmt->execute([$class_id, $session]);
    $total_result = $stmt->fetch();
    $total_students = $total_result['count'];
    
    // Get students enrolled in subject
    $stmt = $pdo->prepare("
        SELECT COUNT(*) as count 
        FROM students s 
        INNER JOIN student_subjects ss ON ss.student_id = s.id 
        WHERE s.class_id = ? AND s.session = ? AND ss.subject_id = ? AND s.status = 'active'
    ");
    $stmt->execute([$class_id, $session, $subject_id]);
    $enrolled_result = $stmt->fetch();
    $enrolled_students = $enrolled_result['count'];
}
$section_filter = $_GET['section'] ?? '';
$sections = $pdo->query("SELECT DISTINCT section FROM classes WHERE status='active' ORDER BY section")->fetchAll(PDO::FETCH_COLUMN);
// Get classes based on user role
$class_where = "status='active'" . ($section_filter ? " AND section=" . $pdo->quote($section_filter) : "");
if ($_SESSION['user_role'] == 'teacher' && !empty($assigned_class_ids)) {
    $ids = implode(',', array_map('intval', $assigned_class_ids));
    $classes = $pdo->query("SELECT id, name, section FROM classes WHERE id IN ($ids) AND $class_where ORDER BY name, section")->fetchAll();
} else {
    $classes = $pdo->query("SELECT id, name, section FROM classes WHERE $class_where ORDER BY name, section")->fetchAll();
}
$sessions = $pdo->query("SELECT session_name FROM academic_sessions WHERE status = 'active' ORDER BY session_name DESC")->fetchAll();
$groups = $pdo->query("SELECT group_name, group_code FROM student_groups WHERE status = 'active' ORDER BY group_name")->fetchAll();
require_once '../includes/branch_helper.php';
$branches = get_active_school_branches($pdo);

// Handle search for students
if (isset($_GET['search']) && $_GET['search'] == '1') {
    $subject_id = $_GET['subject_id'];
    $class_id = $_GET['class_id'];
    $session = $_GET['session'];
    $group_name = $_GET['group_name'] ?? '';
    $exam_type = !empty($_GET['exam_type']) ? $_GET['exam_type'] : 'midterm';
    $sort_by = $_GET['sort_by'] ?? 'roll_asc';
    $branch_id = !empty($_GET['branch_id']) ? (int)$_GET['branch_id'] : 0;
    
    // Get mark distribution with fallback chain:
    // Priority 1: class_mark_distribution (from class_based_setup.php - manually configured)
    // Priority 2: subject_mark_distribution (session-based, with defaults)
    // Priority 3: mark_distributions (legacy/auto-created)
    // Priority 4: Auto-create default
    
    // Priority 1: class_mark_distribution (class_based_setup.php) - highest priority
    try {
        if (!empty($group_name)) {
            $stmt = $pdo->prepare("SELECT * FROM class_mark_distribution WHERE subject_id = ? AND class_id = ? AND (exam_type = ? OR exam_type = 'all') AND (group_name = ? OR group_name IS NULL) ORDER BY IF(exam_type=?,0,1), IF(group_name=?,0,1) LIMIT 1");
            $stmt->execute([$subject_id, $class_id, $exam_type, $group_name, $exam_type, $group_name]);
        } else {
            $stmt = $pdo->prepare("SELECT * FROM class_mark_distribution WHERE subject_id = ? AND class_id = ? AND (exam_type = ? OR exam_type = 'all') ORDER BY IF(exam_type=?,0,1), IF(group_name IS NULL OR group_name='',0,1) LIMIT 1");
            $stmt->execute([$subject_id, $class_id, $exam_type, $exam_type]);
        }
        $mark_distribution = $stmt->fetch();
    } catch (Throwable $e) { $mark_distribution = null; }

    // Priority 2: subject_mark_distribution (exact match + fallbacks)
    if (!$mark_distribution) {
        if (empty($group_name)) {
            $stmt = $pdo->prepare("
                SELECT * FROM subject_mark_distribution 
                WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ?
                ORDER BY 
                    CASE 
                        WHEN group_name IS NULL OR group_name = '' THEN 1
                        WHEN group_name = 'সাধারণ' THEN 2
                        ELSE 3
                    END
                LIMIT 1
            ");
            $stmt->execute([$subject_id, $class_id, $session, $exam_type]);
        } else {
            $stmt = $pdo->prepare("
                SELECT * FROM subject_mark_distribution 
                WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ?
                AND (group_name = ? OR UPPER(group_name) = UPPER(?))
            ");
            $stmt->execute([$subject_id, $class_id, $session, $exam_type, $group_name, $group_name]);
        }
        $mark_distribution = $stmt->fetch();

        // Fallback: session='default', same exam_type
        if (!$mark_distribution) {
            $stmt = $pdo->prepare("SELECT * FROM subject_mark_distribution WHERE subject_id=? AND class_id=? AND session='default' AND exam_type=? LIMIT 1");
            $stmt->execute([$subject_id, $class_id, $exam_type]);
            $mark_distribution = $stmt->fetch();
        }

        // Fallback: same session, exam_type='default'
        if (!$mark_distribution) {
            $stmt = $pdo->prepare("SELECT * FROM subject_mark_distribution WHERE subject_id=? AND class_id=? AND session=? AND exam_type='default' LIMIT 1");
            $stmt->execute([$subject_id, $class_id, $session]);
            $mark_distribution = $stmt->fetch();
        }

        // Fallback: class-level default (session='default', exam_type='default')
        if (!$mark_distribution) {
            $stmt = $pdo->prepare("SELECT * FROM subject_mark_distribution WHERE subject_id=? AND class_id=? AND session='default' AND exam_type='default' LIMIT 1");
            $stmt->execute([$subject_id, $class_id]);
            $mark_distribution = $stmt->fetch();
        }
    }

    // Priority 3: mark_distributions table (legacy/auto-created)
    if (!$mark_distribution) {
        try {
            $stmt = $pdo->prepare("SELECT * FROM mark_distributions WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ?");
            $stmt->execute([$subject_id, $class_id, $session, $exam_type]);
            $mark_distribution = $stmt->fetch();
        } catch (Throwable $e) {}
    }
    
    // Priority 4: Auto-create if still not found
    if (!$mark_distribution) {
        try {
            // Set default marks based on exam type
            $default_marks = [
                'midterm' => ['cq' => 30, 'mcq' => 20, 'practical' => 15, 'assignment' => 10, 'attendance' => 5, 'total' => 80],
                'final' => ['cq' => 40, 'mcq' => 25, 'practical' => 20, 'assignment' => 10, 'attendance' => 5, 'total' => 100],
                'test' => ['cq' => 20, 'mcq' => 15, 'practical' => 10, 'assignment' => 5, 'attendance' => 0, 'total' => 50],
                'assignment' => ['cq' => 0, 'mcq' => 0, 'practical' => 0, 'assignment' => 20, 'attendance' => 0, 'total' => 20],
                'practical' => ['cq' => 0, 'mcq' => 0, 'practical' => 30, 'assignment' => 0, 'attendance' => 0, 'total' => 30]
            ];
            
            $marks = $default_marks[$exam_type] ?? $default_marks['midterm'];
            $overall_pass = $marks['total'] * 0.4; // 40% pass marks
            
            $create_stmt = $pdo->prepare("
                INSERT INTO mark_distributions 
                (subject_id, class_id, session, exam_type, cq_marks, mcq_marks, practical_marks, assignment_marks, attendance_marks, total_marks, overall_pass_marks, cq_pass_marks, mcq_pass_marks, practical_pass_marks)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            
            $create_stmt->execute([
                $subject_id, $class_id, $session, $exam_type,
                $marks['cq'], $marks['mcq'], $marks['practical'], $marks['assignment'], $marks['attendance'],
                $marks['total'], $overall_pass,
                $marks['cq'] * 0.4, $marks['mcq'] * 0.4, $marks['practical'] * 0.4
            ]);
            
            // Fetch the newly created distribution
            $stmt = $pdo->prepare("SELECT * FROM mark_distributions WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ?");
            $stmt->execute([$subject_id, $class_id, $session, $exam_type]);
            $mark_distribution = $stmt->fetch();
            
            $success_message = "মার্কস বিভাজন স্বয়ংক্রিয়ভাবে তৈরি করা হয়েছে! (CQ: {$marks['cq']}, MCQ: {$marks['mcq']}, Practical: {$marks['practical']}, Assignment: {$marks['assignment']}, Attendance: {$marks['attendance']}, Total: {$marks['total']})";
            
        } catch (Exception $create_error) {
            $error_message = "মার্কস বিভাজন তৈরি করতে সমস্যা হয়েছে: " . $create_error->getMessage();
        }
    }
    
    if ($mark_distribution) {
        // Use the group_name from mark_distribution if URL group_name is empty
        $actual_group_name = empty($group_name) ? ($mark_distribution['group_name'] ?? '') : $group_name;
        
        // Build ORDER BY clause based on sort preference
        switch ($sort_by) {
            case 'roll_desc':
                $orderClause = "ORDER BY s.roll_number DESC, s.first_name, s.last_name";
                break;
            case 'name_asc':
                $orderClause = "ORDER BY s.first_name ASC, s.last_name ASC, s.roll_number";
                break;
            case 'name_desc':
                $orderClause = "ORDER BY s.first_name DESC, s.last_name DESC, s.roll_number";
                break;
            case 'roll_asc':
            default:
                $orderClause = "ORDER BY s.roll_number ASC, s.first_name, s.last_name";
                break;
        }
        
        // Fixed: Ensure consistent group name matching for students
        $branchWhere = "";
        if ($branch_id) {
            $branchWhere = "AND s.branch_id = ?";
        }
        if (empty($actual_group_name) || $actual_group_name == '') {
            $whereGroup = ""; // Show all students regardless of group
            $params = [$class_id, $session];
            if ($branch_id) $params[] = $branch_id;
        } else {
            // Use case-insensitive comparison for student group matching
            $whereGroup = "AND (s.group_name = ? OR UPPER(s.group_name) = UPPER(?))";
            $params = [$class_id, $session, $actual_group_name, $actual_group_name];
            if ($branch_id) $params[] = $branch_id;
        }
        
        // Fix group_name matching for results - show all if no specific group
        if (empty($actual_group_name) || $actual_group_name == '') {
            $resultsGroupCondition = ""; // Show results for all groups
        } else {
            // Use case-insensitive comparison for results group matching
            $resultsGroupCondition = "AND (r.group_name = ? OR UPPER(r.group_name) = UPPER(?))";
        }
        
        $stmt = $pdo->prepare("
            SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number,
                   r.id as result_id, r.marks_obtained, r.cq_marks, r.mcq_marks, 
                   r.practical_marks, r.assignment_marks, r.attendance_marks, r.grade,
                   COALESCE(sb.branch_name,'') as branch_name
            FROM students s
            INNER JOIN student_subjects ss ON ss.student_id = s.id AND ss.subject_id = ?
            LEFT JOIN (
                SELECT r1.* FROM results r1
                INNER JOIN (
                    SELECT student_id, MAX(id) as max_id 
                    FROM results 
                    WHERE subject_id = ? AND exam_id IS NULL AND session = ? AND exam_type = ?
                    GROUP BY student_id
                ) r2 ON r1.student_id = r2.student_id AND r1.id = r2.max_id
            ) r ON s.id = r.student_id
            LEFT JOIN school_branches sb ON s.branch_id = sb.id
            WHERE s.class_id = ? AND s.session = ? $whereGroup $branchWhere AND s.status = 'active'
            $orderClause
        ");
        
        // Build execute parameters for the new query structure
        if (empty($actual_group_name) || $actual_group_name == '') {
            // Parameters: ss.subject_id, subject_id (for subquery), session, exam_type, class_id, session [, branch_id]
            $executeParams = [$subject_id, $subject_id, $session, $exam_type, $class_id, $session];
            if ($branch_id) $executeParams[] = $branch_id;
        } else {
            // Include group_name parameter for students condition (both normal and upper case)
            $executeParams = [$subject_id, $subject_id, $session, $exam_type, $class_id, $session, $actual_group_name, $actual_group_name];
            if ($branch_id) $executeParams[] = $branch_id;
        }
        
        $stmt->execute($executeParams);
        $students = $stmt->fetchAll();
    }
}

// Handle marks submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save_marks'])) {
    // Log marks submission for debugging
    error_log("Marks submission for: subject_id=$subject_id, class_id=$class_id, session=$session, exam_type=$exam_type");
    
    $subject_id = $_POST['subject_id'];
    $class_id = $_POST['class_id'];
    $session = $_POST['session'];
    $group_name = $_POST['group_name'] ?? '';
    $exam_type = !empty($_POST['exam_type']) ? $_POST['exam_type'] : 'midterm';
    $student_marks = $_POST['student_marks'] ?? [];
    
    // Load mark distribution for validation with fallback chain:
    // Priority 1: class_mark_distribution (from class_based_setup.php - manually configured)
    // Priority 2: subject_mark_distribution (session-based, with defaults)
    // Priority 3: mark_distributions (legacy/auto-created)
    // Priority 4: Auto-create default
    
    // Priority 1: class_mark_distribution (class_based_setup.php) - highest priority
    try {
        if (!empty($group_name)) {
            $stmt = $pdo->prepare("SELECT * FROM class_mark_distribution WHERE subject_id = ? AND class_id = ? AND (exam_type = ? OR exam_type = 'all') AND (group_name = ? OR group_name IS NULL) ORDER BY IF(exam_type=?,0,1), IF(group_name=?,0,1) LIMIT 1");
            $stmt->execute([$subject_id, $class_id, $exam_type, $group_name, $exam_type, $group_name]);
        } else {
            $stmt = $pdo->prepare("SELECT * FROM class_mark_distribution WHERE subject_id = ? AND class_id = ? AND (exam_type = ? OR exam_type = 'all') ORDER BY IF(exam_type=?,0,1), IF(group_name IS NULL OR group_name='',0,1) LIMIT 1");
            $stmt->execute([$subject_id, $class_id, $exam_type, $exam_type]);
        }
        $mark_distribution = $stmt->fetch();
    } catch (Throwable $e) { $mark_distribution = null; }

    // Priority 2: subject_mark_distribution (exact match + fallbacks)
    if (!$mark_distribution) {
        if (empty($group_name)) {
            $stmt = $pdo->prepare("
                SELECT * FROM subject_mark_distribution 
                WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ?
                ORDER BY 
                    CASE 
                        WHEN group_name IS NULL OR group_name = '' THEN 1
                        WHEN group_name = 'সাধারণ' THEN 2
                        ELSE 3
                    END
                LIMIT 1
            ");
            $stmt->execute([$subject_id, $class_id, $session, $exam_type]);
        } else {
            $stmt = $pdo->prepare("
                SELECT * FROM subject_mark_distribution 
                WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ?
                AND (group_name = ? OR UPPER(group_name) = UPPER(?))
            ");
            $stmt->execute([$subject_id, $class_id, $session, $exam_type, $group_name, $group_name]);
        }
        $mark_distribution = $stmt->fetch();

        // Fallback: session='default', same exam_type
        if (!$mark_distribution) {
            $stmt = $pdo->prepare("SELECT * FROM subject_mark_distribution WHERE subject_id=? AND class_id=? AND session='default' AND exam_type=? LIMIT 1");
            $stmt->execute([$subject_id, $class_id, $exam_type]);
            $mark_distribution = $stmt->fetch();
        }
        // Fallback: same session, exam_type='default'
        if (!$mark_distribution) {
            $stmt = $pdo->prepare("SELECT * FROM subject_mark_distribution WHERE subject_id=? AND class_id=? AND session=? AND exam_type='default' LIMIT 1");
            $stmt->execute([$subject_id, $class_id, $session]);
            $mark_distribution = $stmt->fetch();
        }
        // Fallback: class-level default (session='default', exam_type='default')
        if (!$mark_distribution) {
            $stmt = $pdo->prepare("SELECT * FROM subject_mark_distribution WHERE subject_id=? AND class_id=? AND session='default' AND exam_type='default' LIMIT 1");
            $stmt->execute([$subject_id, $class_id]);
            $mark_distribution = $stmt->fetch();
        }
    }

    // Priority 3: mark_distributions table (legacy/auto-created)
    if (!$mark_distribution) {
        try {
            $stmt = $pdo->prepare("SELECT * FROM mark_distributions WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ?");
            $stmt->execute([$subject_id, $class_id, $session, $exam_type]);
            $mark_distribution = $stmt->fetch();
        } catch (Throwable $e) {}
    }
    
    // Priority 4: Auto-create if still not found
    if (!$mark_distribution) {
        error_log("Mark distribution not found for: subject_id=$subject_id, class_id=$class_id, session=$session, exam_type=$exam_type");
        
        // Auto-create default mark distribution
        error_log("Attempting to auto-create mark distribution...");
        try {
            // Set default marks based on exam type
            $default_marks = [
                'midterm' => ['cq' => 30, 'mcq' => 20, 'practical' => 15, 'assignment' => 10, 'attendance' => 5, 'total' => 80],
                'final' => ['cq' => 40, 'mcq' => 25, 'practical' => 20, 'assignment' => 10, 'attendance' => 5, 'total' => 100],
                'test' => ['cq' => 20, 'mcq' => 15, 'practical' => 10, 'assignment' => 5, 'attendance' => 0, 'total' => 50],
                'assignment' => ['cq' => 0, 'mcq' => 0, 'practical' => 0, 'assignment' => 20, 'attendance' => 0, 'total' => 20],
                'practical' => ['cq' => 0, 'mcq' => 0, 'practical' => 30, 'assignment' => 0, 'attendance' => 0, 'total' => 30]
            ];
            
            $marks = $default_marks[$exam_type] ?? $default_marks['midterm'];
            $overall_pass = $marks['total'] * 0.4; // 40% pass marks
            
            $create_stmt = $pdo->prepare("
                INSERT INTO mark_distributions 
                (subject_id, class_id, session, exam_type, cq_marks, mcq_marks, practical_marks, assignment_marks, attendance_marks, total_marks, overall_pass_marks, cq_pass_marks, mcq_pass_marks, practical_pass_marks)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            
            $create_stmt->execute([
                $subject_id, $class_id, $session, $exam_type,
                $marks['cq'], $marks['mcq'], $marks['practical'], $marks['assignment'], $marks['attendance'],
                $marks['total'], $overall_pass,
                $marks['cq'] * 0.4, $marks['mcq'] * 0.4, $marks['practical'] * 0.4
            ]);
            
            // Fetch the newly created distribution
            $stmt->execute([$subject_id, $class_id, $session, $exam_type]);
            $mark_distribution = $stmt->fetch();
            
            error_log("Auto-created mark distribution: " . print_r($mark_distribution, true));
            
        } catch (Exception $create_error) {
            $error_message = "মার্কস বিভাজন তৈরি করতে সমস্যা হয়েছে: " . $create_error->getMessage();
            error_log("Failed to auto-create mark distribution: " . $create_error->getMessage());
        }
    }
    
    if ($mark_distribution) {
        error_log("Using mark distribution: " . print_r($mark_distribution, true));
        try {
            $pdo->beginTransaction();
        
        $processed_count = 0;
        $skipped_count = 0;
        $all_warnings = [];
        
        foreach ($student_marks as $student_id => $marks) {
            // Skip if no marks entered for this student
            $has_marks = false;
            foreach ($marks as $mark_value) {
                if (!empty($mark_value) && trim($mark_value) !== '' && (float)$mark_value > 0) {
                    $has_marks = true;
                    break;
                }
            }
            
            if (!$has_marks) {
                $skipped_count++;
                continue; // Skip this student
            }
            
            // Validate marks (hard validation: block save if any component exceeds limits)
            $errors = [];
            
            $cq_input = (float)($marks['cq'] ?? 0);
            if ($cq_input < 0) { $errors[] = "CQ marks cannot be negative ({$cq_input})"; }
            if (($mark_distribution['cq_marks'] ?? 0) > 0 && $cq_input > ($mark_distribution['cq_marks'] ?? 0)) {
                $errors[] = "CQ marks {$cq_input} exceeded limit {$mark_distribution['cq_marks']}";
            }
            
            $mcq_input = (float)($marks['mcq'] ?? 0);
            if ($mcq_input < 0) { $errors[] = "MCQ marks cannot be negative ({$mcq_input})"; }
            if (($mark_distribution['mcq_marks'] ?? 0) > 0 && $mcq_input > ($mark_distribution['mcq_marks'] ?? 0)) {
                $errors[] = "MCQ marks {$mcq_input} exceeded limit {$mark_distribution['mcq_marks']}";
            }
            
            $practical_input = (float)($marks['practical'] ?? 0);
            if ($practical_input < 0) { $errors[] = "Practical marks cannot be negative ({$practical_input})"; }
            if (($mark_distribution['practical_marks'] ?? 0) > 0 && $practical_input > ($mark_distribution['practical_marks'] ?? 0)) {
                $errors[] = "Practical marks {$practical_input} exceeded limit {$mark_distribution['practical_marks']}";
            }
            
            $assignment_input = (float)($marks['assignment'] ?? 0);
            if ($assignment_input < 0) { $errors[] = "Assignment marks cannot be negative ({$assignment_input})"; }
            if (($mark_distribution['assignment_marks'] ?? 0) > 0 && $assignment_input > ($mark_distribution['assignment_marks'] ?? 0)) {
                $errors[] = "Assignment marks {$assignment_input} exceeded limit {$mark_distribution['assignment_marks']}";
            }
            
            $attendance_input = (float)($marks['attendance'] ?? 0);
            if ($attendance_input < 0) { $errors[] = "Attendance marks cannot be negative ({$attendance_input})"; }
            if (($mark_distribution['attendance_marks'] ?? 0) > 0 && $attendance_input > ($mark_distribution['attendance_marks'] ?? 0)) {
                $errors[] = "Attendance marks {$attendance_input} exceeded limit {$mark_distribution['attendance_marks']}";
            }
            
            if (!empty($errors)) {
                $student_name = "Student $student_id";
                $all_warnings[] = "$student_name: " . implode('; ', $errors);
                error_log("Student $student_id validation errors: " . implode('; ', $errors));
                $skipped_count++;
                continue; // skip saving this student's marks
            }
            
            // If valid, use the input values directly
            $cq_marks = $cq_input;
            $mcq_marks = $mcq_input;
            $practical_marks = $practical_input;
            $assignment_marks = $assignment_input;
            $attendance_marks = $attendance_input;
            
            $total_marks = (float)$cq_marks + (float)$mcq_marks + (float)$practical_marks + (float)$assignment_marks + (float)$attendance_marks;
            
            error_log("Processing student $student_id: CQ=$cq_marks, MCQ=$mcq_marks, Total=$total_marks");
            
            // Prepare marks array for grade calculation
            $sanitized_marks = [
                'cq' => $cq_marks,
                'mcq' => $mcq_marks,
                'practical' => $practical_marks,
                'assignment' => $assignment_marks,
                'attendance' => $attendance_marks
            ];
            
            // Calculate grade with individual passing marks check
            $grade = calculateGrade($total_marks, ($mark_distribution['total_marks'] ?? 100), $mark_distribution, $sanitized_marks);
            
            // Insert or update result
            $stmt = $pdo->prepare("
                INSERT INTO results 
                (student_id, exam_id, subject_id, session, group_name, exam_type, marks_obtained, 
                 cq_marks, mcq_marks, practical_marks, assignment_marks, attendance_marks, grade)
                VALUES (?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE
                marks_obtained = VALUES(marks_obtained),
                cq_marks = VALUES(cq_marks),
                mcq_marks = VALUES(mcq_marks),
                practical_marks = VALUES(practical_marks),
                assignment_marks = VALUES(assignment_marks),
                attendance_marks = VALUES(attendance_marks),
                grade = VALUES(grade),
                updated_at = CURRENT_TIMESTAMP
            ");
            
            $stmt->execute([
                $student_id, $subject_id, $session, $group_name, $exam_type, $total_marks,
                $cq_marks, $mcq_marks, $practical_marks, $assignment_marks, $attendance_marks, $grade
            ]);
            
            $processed_count++;
        }
        
        $pdo->commit();
        
        // Verify that data was actually saved
        $verify_stmt = $pdo->prepare("SELECT COUNT(*) as count FROM results WHERE subject_id = ? AND session = ? AND exam_type = ?");
        $verify_stmt->execute([$subject_id, $session, $exam_type]);
        $saved_count = $verify_stmt->fetch()['count'];
        
        error_log("Marks save completed. Records in database: $saved_count");
        
        // Success - marks saved
        $success_message = "মার্কস সফলভাবে সেভ করা হয়েছে! ($processed_count জন ছাত্রের মার্কস সেভ হয়েছে, $skipped_count জন skip করা হয়েছে)";

        // SMS: pass/fail notify per student
        try {
            require_once __DIR__ . '/../includes/sms_helper.php';
            $cfg = sms_config();
            if ($processed_count > 0) {
                // Retrieve saved results for this subject+session+exam_type (latest per student)
                $q = $pdo->prepare("SELECT r.student_id, r.grade, r.marks_obtained, r.cq_marks, r.mcq_marks, r.practical_marks, r.assignment_marks, r.attendance_marks,
                                            s.first_name, s.last_name, s.phone, s.guardian_phone,
                                            sub.name AS subject_name,
                                            COALESCE(s.group_name,'') AS group_name
                                     FROM results r
                                     JOIN students s ON s.id = r.student_id
                                     JOIN subjects sub ON sub.id = r.subject_id
                                     WHERE r.subject_id = ? AND r.session = ? AND r.exam_type = ?");
                $q->execute([$subject_id, $session, $exam_type]);
                $rows = $q->fetchAll();
                foreach ($rows as $row) {
                    $numbers = [];
                    if (!empty($row['phone'])) $numbers[] = $row['phone'];
                    if (($cfg['send_to_guardian_also'] ?? true) && !empty($row['guardian_phone'])) $numbers[] = $row['guardian_phone'];
                    if (empty($numbers)) continue;

                    $vars = [
                        'name' => trim(($row['first_name'] ?? '') . ' ' . ($row['last_name'] ?? '')),
                        'subject' => $row['subject_name'] ?? '',
                        'exam_type' => $exam_type,
                        'obtained' => number_format((float)$row['marks_obtained'], 2),
                        'total' => (string)($mark_distribution['total_marks'] ?? ''),
                        'grade' => (string)($row['grade'] ?? ''),
                    ];
                    $tpl = ($row['grade'] ?? 'F') === 'F' ? 'result_fail' : 'result_pass';
                    sms_send_template($pdo, $tpl, $vars, $numbers);
                }
            }
        } catch (Throwable $e) {
            if (function_exists('sms_log')) sms_log('RESULT SMS error: '.$e->getMessage());
        }

        // Add warnings if any
        if (!empty($all_warnings)) {
            $success_message .= "<br><br><strong>⚠️ সতর্কতা:</strong><br>";
            $success_message .= "<small>" . implode('<br>', $all_warnings) . "</small>";
        }

        // Don't redirect immediately - show success message first
        // header("Location: entry.php?search=1&subject_id=$subject_id&class_id=$class_id&session=$session&group_name=$group_name&exam_type=$exam_type&saved=1");
        // exit();

        } catch (Exception $e) {
            $pdo->rollBack();
            $error_message = "ত্রুটি: " . $e->getMessage();
        }
    }
}

// Handle marks deletion
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['delete_all_marks'])) {
    $subject_id = $_POST['subject_id'];
    $class_id = $_POST['class_id'];
    $session = $_POST['session'];
    $exam_type = $_POST['exam_type'];
    $group_name = $_POST['group_name'] ?? '';
    
    error_log("🗑️ Delete request: Subject=$subject_id, Class=$class_id, Session=$session, ExamType=$exam_type, Group='$group_name'");
    
    try {
        $pdo->beginTransaction();
        
        // First, check what records exist before deletion
        $check_stmt = $pdo->prepare(
            "SELECT COUNT(*) as count FROM results r
            INNER JOIN students s ON r.student_id = s.id
            INNER JOIN student_subjects ss ON ss.student_id = r.student_id AND ss.subject_id = r.subject_id
            WHERE r.subject_id = ? AND s.class_id = ? AND r.session = ? AND r.exam_type = ?"
        );
        $check_stmt->execute([$subject_id, $class_id, $session, $exam_type]);
        $before_count = $check_stmt->fetch()['count'];
        
        error_log("📊 Records before deletion: $before_count");
        
        // Build delete query based on group using proper MySQL JOIN syntax with student_subjects
        if (empty($group_name) || $group_name == '') {
            // Delete all marks for this class/subject/session/exam_type regardless of group
            $delete_stmt = $pdo->prepare(
                "DELETE r FROM results r
                INNER JOIN students s ON r.student_id = s.id
                INNER JOIN student_subjects ss ON ss.student_id = r.student_id AND ss.subject_id = r.subject_id
                WHERE r.subject_id = ? AND s.class_id = ? AND r.session = ? AND r.exam_type = ?"
            );
            $delete_stmt->execute([$subject_id, $class_id, $session, $exam_type]);
        } else {
            // Delete marks for specific group - also check for empty group names in results table
            // This handles cases where marks were saved with empty group name but user selected a group for deletion
            $delete_stmt = $pdo->prepare(
                "DELETE r FROM results r
                INNER JOIN students s ON r.student_id = s.id
                INNER JOIN student_subjects ss ON ss.student_id = r.student_id AND ss.subject_id = r.subject_id
                WHERE r.subject_id = ? AND s.class_id = ? AND r.session = ? AND r.exam_type = ? AND (r.group_name = ? OR r.group_name = '' OR r.group_name IS NULL)"
            );
            $delete_stmt->execute([$subject_id, $class_id, $session, $exam_type, $group_name]);
        }
        
        // Verify the deletion worked by checking affected rows
        $deleted_count = $delete_stmt->rowCount();
        error_log("🗑️ SQL Delete affected rows: $deleted_count");
        
        // Check what records remain after deletion
        // Check what records remain after deletion
        $check_stmt_after = $pdo->prepare(
            "SELECT COUNT(*) as count FROM results r
            INNER JOIN students s ON r.student_id = s.id
            INNER JOIN student_subjects ss ON ss.student_id = r.student_id AND ss.subject_id = r.subject_id
            WHERE r.subject_id = ? AND s.class_id = ? AND r.session = ? AND r.exam_type = ?"
        );
        $check_stmt_after->execute([$subject_id, $class_id, $session, $exam_type]);
        $after_count = $check_stmt_after->fetch()['count'];
        
        // Additional debugging - log if deletion didn't work as expected
        if ($before_count > 0 && $deleted_count == 0 && $after_count == $before_count) {
            error_log("⚠️ Deletion may not have worked as expected. Before: $before_count, Deleted: $deleted_count, After: $after_count");
        }
        
        error_log("📊 Records after deletion: $after_count");
        
        $pdo->commit();
        
        error_log("✅ Transaction committed. Before: $before_count, Deleted: $deleted_count, After: $after_count");
        
        // Check if this is an AJAX request
        $is_ajax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
        
        if ($is_ajax) {
            // For AJAX requests, return JSON response
            header('Content-Type: application/json');
            echo json_encode([
                'success' => true,
                'message' => "সফলভাবে $deleted_count টি marks entry মুছে ফেলা হয়েছে! (আগে: $before_count, পরে: $after_count)",
                'deleted_count' => $deleted_count,
                'before_count' => $before_count,
                'after_count' => $after_count
            ]);
            exit();
        } else {
            // For regular form submissions, set success message and redirect
            $success_message = "সফলভাবে $deleted_count টি marks entry মুছে ফেলা হয়েছে! (আগে: $before_count, পরে: $after_count)";
            // Add a flag to indicate that the page should be refreshed after deletion
            $should_refresh_after_delete = true;
            
            // Redirect to prevent form resubmission on refresh
            if (!headers_sent()) {
                header("Location: " . $_SERVER['PHP_SELF'] . "?search=1&subject_id=$subject_id&class_id=$class_id&session=$session&group_name=$group_name&exam_type=$exam_type");
                exit();
            }
        }
        
    } catch (Exception $e) {
        $pdo->rollBack();
        $error_message = "মার্কস মুছতে সমস্যা হয়েছে: " . $e->getMessage();
        error_log("❌ Delete error: " . $e->getMessage());
    }
}

function calculateGrade($obtained_marks, $total_marks, $mark_distribution = null, $individual_marks = []) {
    if ($total_marks == 0) return 'F';
    
    // Check individual passing marks if set
    if ($mark_distribution) {
        // Check CQ passing marks
        if (!empty($mark_distribution['cq_pass_marks'] ?? 0) && ($mark_distribution['cq_marks'] ?? 0) > 0) {
            $cq_obtained = (float)($individual_marks['cq'] ?? 0);
            if ($cq_obtained < ($mark_distribution['cq_pass_marks'] ?? 0)) {
                return 'F'; // Failed in CQ
            }
        }
        
        // Check MCQ passing marks
        if (!empty($mark_distribution['mcq_pass_marks'] ?? 0) && ($mark_distribution['mcq_marks'] ?? 0) > 0) {
            $mcq_obtained = (float)($individual_marks['mcq'] ?? 0);
            if ($mcq_obtained < ($mark_distribution['mcq_pass_marks'] ?? 0)) {
                return 'F'; // Failed in MCQ
            }
        }
        
        // Check Practical passing marks
        if (!empty($mark_distribution['practical_pass_marks'] ?? 0) && ($mark_distribution['practical_marks'] ?? 0) > 0) {
            $practical_obtained = (float)($individual_marks['practical'] ?? 0);
            if ($practical_obtained < ($mark_distribution['practical_pass_marks'] ?? 0)) {
                return 'F'; // Failed in Practical
            }
        }
        
        // Check overall passing marks
        $overall_pass_marks = $mark_distribution['overall_pass_marks'] ?? $mark_distribution['pass_marks'] ?? ($total_marks * 0.4);
        if ($obtained_marks < $overall_pass_marks) {
            return 'F'; // Failed overall
        }
    }
    
    $percentage = ($obtained_marks / $total_marks) * 100;
    
    if ($percentage >= 80) return 'A+';
    elseif ($percentage >= 70) return 'A';
    elseif ($percentage >= 60) return 'A-';
    elseif ($percentage >= 50) return 'B';
    elseif ($percentage >= 40) return 'C';
    elseif ($percentage >= 33) return 'D';
    else return 'F';
}
?>


<!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/style.css" rel="stylesheet">
    <style>
        body { font-size:0.83rem; background:linear-gradient(135deg,#667eea15,#764ba215); min-height:100vh; }
        .navbar { background:linear-gradient(135deg,#1a237e,#3949ab) !important; }
        .filter-card { border:none; border-radius:10px; box-shadow:0 2px 12px rgba(102,126,234,.15); }
        .filter-card .card-header { background:linear-gradient(135deg,#667eea,#764ba2); color:#fff; padding:.4rem .75rem; border-radius:10px 10px 0 0; font-size:.82rem; font-weight:600; }
        .filter-card .card-body { background:#f8f9ff; padding:.5rem .75rem; border-radius:0 0 10px 10px; }
        .entry-card { border:none; border-radius:10px; box-shadow:0 2px 16px rgba(0,0,0,.08); }
        .entry-card .card-header { background:linear-gradient(135deg,#1a237e,#3949ab); color:#fff; padding:.45rem .75rem; border-radius:10px 10px 0 0; }
        .dist-bar { background:#f0f4ff; border-radius:8px; padding:5px 10px; margin-bottom:6px; display:flex; flex-wrap:wrap; gap:6px; align-items:center; }
        .dist-item { display:inline-flex; align-items:center; gap:4px; font-size:.73rem; background:#fff; border-radius:20px; padding:2px 10px; border:1px solid #dee2e6; }
        .dist-item .num { font-weight:700; color:#1a237e; }
        .dist-item .pass { color:#c62828; font-size:.67rem; }
        .enroll-info { background:#e8f5e9; border-left:3px solid #43a047; border-radius:0 6px 6px 0; padding:4px 10px; font-size:.73rem; margin-bottom:6px; }
        .marks-table { font-size:.78rem; }
        .marks-table thead th { background:linear-gradient(135deg,#2c3e50,#3d5a80); color:#fff; border:none; padding:4px 6px; text-align:center; white-space:nowrap; font-size:.71rem; position:sticky; top:0; z-index:5; }
        .marks-table tbody tr:nth-child(odd)  { background:#f0f4ff; }
        .marks-table tbody tr:nth-child(even) { background:#fff; }
        .marks-table tbody tr:hover { background:#e3f2fd !important; }
        .marks-table td { padding:3px 4px; vertical-align:middle; }
        .mark-input { width:56px; padding:2px 4px; font-size:.76rem; text-align:center; border-radius:4px; }
        .mark-input:focus { border-color:#764ba2; box-shadow:0 0 0 .1rem rgba(118,75,162,.25); }
        .mark-input.over-limit { border-color:#dc3545 !important; background:#fff5f5; }
        .btn-save-marks  { background:linear-gradient(135deg,#11998e,#38ef7d); border:none; color:#fff; font-weight:600; }
        .btn-save-marks:hover  { opacity:.9; color:#fff; }
        .btn-clear-marks { background:linear-gradient(135deg,#f7971e,#ffd200); border:none; color:#333; font-weight:600; }
        .btn-clear-marks:hover { opacity:.9; color:#333; }
        .btn-delete-marks { background:linear-gradient(135deg,#f5576c,#f093fb); border:none; color:#fff; font-weight:600; }
        .btn-delete-marks:hover { opacity:.9; color:#fff; }
        @media print { .no-print { display:none !important; } body { background:#fff; } }
    </style>
</head>
<body class="bengali-text">
    <nav class="navbar navbar-expand-lg navbar-dark py-1 no-print">
        <div class="container-fluid">
            <a class="navbar-brand fw-bold" href="../index.php"><i class="fas fa-graduation-cap me-1"></i>স্কুল ম্যানেজমেন্ট</a>
            <div class="navbar-nav ms-auto flex-row gap-2">
                <a class="nav-link px-2 py-1" href="../index.php"><i class="fas fa-home"></i> হোম</a>
                <a class="nav-link px-2 py-1" href="setup.php"><i class="fas fa-cog"></i> সেটআপ</a>
                <a class="nav-link px-2 py-1" href="quick_setup.php"><i class="fas fa-bolt"></i> দ্রুত সেটআপ</a>
            </div>
        </div>
    </nav>

    <div class="container-fluid px-3 mt-2">
        <?php if ($success_message): ?>
            <div class="alert alert-success alert-dismissible fade show py-1 px-3 mb-2 small no-print">
                <i class="fas fa-check-circle"></i> <?php echo $success_message; ?>
                <button type="button" class="btn-close btn-sm" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        <?php if ($error_message): ?>
            <div class="alert alert-danger alert-dismissible fade show py-1 px-3 mb-2 small no-print">
                <i class="fas fa-exclamation-triangle"></i> <?php echo $error_message; ?>
                <button type="button" class="btn-close btn-sm" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- Filter -->
        <div class="card filter-card mb-2 no-print">
            <div class="card-header"><i class="fas fa-search me-1"></i>মার্কস এন্ট্রি — শিক্ষার্থী খুঁজুন</div>
            <div class="card-body">
                <form method="GET" action="" class="needs-validation" novalidate>
                    <input type="hidden" name="search" value="1">
                    <div class="row g-1 align-items-end flex-nowrap" style="flex-wrap:nowrap;overflow-x:auto">
                        <div class="col" style="min-width:120px">
                            <label class="form-label mb-0" style="font-size:.68rem;">বিষয় *</label>
                            <select class="form-select form-select-sm" name="subject_id" required>
                                <option value="">নির্বাচন</option>
                                <?php foreach ($subjects as $s): ?>
                                    <option value="<?php echo $s['id']; ?>" <?php echo (isset($_GET['subject_id'])&&$_GET['subject_id']==$s['id'])?'selected':''; ?>><?php echo $s['name'].' ('.$s['code'].')'; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col" style="min-width:100px">
                            <label class="form-label mb-0" style="font-size:.68rem;">ক্লাস *</label>
                            <select class="form-select form-select-sm" name="class_id" required>
                                <option value="">নির্বাচন</option>
                                <?php foreach ($classes as $c): ?>
                                    <option value="<?php echo $c['id']; ?>" <?php echo (isset($_GET['class_id'])&&$_GET['class_id']==$c['id'])?'selected':''; ?>><?php echo $c['name'].'-'.$c['section']; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col" style="min-width:100px">
                            <label class="form-label mb-0" style="font-size:.68rem;">সেশন *</label>
                            <select class="form-select form-select-sm" name="session" required>
                                <option value="">নির্বাচন</option>
                                <?php foreach ($sessions as $sess): ?>
                                    <option value="<?php echo $sess['session_name']; ?>" <?php echo (isset($_GET['session'])&&$_GET['session']==$sess['session_name'])?'selected':''; ?>><?php echo $sess['session_name']; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col" style="min-width:80px">
                            <label class="form-label mb-0" style="font-size:.68rem;">গ্রুপ</label>
                            <select class="form-select form-select-sm" name="group_name">
                                <option value="">সাধারণ</option>
                                <?php foreach ($groups as $g): ?>
                                    <option value="<?php echo $g['group_name']; ?>" <?php echo (isset($_GET['group_name'])&&$_GET['group_name']==$g['group_name'])?'selected':''; ?>><?php echo $g['group_name']; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col" style="min-width:100px">
                            <label class="form-label mb-0" style="font-size:.68rem;">পরীক্ষা *</label>
                            <select class="form-select form-select-sm" name="exam_type" required>
                                <option value="">নির্বাচন</option>
                                <option value="midterm"    <?php echo (isset($_GET['exam_type'])&&$_GET['exam_type']=='midterm')?'selected':''; ?>>অর্ধবার্ষিক</option>
                                <option value="final"      <?php echo (isset($_GET['exam_type'])&&$_GET['exam_type']=='final')?'selected':''; ?>>বার্ষিক</option>
                                <option value="test"       <?php echo (isset($_GET['exam_type'])&&$_GET['exam_type']=='test')?'selected':''; ?>>টেস্ট</option>
                                <option value="assignment" <?php echo (isset($_GET['exam_type'])&&$_GET['exam_type']=='assignment')?'selected':''; ?>>অ্যাসাইনমেন্ট</option>
                                <option value="practical"  <?php echo (isset($_GET['exam_type'])&&$_GET['exam_type']=='practical')?'selected':''; ?>>ব্যবহারিক</option>
                            </select>
                        </div>
                        <div class="col" style="min-width:100px">
                            <label class="form-label mb-0" style="font-size:.68rem;">শাখা (ব্রাঞ্চ)</label>
                            <select class="form-select form-select-sm" name="branch_id">
                                <option value="">সব</option>
                                <?php foreach ($branches as $br): ?>
                                    <option value="<?php echo $br['id']; ?>" <?php echo (isset($_GET['branch_id'])&&$_GET['branch_id']==$br['id'])?'selected':''; ?>><?php echo htmlspecialchars($br['branch_name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col" style="min-width:80px">
                            <button type="submit" class="btn btn-sm w-100 py-1 mt-auto" style="background:linear-gradient(135deg,#667eea,#764ba2);color:#fff;border:none;font-size:.78rem;">
                                <i class="fas fa-search"></i> খুঁজুন
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <?php if ($mark_distribution && !empty($students)): ?>
        <div class="card entry-card">
            <div class="card-header d-flex align-items-center justify-content-between flex-wrap gap-1">
                <div>
                    <span style="font-size:.85rem;font-weight:700;"><i class="fas fa-edit me-1"></i>মার্কস এন্ট্রি</span>
                    <span class="ms-2" style="font-size:.71rem;opacity:.85;">
                        <?php $subj=array_filter($subjects,fn($s)=>$s['id']==($mark_distribution['subject_id']??0)); echo reset($subj)['name']??''; ?>
                        | মোট: <?php echo $mark_distribution['total_marks']??''; ?>
                        | পাস: <?php echo $mark_distribution['overall_pass_marks']??$mark_distribution['pass_marks']??''; ?>
                    </span>
                </div>
                <div class="d-flex gap-1 align-items-center no-print">
                    <div class="dropdown">
                        <button class="btn btn-sm btn-light py-0 px-2 dropdown-toggle" type="button" data-bs-toggle="dropdown" style="font-size:.71rem;"><i class="fas fa-sort"></i> সাজানো</button>
                        <ul class="dropdown-menu dropdown-menu-end" style="font-size:.76rem;">
                            <li><a class="dropdown-item <?php echo ($sort_by=='roll_asc')?'active':''; ?>" href="?<?php echo http_build_query(array_merge($_GET,['sort_by'=>'roll_asc'])); ?>">রোল ↑</a></li>
                            <li><a class="dropdown-item <?php echo ($sort_by=='roll_desc')?'active':''; ?>" href="?<?php echo http_build_query(array_merge($_GET,['sort_by'=>'roll_desc'])); ?>">রোল ↓</a></li>
                            <li><a class="dropdown-item <?php echo ($sort_by=='name_asc')?'active':''; ?>"  href="?<?php echo http_build_query(array_merge($_GET,['sort_by'=>'name_asc'])); ?>">নাম A-Z</a></li>
                            <li><a class="dropdown-item <?php echo ($sort_by=='name_desc')?'active':''; ?>" href="?<?php echo http_build_query(array_merge($_GET,['sort_by'=>'name_desc'])); ?>">নাম Z-A</a></li>
                        </ul>
                    </div>
                    <button type="button" class="btn btn-sm btn-outline-secondary py-0 px-2" onclick="fillSampleMarks()" style="font-size:.71rem;" title="নমুনা মার্কস"><i class="fas fa-magic"></i></button>
                    <button type="button" class="btn btn-sm btn-outline-warning py-0 px-2" onclick="clearAllMarks()" style="font-size:.71rem;" title="সব মুছুন"><i class="fas fa-eraser"></i></button>
                </div>
            </div>
            <div class="card-body p-2">
                <!-- Distribution bar -->
                <div class="dist-bar no-print">
                    <?php if(($mark_distribution['cq_marks']??0)>0): ?><div class="dist-item"><span>CQ</span><span class="num"><?php echo $mark_distribution['cq_marks']; ?></span><?php if(!empty($mark_distribution['cq_pass_marks'])): ?><span class="pass">পাস:<?php echo $mark_distribution['cq_pass_marks']; ?></span><?php endif; ?></div><?php endif; ?>
                    <?php if(($mark_distribution['mcq_marks']??0)>0): ?><div class="dist-item"><span>MCQ</span><span class="num"><?php echo $mark_distribution['mcq_marks']; ?></span><?php if(!empty($mark_distribution['mcq_pass_marks'])): ?><span class="pass">পাস:<?php echo $mark_distribution['mcq_pass_marks']; ?></span><?php endif; ?></div><?php endif; ?>
                    <?php if(($mark_distribution['practical_marks']??0)>0): ?><div class="dist-item"><span>Practical</span><span class="num"><?php echo $mark_distribution['practical_marks']; ?></span><?php if(!empty($mark_distribution['practical_pass_marks'])): ?><span class="pass">পাস:<?php echo $mark_distribution['practical_pass_marks']; ?></span><?php endif; ?></div><?php endif; ?>
                    <?php if(($mark_distribution['assignment_marks']??0)>0): ?><div class="dist-item"><span>Assignment</span><span class="num"><?php echo $mark_distribution['assignment_marks']; ?></span></div><?php endif; ?>
                    <?php if(($mark_distribution['attendance_marks']??0)>0): ?><div class="dist-item"><span>Attendance</span><span class="num"><?php echo $mark_distribution['attendance_marks']; ?></span></div><?php endif; ?>
                    <div class="dist-item" style="background:#e8f5e9;border-color:#43a047;"><span>মোট</span><span class="num" style="color:#2e7d32;"><?php echo $mark_distribution['total_marks']; ?></span></div>
                    <div class="dist-item" style="background:#fff3e0;border-color:#ef6c00;"><span>পাস</span><span class="num" style="color:#e65100;"><?php echo $mark_distribution['overall_pass_marks']??$mark_distribution['pass_marks']??''; ?></span></div>
                </div>

                <?php if($total_students>0): ?>
                <div class="enroll-info no-print">
                    <i class="fas fa-users me-1"></i>
                    ক্লাসে মোট: <strong><?php echo $total_students; ?></strong> |
                    নিবন্ধিত: <strong><?php echo $enrolled_students; ?></strong> |
                    এন্ট্রি উপলব্ধ: <strong><?php echo count($students); ?></strong>
                    <?php if($total_students>$enrolled_students): ?><span class="text-warning ms-2"><i class="fas fa-info-circle"></i> <?php echo ($total_students-$enrolled_students); ?> জন নিবন্ধিত নয়</span><?php endif; ?>
                </div>
                <?php endif; ?>

                <form method="POST" action="" id="marks-form">
                    <input type="hidden" name="save_marks" value="1">
                    <input type="hidden" name="subject_id" value="<?php echo htmlspecialchars($_GET['subject_id']); ?>">
                    <input type="hidden" name="class_id"   value="<?php echo htmlspecialchars($_GET['class_id']); ?>">
                    <input type="hidden" name="session"    value="<?php echo htmlspecialchars($_GET['session']); ?>">
                    <input type="hidden" name="group_name" value="<?php echo htmlspecialchars($_GET['group_name']??''); ?>">
                    <input type="hidden" name="exam_type"  value="<?php echo htmlspecialchars($_GET['exam_type']); ?>">

                    <div class="table-responsive" style="max-height:62vh;overflow-y:auto;">
                        <table class="table table-bordered marks-table mb-0">
                            <thead>
                                <tr>
                                    <th style="width:38px;">রোল</th>
                                    <th>নাম</th>
                                    <th>শাখা</th>
                                    <?php if(($mark_distribution['cq_marks']??0)>0): ?><th>CQ<br><small>/<?php echo $mark_distribution['cq_marks']; ?></small></th><?php endif; ?>
                                    <?php if(($mark_distribution['mcq_marks']??0)>0): ?><th>MCQ<br><small>/<?php echo $mark_distribution['mcq_marks']; ?></small></th><?php endif; ?>
                                    <?php if(($mark_distribution['practical_marks']??0)>0): ?><th>Prac<br><small>/<?php echo $mark_distribution['practical_marks']; ?></small></th><?php endif; ?>
                                    <?php if(($mark_distribution['assignment_marks']??0)>0): ?><th>Asn<br><small>/<?php echo $mark_distribution['assignment_marks']; ?></small></th><?php endif; ?>
                                    <?php if(($mark_distribution['attendance_marks']??0)>0): ?><th>Att<br><small>/<?php echo $mark_distribution['attendance_marks']; ?></small></th><?php endif; ?>
                                    <th>মোট<br><small>/<?php echo $mark_distribution['total_marks']??0; ?></small></th>
                                    <th>গ্রেড</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($students as $student): ?>
                                <tr>
                                    <td class="text-center fw-bold"><?php echo $student['roll_number']?:'N/A'; ?></td>
                                    <td>
                                        <div class="fw-semibold" style="font-size:.77rem;"><?php echo $student['first_name'].' '.$student['last_name']; ?></div>
                                        <div class="text-muted" style="font-size:.67rem;"><?php echo $student['student_id']; ?></div>
                                    </td>
                                    <td style="font-size:.72rem;white-space:nowrap;"><?php echo htmlspecialchars($student['branch_name']?:'-'); ?></td>
                                    <?php if(($mark_distribution['cq_marks']??0)>0): ?>
                                    <td><input type="number" class="form-control mark-input" name="student_marks[<?php echo $student['id']; ?>][cq]" min="0" max="<?php echo $mark_distribution['cq_marks']??0; ?>" step="0.5" value="<?php echo $student['cq_marks']??''; ?>" data-student="<?php echo $student['id']; ?>" data-type="cq"></td>
                                    <?php endif; ?>
                                    <?php if(($mark_distribution['mcq_marks']??0)>0): ?>
                                    <td><input type="number" class="form-control mark-input" name="student_marks[<?php echo $student['id']; ?>][mcq]" min="0" max="<?php echo $mark_distribution['mcq_marks']??0; ?>" step="0.5" value="<?php echo $student['mcq_marks']??''; ?>" data-student="<?php echo $student['id']; ?>" data-type="mcq"></td>
                                    <?php endif; ?>
                                    <?php if(($mark_distribution['practical_marks']??0)>0): ?>
                                    <td><input type="number" class="form-control mark-input" name="student_marks[<?php echo $student['id']; ?>][practical]" min="0" max="<?php echo $mark_distribution['practical_marks']??0; ?>" step="0.5" value="<?php echo $student['practical_marks']??''; ?>" data-student="<?php echo $student['id']; ?>" data-type="practical"></td>
                                    <?php endif; ?>
                                    <?php if(($mark_distribution['assignment_marks']??0)>0): ?>
                                    <td><input type="number" class="form-control mark-input" name="student_marks[<?php echo $student['id']; ?>][assignment]" min="0" max="<?php echo $mark_distribution['assignment_marks']??0; ?>" step="0.5" value="<?php echo $student['assignment_marks']??''; ?>" data-student="<?php echo $student['id']; ?>" data-type="assignment"></td>
                                    <?php endif; ?>
                                    <?php if(($mark_distribution['attendance_marks']??0)>0): ?>
                                    <td><input type="number" class="form-control mark-input" name="student_marks[<?php echo $student['id']; ?>][attendance]" min="0" max="<?php echo $mark_distribution['attendance_marks']??0; ?>" step="0.5" value="<?php echo $student['attendance_marks']??''; ?>" data-student="<?php echo $student['id']; ?>" data-type="attendance"></td>
                                    <?php endif; ?>
                                    <td class="text-center fw-bold"><span class="total-marks" data-student="<?php echo $student['id']; ?>"><?php echo $student['marks_obtained']??'0'; ?></span></td>
                                    <td class="text-center"><span class="badge grade-badge" data-student="<?php echo $student['id']; ?>"><?php echo $student['grade']??'N/A'; ?></span></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>

                    <div class="d-flex gap-2 justify-content-center mt-2 no-print">
                        <button type="submit" class="btn btn-save-marks btn-sm px-4"><i class="fas fa-save me-1"></i>সব মার্কস সেভ করুন</button>
                        <button type="button" class="btn btn-clear-marks btn-sm px-3" onclick="clearAllMarks()"><i class="fas fa-eraser me-1"></i>ক্লিয়ার</button>
                        <button type="button" class="btn btn-delete-marks btn-sm px-3" onclick="confirmDeleteAllMarks()"><i class="fas fa-trash-alt me-1"></i>DB মুছুন</button>
                    </div>
                    <div class="text-center mt-1 no-print" style="font-size:.67rem;color:#888;">
                        <i class="fas fa-info-circle"></i> ক্লিয়ার = শুধু ফর্ম | DB মুছুন = স্থায়ীভাবে মুছবে
                    </div>
                </form>

            </div><!-- /card-body -->
        </div><!-- /entry-card -->
        <?php elseif (isset($_GET['search'])): ?>
            <div class="alert alert-warning py-2 small">
                <i class="fas fa-exclamation-triangle"></i>
                <?php if (!$mark_distribution): ?>
                    এই বিষয়ের জন্য মার্কস বিভাজন সেটআপ করা হয়নি। <a href="setup.php">সেটআপ করুন</a>
                <?php elseif (empty($students)): ?>
                    কোনো শিক্ষার্থী পাওয়া যায়নি।
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div><!-- /container -->

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    const markDist = {
        cq:         <?php echo $mark_distribution['cq_marks']         ?? 0; ?>,
        mcq:        <?php echo $mark_distribution['mcq_marks']        ?? 0; ?>,
        practical:  <?php echo $mark_distribution['practical_marks']  ?? 0; ?>,
        assignment: <?php echo $mark_distribution['assignment_marks'] ?? 0; ?>,
        attendance: <?php echo $mark_distribution['attendance_marks'] ?? 0; ?>,
        total:      <?php echo $mark_distribution['total_marks']      ?? 0; ?>,
        pass:       <?php echo $mark_distribution['overall_pass_marks'] ?? $mark_distribution['pass_marks'] ?? 0; ?>,
        cqPass:     <?php echo $mark_distribution['cq_pass_marks']     ?? 0; ?>,
        mcqPass:    <?php echo $mark_distribution['mcq_pass_marks']    ?? 0; ?>,
        pracPass:   <?php echo $mark_distribution['practical_pass_marks'] ?? 0; ?>
    };

    function calculateTotal(studentId) {
        let total = 0;
        const marks = {};
        document.querySelectorAll(`.mark-input[data-student="${studentId}"]`).forEach(inp => {
            const v = parseFloat(inp.value) || 0;
            total += v;
            marks[inp.dataset.type] = v;
        });
        const totalEl = document.querySelector(`.total-marks[data-student="${studentId}"]`);
        const gradeEl = document.querySelector(`.grade-badge[data-student="${studentId}"]`);
        if (totalEl) totalEl.textContent = total.toFixed(1).replace('.0','');
        if (gradeEl) {
            const g = getGrade(total, markDist.total, marks);
            gradeEl.textContent = g;
            gradeEl.className = 'badge grade-badge bg-' + gradeColor(g);
        }
    }

    function getGrade(marks, total, individual) {
        if (!total) return 'N/A';
        if (individual) {
            if (markDist.cqPass > 0 && markDist.cq > 0 && (individual.cq || 0) < markDist.cqPass) return 'F';
            if (markDist.mcqPass > 0 && markDist.mcq > 0 && (individual.mcq || 0) < markDist.mcqPass) return 'F';
            if (markDist.pracPass > 0 && markDist.practical > 0 && (individual.practical || 0) < markDist.pracPass) return 'F';
        }
        if (markDist.pass > 0 && marks < markDist.pass) return 'F';
        const p = (marks / total) * 100;
        if (p >= 80) return 'A+';
        if (p >= 70) return 'A';
        if (p >= 60) return 'A-';
        if (p >= 50) return 'B';
        if (p >= 40) return 'C';
        if (p >= 33) return 'D';
        return 'F';
    }

    function gradeColor(g) {
        const map = {'A+':'success','A':'success','A-':'primary','B':'info','C':'warning','D':'secondary','F':'danger'};
        return map[g] || 'secondary';
    }

    document.querySelectorAll('.mark-input').forEach(inp => {
        inp.addEventListener('input', function() {
            const max = parseFloat(this.max) || 0;
            const val = parseFloat(this.value) || 0;
            this.classList.toggle('over-limit', max > 0 && val > max);
            calculateTotal(this.dataset.student);
        });
    });

    function fillSampleMarks() {
        document.querySelectorAll('.mark-input').forEach(inp => {
            const max = parseFloat(inp.max) || 0;
            if (max > 0) {
                inp.value = Math.floor(max * 0.75);
                inp.dispatchEvent(new Event('input'));
            }
        });
    }

    function clearAllMarks() {
        document.querySelectorAll('.mark-input').forEach(inp => {
            inp.value = '';
            inp.classList.remove('over-limit');
        });
        document.querySelectorAll('.total-marks').forEach(el => el.textContent = '0');
        document.querySelectorAll('.grade-badge').forEach(el => { el.textContent = 'N/A'; el.className = 'badge grade-badge bg-secondary'; });
    }

    function confirmDeleteAllMarks() {
        if (confirm('সতর্কতা! এই বিষয়ের সব সেভ করা মার্কস স্থায়ীভাবে মুছে যাবে। নিশ্চিত?')) {
            const form = document.getElementById('marks-form');
            const inp = document.createElement('input');
            inp.type = 'hidden'; inp.name = 'delete_all_marks'; inp.value = '1';
            form.appendChild(inp);
            form.submit();
        }
    }

    // Init totals on load
    document.querySelectorAll('.total-marks').forEach(el => {
        const sid = el.dataset.student;
        calculateTotal(sid);
    });
    </script>
</body>
</html>
