<?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();

// 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 = '';

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

// Get teacher's assigned classes and subjects
$assigned_classes = [];
$assigned_subjects = [];
$assigned_class_ids = [];
$teacher_sections = [];
$teacher_classrooms = [];

if ($teacher_id) {
    $assigned_class_ids = get_teacher_assigned_classes($teacher_id);

    // Get detailed class information
    if (!empty($assigned_class_ids)) {
        $placeholders = str_repeat('?,', count($assigned_class_ids) - 1) . '?';
        $stmt = $pdo->prepare("
            SELECT DISTINCT c.id, c.name, c.section
            FROM classes c
            WHERE c.id IN ($placeholders) AND c.status = 'active'
            ORDER BY c.name, c.section
        ");
        $stmt->execute($assigned_class_ids);
        $assigned_classes = $stmt->fetchAll();
    }

    // Get assigned subjects
    $assigned_subjects = get_teacher_assigned_subjects($teacher_id, $assigned_class_ids);
    if (!empty($assigned_subjects)) {
        $placeholders = str_repeat('?,', count($assigned_subjects) - 1) . '?';
        $stmt = $pdo->prepare("
            SELECT DISTINCT s.id, s.name, s.code
            FROM subjects s
            WHERE s.id IN ($placeholders) AND s.status = 'active'
            ORDER BY s.name
        ");
        $stmt->execute($assigned_subjects);
        $assigned_subjects = $stmt->fetchAll();
    }
}

// Selected group/section filter
$selected_section = $_GET['section'] ?? '';

$students = [];
$mark_distribution = null;

// Get data for dropdowns
$classes  = $assigned_classes;
$subjects = $assigned_subjects;
$sessions = $pdo->query("SELECT session_name FROM academic_sessions WHERE status = 'active' ORDER BY session_name DESC")->fetchAll();
// Load school branches for filter dropdown
$branches = [];
try {
    $branches = $pdo->query("SELECT id, branch_name FROM school_branches WHERE status='active' ORDER BY branch_name")->fetchAll();
} catch (Exception $e) {}
$selected_branch = (int)($_GET['branch_id'] ?? 0);

// Handle search for students
if (isset($_GET['search']) && $_GET['search'] == '1') {
    $subject_id = $_GET['subject_id'] ?? 0;
    $class_id = $_GET['class_id'] ?? 0;
    $session = $_GET['session'] ?? '';
    $group_name = $_GET['group_name'] ?? '';
    $exam_type = $_GET['exam_type'] ?? 'midterm';
    $filter_branch = $selected_branch; // from GET branch_id

    // Validate that teacher has access to this class and subject
    $access_validation = validate_teacher_class_subject_access($teacher_id, $class_id, $subject_id);
    if (!$access_validation['valid']) {
        $error_message = $access_validation['error'];
    } else {
        // Get 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 = ?
            ");
            $stmt->execute([$subject_id, $class_id, $session, $exam_type, $group_name]);
        }
        $mark_distribution = $stmt->fetch();
        
        // If not found in subject_mark_distribution, try mark_distributions table
        if (!$mark_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();
        }
        
        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 WHERE conditions
            $whereParts = [];
            $executeParams_base = [];

            if (!empty($actual_group_name)) {
                $whereParts[] = "s.group_name = ?";
            }
            if ($filter_branch > 0) {
                $whereParts[] = "s.branch_id = ?";
            }
            $whereGroup = !empty($whereParts) ? 'AND ' . implode(' AND ', $whereParts) : '';

            $stmt = $pdo->prepare("
                SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number,
                       s.group_name, c.section AS student_section,
                       sb.branch_name AS student_branch,
                       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
                FROM students s
                LEFT JOIN classes c ON s.class_id = c.id
                LEFT JOIN school_branches sb ON s.branch_id = sb.id
                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
                WHERE s.class_id = ? AND s.session = ? $whereGroup AND s.status = 'active'
                ORDER BY s.roll_number, s.first_name
            ");

            // Build execute parameters
            $executeParams = [$subject_id, $subject_id, $session, $exam_type, $class_id, $session];
            if (!empty($actual_group_name)) { $executeParams[] = $actual_group_name; }
            if ($filter_branch > 0)         { $executeParams[] = $filter_branch; }
            
            $stmt->execute($executeParams);
            $students = $stmt->fetchAll();
        }
    }
}

// Handle marks submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save_marks'])) {
    $subject_id = $_POST['subject_id'] ?? 0;
    $class_id = $_POST['class_id'] ?? 0;
    $session = $_POST['session'] ?? '';
    $exam_type = $_POST['exam_type'] ?? 'midterm';

    // Validate that teacher has access to this class and subject
    $access_validation = validate_teacher_class_subject_access($teacher_id, $class_id, $subject_id);
    if (!$access_validation['valid']) {
        $error_message = $access_validation['error'];
    } else {
        try {
            $pdo->beginTransaction();
            
            // Process each student's marks
            if (isset($_POST['students']) && is_array($_POST['students'])) {
                foreach ($_POST['students'] as $student_id => $marks) {
                    $cq_marks = (float)($marks['cq'] ?? 0);
                    $mcq_marks = (float)($marks['mcq'] ?? 0);
                    $practical_marks = (float)($marks['practical'] ?? 0);
                    $assignment_marks = (float)($marks['assignment'] ?? 0);
                    $attendance_marks = (float)($marks['attendance'] ?? 0);
                    
                    // Calculate total marks
                    $total_marks = (float)$cq_marks + (float)$mcq_marks + (float)$practical_marks + (float)$assignment_marks + (float)$attendance_marks;
                    
                    // Calculate grade (simplified)
                    $grade = 'F';
                    $is_fail = false;

                    // Check individual pass marks
                    $cq_pass   = (float)($mark_distribution['cq_pass_marks']   ?? 0);
                    $mcq_pass  = (float)($mark_distribution['mcq_pass_marks']  ?? 0);
                    $prac_pass = (float)($mark_distribution['practical_pass_marks'] ?? 0);
                    $over_pass = (float)($mark_distribution['overall_pass_marks']   ?? 0);

                    if ($cq_pass   > 0 && $cq_marks   < $cq_pass)   $is_fail = true;
                    if ($mcq_pass  > 0 && $mcq_marks  < $mcq_pass)  $is_fail = true;
                    if ($prac_pass > 0 && $practical_marks < $prac_pass) $is_fail = true;
                    if ($over_pass > 0 && $total_marks < $over_pass) $is_fail = true;
                    // If no overall_pass_marks set, fallback to 33% of total
                    if ($over_pass == 0 && $total_marks < ($mark_distribution['total_marks'] ?? 100) * 0.33) $is_fail = true;

                    if (!$is_fail) {
                        if ($total_marks >= 80)      $grade = 'A+';
                        elseif ($total_marks >= 70)  $grade = 'A';
                        elseif ($total_marks >= 60)  $grade = 'A-';
                        elseif ($total_marks >= 50)  $grade = 'B';
                        elseif ($total_marks >= 40)  $grade = 'C';
                        elseif ($total_marks >= 33)  $grade = 'D';
                        else                         $grade = 'F';
                    }
                    
                    // Check if result already exists for this student/subject/exam
                    $stmt = $pdo->prepare("
                        SELECT id FROM results 
                        WHERE student_id = ? AND subject_id = ? AND session = ? AND exam_type = ?
                        ORDER BY id DESC LIMIT 1
                    ");
                    $stmt->execute([$student_id, $subject_id, $session, $exam_type]);
                    $existing_result = $stmt->fetch();
                    
                    if ($existing_result) {
                        // Update existing result
                        $stmt = $pdo->prepare("
                            UPDATE results SET 
                                cq_marks = ?, mcq_marks = ?, practical_marks = ?, 
                                assignment_marks = ?, attendance_marks = ?, 
                                marks_obtained = ?, grade = ?, updated_at = NOW()
                            WHERE id = ?
                        ");
                        $stmt->execute([
                            $cq_marks, $mcq_marks, $practical_marks, 
                            $assignment_marks, $attendance_marks, 
                            $total_marks, $grade, $existing_result['id']
                        ]);
                    } else {
                        // Insert new result
                        $stmt = $pdo->prepare("
                            INSERT INTO results 
                            (student_id, subject_id, exam_id, session, exam_type, 
                             cq_marks, mcq_marks, practical_marks, assignment_marks, attendance_marks, 
                             marks_obtained, grade, created_at, updated_at)
                            VALUES (?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
                        ");
                        $stmt->execute([
                            $student_id, $subject_id, $session, $exam_type,
                            $cq_marks, $mcq_marks, $practical_marks, 
                            $assignment_marks, $attendance_marks, 
                            $total_marks, $grade
                        ]);
                    }
                }
            }
            
            $pdo->commit();
            header('Location: marks_entry.php?saved=1');
            exit();
            
        } 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="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<style>
*{font-family:'Hind Siliguri',sans-serif}body{background:#eef1f5}
.hd{background:linear-gradient(135deg,#006747,#004d35);color:#fff;border-radius:14px;padding:18px 22px;margin-bottom:18px;box-shadow:0 6px 18px rgba(0,103,71,.25)}
.hd h4{font-weight:700;margin:0}.hd p{margin:3px 0 0;opacity:.85;font-size:.88rem}
.sc{background:#fff;border-radius:12px;padding:14px 18px;margin-bottom:16px;box-shadow:0 2px 8px rgba(0,0,0,.06)}
.fl{font-size:.78rem;font-weight:600;color:#555;margin-bottom:3px}
.fg select,.fg input{border-radius:7px;border:1.5px solid #ddd;font-size:.85rem;padding:5px 10px}.fg select:focus,.fg input:focus{border-color:#006747;box-shadow:0 0 0 3px rgba(0,103,71,.1)}
.mi{width:72px!important;text-align:center;font-size:.82rem;padding:3px 4px!important;border-radius:6px!important;border:1.5px solid #ddd!important;transition:.2s}
.mi:focus{border-color:#006747!important;box-shadow:0 0 0 3px rgba(0,103,71,.1)!important}
.tm{font-weight:700;background:#f0fdf4;color:#006747;border-radius:6px;padding:2px 8px;display:inline-block;min-width:36px}
.grd{font-size:.75rem;font-weight:700;padding:2px 8px;border-radius:10px;display:inline-block;min-width:28px;text-align:center}
.grd.ga{background:#d4f5e9;color:#028a5b}
.grd.gb{background:#e8f0fb;color:#3a0ca3}
.grd.gc{background:#fff3e0;color:#c96a00}
.grd.gf{background:#fde8e8;color:#c0392b;animation:failpulse .8s ease-in-out 2}
@keyframes failpulse{0%,100%{transform:scale(1)}50%{transform:scale(1.15)}}
.md{background:linear-gradient(135deg,#f0fdf4,#e8f5e9);border:1px solid #c8e6c9;border-radius:10px;padding:12px 16px;margin-bottom:14px}
.md .l{font-weight:600;color:#006747;font-size:.82rem}.md .v{font-size:.85rem}.md .v small{color:#888;font-size:.72rem}
.qa{display:flex;gap:5px;flex-wrap:wrap;margin-bottom:14px}.qa button{font-size:.78rem!important;padding:4px 10px!important;border-radius:7px!important;font-weight:600!important;border:none!important}
.tw{background:#fff;border-radius:12px;overflow:hidden;box-shadow:0 2px 10px rgba(0,0,0,.06)}
.tw table{margin:0}.tw thead{background:linear-gradient(135deg,#006747,#004d35);color:#fff}
.tw th{font-size:.78rem;font-weight:600;padding:8px 10px!important;border:none;white-space:nowrap;position:sticky;top:0;z-index:2}
.tw td{padding:6px 8px!important;font-size:.82rem;border-bottom:1px solid #f0f0f0;vertical-align:middle}
.tw tbody tr:hover{background:#f0fdf4}
.sb{display:inline-block;padding:1px 8px;font-size:.7rem;border-radius:8px;font-weight:500}
.ac{border-radius:10px;padding:10px 14px;font-size:.88rem;margin-bottom:14px;display:flex;align-items:center;gap:8px}
.em{text-align:center;padding:50px 20px;color:#999}.em i{font-size:3rem;opacity:.25}.em h5{margin-top:10px}
@media(max-width:768px){.mi{width:60px!important}}
@media print{body{background:#fff}.np{display:none!important}}
</style>
</head><body>
<div class="container-fluid p-3">
<div class="hd d-flex justify-content-between align-items-center flex-wrap gap-2 np">
<div><h4><i class="fas fa-edit"></i> মার্কস এন্ট্রি</h4><p>আপনার নির্ধারিত বিষয় ও ক্লাসের জন্য মার্কস এন্ট্রি করুন</p></div>
<a href="dashboard.php" class="btn btn-light btn-sm fw-bold"><i class="fas fa-arrow-left"></i> ড্যাশবোর্ড</a>
</div>

<?php if($success_message):?>
<div class="alert alert-success ac alert-dismissible fade show py-2"><i class="fas fa-check-circle" style="color:#006747"></i> <?=$success_message?><button type="button" class="btn-close py-2" data-bs-dismiss="alert"></button></div>
<?php endif;?>
<?php if($error_message):?>
<div class="alert alert-danger ac alert-dismissible fade show py-2"><i class="fas fa-exclamation-triangle" style="color:#dc3545"></i> <?=$error_message?><button type="button" class="btn-close py-2" data-bs-dismiss="alert"></button></div>
<?php endif;?>

<div class="sc np">
<form method="GET" class="row g-2">
<input type="hidden" name="search" value="1">
<div class="col-6 col-md-3"><div class="fg"><label class="fl">বিষয় <span class="text-danger">*</span></label>
<select class="form-select form-select-sm" name="subject_id" required>
<option value="">বিষয়</option>
<?php foreach($subjects as $sub):?>
<option value="<?=$sub['id']?>" <?=(isset($_GET['subject_id'])&&$_GET['subject_id']==$sub['id'])?'selected':''?>><?=htmlspecialchars($sub['name'].' ('.$sub['code'].')')?></option>
<?php endforeach;?>
</select></div></div>
<div class="col-6 col-md-2"><div class="fg"><label class="fl">ক্লাস <span class="text-danger">*</span></label>
<select class="form-select form-select-sm" name="class_id" required onchange="loadGroups(this.value)">
<option value="">ক্লাস</option>
<?php foreach($classes as $c):?>
<option value="<?=$c['id']?>" <?=(isset($_GET['class_id'])&&$_GET['class_id']==$c['id'])?'selected':''?>><?=htmlspecialchars($c['name'].($c['section']?'-'.$c['section']:''))?></option>
<?php endforeach;?>
</select></div></div>
<div class="col-6 col-md-2"><div class="fg"><label class="fl">গ্রুপ</label>
<select class="form-select form-select-sm" name="group_name" id="group_name">
<option value="">সব</option>
<?php if(!empty($_GET['class_id'])){$gs=$pdo->prepare("SELECT DISTINCT group_name FROM class_subjects WHERE class_id=? AND group_name IS NOT NULL AND group_name!='' ORDER BY group_name");$gs->execute([(int)$_GET['class_id']]);foreach($gs->fetchAll(PDO::FETCH_COLUMN)as$pg):?>
<option value="<?=htmlspecialchars($pg)?>" <?=(isset($_GET['group_name'])&&$_GET['group_name']===$pg)?'selected':''?>><?=htmlspecialchars($pg)?></option>
<?php endforeach;}?>
</select></div></div>
<?php if(!empty($branches)):?>
<div class="col-6 col-md-2"><div class="fg"><label class="fl">শাখা</label>
<select class="form-select form-select-sm" name="branch_id">
<option value="0">সব</option>
<?php foreach($branches as $br):?>
<option value="<?=$br['id']?>" <?=$selected_branch==$br['id']?'selected':''?>><?=htmlspecialchars($br['branch_name'])?></option>
<?php endforeach;?>
</select></div></div>
<?php endif;?>
<div class="col-6 col-md-1"><div class="fg"><label class="fl">সেশন <span class="text-danger">*</span></label>
<select class="form-select form-select-sm" name="session" required>
<option value="">সেশন</option>
<?php foreach($sessions as $s):?>
<option value="<?=$s['session_name']?>" <?=(isset($_GET['session'])&&$_GET['session']==$s['session_name'])?'selected':''?>><?=htmlspecialchars($s['session_name'])?></option>
<?php endforeach;?>
</select></div></div>
<div class="col-6 col-md-2"><div class="fg"><label class="fl">পরীক্ষা <span class="text-danger">*</span></label>
<select class="form-select form-select-sm" name="exam_type" required>
<?php $exT=['midterm'=>'অর্ধবার্ষিক','final'=>'বার্ষিক','test'=>'টেস্ট','assignment'=>'অ্যাসাইনমেন্ট','practical'=>'প্র্যাকটিক্যাল'];foreach($exT as $ek=>$ev):?>
<option value="<?=$ek?>" <?=(isset($_GET['exam_type'])&&$_GET['exam_type']==$ek)?'selected':''?>><?=$ev?></option>
<?php endforeach;?>
</select></div></div>
<div class="col-12 text-end pt-2">
<button type="submit" class="btn btn-sm fw-bold" style="background:linear-gradient(135deg,#006747,#00a86b);color:#fff;border:none;border-radius:7px;padding:6px 16px"><i class="fas fa-search"></i> খুঁজুন</button>
</div>
</form>
</div>

<?php if(!empty($students)&&$mark_distribution):?>
<div class="md">
<div class="d-flex align-items-center gap-2 flex-wrap"><i class="fas fa-info-circle" style="color:#006747"></i><strong style="font-size:.88rem">মার্কস বিভাজন</strong></div>
<div class="row g-2 mt-1">
<div class="col-6 col-md"><div class="l">মোট</div><div class="v"><?=$mark_distribution['total_marks']?></div></div>
<?php foreach(['cq_marks'=>'CQ','mcq_marks'=>'MCQ','practical_marks'=>'Practical','assignment_marks'=>'Assignment','attendance_marks'=>'Attendance'] as $mk=>$ml):?>
<?php if($mark_distribution[$mk]>0):?>
<div class="col-6 col-md"><div class="l"><?=$ml?></div><div class="v"><?=$mark_distribution[$mk]?> <?php $pk=$mk.'_pass_marks';if(!empty($mark_distribution[$pk])):?><small>(পাস: <?=$mark_distribution[$pk]?>)</small><?php endif;?></div></div>
<?php endif;endforeach;?>
<?php if(!empty($mark_distribution['overall_pass_marks'])):?>
<div class="col-6 col-md"><div class="l">পাস নম্বর</div><div class="v"><?=$mark_distribution['overall_pass_marks']?></div></div>
<?php endif;?>
</div>
</div>

<form method="POST">
<input type="hidden" name="subject_id" value="<?=htmlspecialchars($_GET['subject_id']??'')?>">
<input type="hidden" name="class_id" value="<?=htmlspecialchars($_GET['class_id']??'')?>">
<input type="hidden" name="session" value="<?=htmlspecialchars($_GET['session']??'')?>">
<input type="hidden" name="exam_type" value="<?=htmlspecialchars($_GET['exam_type']??'midterm')?>">
<input type="hidden" name="branch_id" value="<?=htmlspecialchars($_GET['branch_id']??'0')?>">

<div class="qa">
<?php $qac=['cq'=>'success','mcq'=>'primary','practical'=>'info','assignment'=>'warning','attendance'=>'secondary'];foreach($qac as $qk=>$qc):?>
<?php if($mark_distribution[$qk.'_marks']>0):?>
<button type="button" class="btn btn-<?=$qc?> qab" data-field="<?=$qk?>"><i class="fas fa-plus-circle"></i> <?=ucfirst($qk)?> সর্বোচ্চ</button>
<?php endif;endforeach;?>
<button type="button" class="btn btn-danger qab" id="ca"><i class="fas fa-trash"></i> সব মুছুন</button>
</div>

<div class="tw">
<div style="max-height:70vh;overflow-y:auto">
<table class="table">
<thead><tr>
<th>ছাত্র</th><th>রোল</th><th>শাখা</th><th>গ্রুপ</th>
<?php foreach(['cq_marks'=>'CQ','mcq_marks'=>'MCQ','practical_marks'=>'Practical','assignment_marks'=>'Assignment','attendance_marks'=>'Attendance'] as $mk=>$ml):?>
<?php if($mark_distribution[$mk]>0):?><th class="text-center"><?=$ml?>(<?=$mark_distribution[$mk]?>)</th><?php endif;endforeach;?>
<th class="text-center">Total</th><th class="text-center">Grade</th>
</tr></thead>
<tbody>
<?php foreach($students as $st):?>
<tr>
<td><strong style="font-size:.82rem"><?=htmlspecialchars($st['first_name'].' '.$st['last_name'])?></strong></td>
<td><?=htmlspecialchars($st['roll_number'])?></td>
<td><?php if($st['student_branch']):?><span class="sb" style="background:#e8f5e9;color:#006747"><?=htmlspecialchars($st['student_branch'])?></span><?php elseif($st['student_section']):?><span class="sb" style="background:#f0f0f0;color:#666"><?=htmlspecialchars($st['student_section'])?></span><?php else:?><span class="text-muted">—</span><?php endif;?></td>
<td><?php if($st['group_name']):?><span class="sb" style="background:#e3f2fd;color:#1565c0"><?=htmlspecialchars($st['group_name'])?></span><?php else:?><span class="text-muted">—</span><?php endif;?></td>
<?php foreach(['cq','mcq','practical','assignment','attendance'] as $fk):?>
<?php if($mark_distribution[$fk.'_marks']>0):?>
<td class="text-center"><input type="number" step="0.5" min="0" max="<?=$mark_distribution[$fk.'_marks']?>" class="form-control form-control-sm mi" name="students[<?=$st['id']?>][<?=$fk?>]" value="<?=$st[$fk.'_marks']??''?>" data-max="<?=$mark_distribution[$fk.'_marks']?>" data-field="<?=$fk?>"></td>
<?php endif;endforeach;?>
<td class="text-center"><span class="tm" id="t_<?=$st['id']?>"><?=($st['cq_marks']??0)+($st['mcq_marks']??0)+($st['practical_marks']??0)+($st['assignment_marks']??0)+($st['attendance_marks']??0)?></span></td>
<td class="text-center"><span id="g_<?=$st['id']?>" class="grd <?php
    $g=$st['grade']??'';
    if($g==='A+'||$g==='A'||$g==='A-') echo 'ga';
    elseif($g==='B'||$g==='C'||$g==='D') echo 'gc';
    elseif($g==='F') echo 'gf';
?>"><?=htmlspecialchars($g)?></span></td>
</tr>
<?php endforeach;?>
</tbody>
</table>
</div>
</div>

<div class="text-end mt-3 mb-2">
<button type="submit" name="save_marks" class="btn fw-bold" style="background:linear-gradient(135deg,#006747,#00a86b);color:#fff;border:none;border-radius:8px;padding:8px 22px;font-size:.92rem"><i class="fas fa-save"></i> মার্কস সেভ করুন</button>
</div>
</form>

<?php elseif(isset($_GET['search'])&&$_GET['search']=='1'):?>
<div class="em"><i class="fas fa-search"></i><h5>কোন ছাত্র-ছাত্রী পাওয়া যায়নি</h5><p class="small text-muted">নির্বাচিত মানদণ্ডের জন্য কোন ছাত্র পাওয়া যায়নি বা মার্কস বিভাজন নেই</p></div>
<?php endif;?>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
var md=<?=json_encode($mark_distribution ? [
    'cq_marks'            => (float)($mark_distribution['cq_marks']            ?? 0),
    'mcq_marks'           => (float)($mark_distribution['mcq_marks']           ?? 0),
    'practical_marks'     => (float)($mark_distribution['practical_marks']     ?? 0),
    'assignment_marks'    => (float)($mark_distribution['assignment_marks']    ?? 0),
    'attendance_marks'    => (float)($mark_distribution['attendance_marks']    ?? 0),
    'cq_pass_marks'       => (float)($mark_distribution['cq_pass_marks']       ?? 0),
    'mcq_pass_marks'      => (float)($mark_distribution['mcq_pass_marks']      ?? 0),
    'practical_pass_marks'=> (float)($mark_distribution['practical_pass_marks']?? 0),
    'overall_pass_marks'  => (float)($mark_distribution['overall_pass_marks']  ?? 0),
    'total_marks'         => (float)($mark_distribution['total_marks']         ?? 100),
] : [])?>;

var fl=[];
['cq','mcq','practical','assignment','attendance'].forEach(function(f){if((md[f+'_marks']||0)>0)fl.push(f);});

function calcGrade(id){
    var t=0;
    fl.forEach(function(f){var i=document.querySelector('input[name="students['+id+']['+f+']"]');if(i)t+=parseFloat(i.value)||0;});
    document.getElementById('t_'+id).textContent=t;

    // Check fail conditions
    var fail=false;
    var cqVal   =parseFloat(document.querySelector('input[name="students['+id+'][cq]"]')?.value)||0;
    var mcqVal  =parseFloat(document.querySelector('input[name="students['+id+'][mcq]"]')?.value)||0;
    var pracVal =parseFloat(document.querySelector('input[name="students['+id+'][practical]"]')?.value)||0;
    if((md.cq_pass_marks||0)>0        && cqVal  < md.cq_pass_marks)        fail=true;
    if((md.mcq_pass_marks||0)>0       && mcqVal < md.mcq_pass_marks)       fail=true;
    if((md.practical_pass_marks||0)>0 && pracVal< md.practical_pass_marks) fail=true;
    if((md.overall_pass_marks||0)>0   && t      < md.overall_pass_marks)   fail=true;
    if(!(md.overall_pass_marks>0) && t < (md.total_marks||100)*0.33)       fail=true;

    var g='F';
    if(!fail){
        if(t>=80)g='A+'; else if(t>=70)g='A'; else if(t>=60)g='A-';
        else if(t>=50)g='B'; else if(t>=40)g='C'; else if(t>=33)g='D';
        else g='F';
    }
    var gel=document.getElementById('g_'+id);
    if(gel){ gel.textContent=g; gel.className='grd '+(fail?'gf':g==='A+'?'ga':g==='A'||g==='A-'?'gb':g==='F'?'gf':'gc'); }
}
document.addEventListener('input',function(e){
if(!e.target.classList.contains('mi'))return;
var id=e.target.name.match(/\[(\d+)\]/)[1];
calcGrade(id);
});
document.querySelectorAll('.qab').forEach(function(b){
b.addEventListener('click',function(){
if(this.id==='ca'){if(!confirm('সব মার্কস মুছবেন?'))return;document.querySelectorAll('.mi').forEach(function(i){i.value='';i.dispatchEvent(new Event('input',{bubbles:true}));});return;}
var f=this.getAttribute('data-field');if(!f)return;
document.querySelectorAll('input[data-field="'+f+'"]').forEach(function(i){i.value=i.getAttribute('data-max');i.dispatchEvent(new Event('input',{bubbles:true}));});});});
// Recalculate all grades on page load
document.querySelectorAll('[id^="t_"]').forEach(function(el){calcGrade(el.id.replace('t_',''));});
function loadGroups(cid){
var s=document.getElementById('group_name');s.innerHTML='<option value="">সব</option>';if(!cid)return;
fetch('../students/get_class_subjects.php?groups=1&class_id='+encodeURIComponent(cid)).then(function(r){return r.json();}).then(function(d){
d.forEach(function(g){var n=(typeof g==='string')?g:(g.group_name||'');if(!n)return;var o=document.createElement('option');o.value=n;o.textContent=n;s.appendChild(o);});}).catch(function(){});
}
(function(){var s=document.querySelector('select[name="class_id"]');if(s&&s.value)setTimeout(function(){loadGroups(s.value);},100);})();
setTimeout(function(){document.querySelectorAll('.alert-dismissible').forEach(function(a){new bootstrap.Alert(a).close()})},5000);
</script>
</body></html>