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

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

// Quick delete handler for existing distributions (by ID)
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['delete_id'])) {
    try {
        $id = (int)$_POST['delete_id'];
        $stmt = $pdo->prepare('DELETE FROM subject_mark_distribution WHERE id = ?');
        $stmt->execute([$id]);
        if ($stmt->rowCount() > 0) {
            $success_message = 'রেকর্ড সফলভাবে মুছে ফেলা হয়েছে।';
        } else {
            $error_message = 'রেকর্ড খুঁজে পাওয়া যায়নি।';
        }
    } catch (Exception $e) {
        $error_message = 'ত্রুটি: ' . $e->getMessage();
    }
}

// Delete by filters (subject/class/session/exam/group)
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete_filters') {
    try {
        $subject_id = isset($_POST['subject_id']) ? (int)$_POST['subject_id'] : 0;
        $class_id = isset($_POST['class_id']) ? (int)$_POST['class_id'] : 0;
        $session = isset($_POST['session']) ? $_POST['session'] : '';
        $exam_type = isset($_POST['exam_type']) ? $_POST['exam_type'] : '';
        $group_name = isset($_POST['group_name']) ? $_POST['group_name'] : '';

        if ($subject_id && $class_id && $session) {
            // Handle "all exam types" selection for deletion
            if ($exam_type === 'all') {
                // Delete for all exam types
                $exam_types = ['midterm', 'final', 'test', 'assignment', 'practical'];
                $deleted_count = 0;
                
                foreach ($exam_types as $current_exam_type) {
                    $params = [$subject_id, $class_id, $session, $current_exam_type];
                    $sql = "DELETE FROM subject_mark_distribution WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ?";
                    if (!empty($group_name)) {
                        $sql .= " AND group_name = ?";
                        $params[] = $group_name;
                    } else {
                        $sql .= " AND (group_name IS NULL OR group_name = '')";
                    }
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute($params);
                    $deleted_count += $stmt->rowCount();
                }
                
                $success_message = $deleted_count > 0 ? "নির্বাচিত ফিল্টারে {$deleted_count} টি রেকর্ড মুছে ফেলা হয়েছে।" : "মিলে যাওয়া কোন রেকর্ড পাওয়া যায়নি।";
            } else if ($exam_type) {
                // Delete for specific exam type
                $params = [$subject_id, $class_id, $session, $exam_type];
                $sql = "DELETE FROM subject_mark_distribution WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ?";
                if (!empty($group_name)) {
                    $sql .= " AND group_name = ?";
                    $params[] = $group_name;
                } else {
                    $sql .= " AND (group_name IS NULL OR group_name = '')";
                }
                $stmt = $pdo->prepare($sql);
                $stmt->execute($params);
                $count = $stmt->rowCount();
                $success_message = $count > 0 ? "নির্বাচিত ফিল্টারে {$count} টি রেকর্ড মুছে ফেলা হয়েছে।" : "মিলে যাওয়া কোন রেকর্ড পাওয়া যায়নি।";
            } else {
                $error_message = 'Exam Type প্রদান করুন।';
            }
        } else {
            $error_message = 'Subject, Class এবং Session প্রদান করুন।';
        }
    } catch (Exception $e) {
        $error_message = 'ত্রুটি: ' . $e->getMessage();
    }
}

// Get data for dropdowns
$subjects = $pdo->query("SELECT id, name, code FROM subjects WHERE status = 'active' ORDER BY name")->fetchAll();
$classes = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' 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, description FROM student_groups WHERE status = 'active' ORDER BY group_name")->fetchAll();

// Get global passing percentage setting

// Handle clearing default layout
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['clear_default_layout'])) {
    unset($_SESSION['default_subject_layout']);
    $success_message = 'ডিফল্ট লেআউট সফলভাবে মুছে ফেলা হয়েছে।';
}

// Handle saving subject layout
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save_subject_layout'])) {
    $layout_name = trim($_POST['layout_name']);
    $subject_order = $_POST['subject_order'] ?? '';
    $set_as_default = isset($_POST['set_as_default']);
    
    if (!empty($layout_name) && !empty($subject_order)) {
        // Save layout to session
        error_log("Saving subject layout: $layout_name with order: $subject_order");
        $_SESSION['subject_layout_' . $layout_name] = $subject_order;
        
        // Set as default if requested
        if ($set_as_default) {
            error_log("Setting default subject layout: $layout_name");
            $_SESSION['default_subject_layout'] = $layout_name;
            $success_message = "লেআউট '$layout_name' সফলভাবে সংরক্ষিত এবং ডিফল্ট হিসেবে সেট করা হয়েছে!";
        } else {
            $success_message = "লেআউট '$layout_name' সফলভাবে সংরক্ষিত হয়েছে!";
        }
    } else {
        // More descriptive error message
        if (empty($layout_name) && empty($subject_order)) {
            $error_message = 'লেআউটের নাম এবং বিষয় ক্রম প্রদান করুন!';
        } else if (empty($layout_name)) {
            $error_message = 'লেআউটের নাম প্রদান করুন!';
        } else {
            $error_message = 'অন্ততপক্ষে একটি বিষয় ড্রপ করুন!';
        }
    }
}

// Handle form submission (save only; skip delete actions)
if (
    $_SERVER['REQUEST_METHOD'] == 'POST'
    && isset($_POST['main_form'])
    && !isset($_POST['delete_id'])
    && (!isset($_POST['action']) || $_POST['action'] !== 'delete_filters')
    && isset($_POST['subject_id'])
    && isset($_POST['class_id'])
    && isset($_POST['session'])
) {
    $subject_id = $_POST['subject_id'];
    $class_id = $_POST['class_id'];
    $session = $_POST['session'];
    $group_name = isset($_POST['group_name']) ? $_POST['group_name'] : '';
    $exam_type = isset($_POST['exam_type']) ? $_POST['exam_type'] : '';
    $total_marks = isset($_POST['total_marks']) ? $_POST['total_marks'] : 0;
    $cq_marks = isset($_POST['cq_marks']) ? $_POST['cq_marks'] : 0;
    $mcq_marks = isset($_POST['mcq_marks']) ? $_POST['mcq_marks'] : 0;
    $practical_marks = isset($_POST['practical_marks']) ? $_POST['practical_marks'] : 0;
    $assignment_marks = isset($_POST['assignment_marks']) ? $_POST['assignment_marks'] : 0;
    $attendance_marks = isset($_POST['attendance_marks']) ? $_POST['attendance_marks'] : 0;
    $overall_pass_marks = isset($_POST['overall_pass_marks']) ? $_POST['overall_pass_marks'] : 0;
    $cq_pass_marks = !empty($_POST['cq_pass_marks']) ? $_POST['cq_pass_marks'] : null;
    $mcq_pass_marks = !empty($_POST['mcq_pass_marks']) ? $_POST['mcq_pass_marks'] : null;
    $practical_pass_marks = !empty($_POST['practical_pass_marks']) ? $_POST['practical_pass_marks'] : null;
    $grade_system = isset($_POST['grade_system']) ? $_POST['grade_system'] : 'gpa';
    
    // Handle "all exam types" selection
    $exam_types_to_process = [];
    if ($exam_type === 'all') {
        $exam_types_to_process = ['midterm', 'final', 'test', 'assignment', 'practical'];
    } elseif ($exam_type === 'default') {
        // Save as 'default' — applies to all exam types via fallback
        $exam_types_to_process = ['default'];
    } else {
        $exam_types_to_process = [$exam_type];
    }

    // Handle session default
    if (empty($session)) $session = 'default';
    
    // Validate total marks
    $sum_marks = (float)$cq_marks + (float)$mcq_marks + (float)$practical_marks + (float)$assignment_marks + (float)$attendance_marks;
    if ($sum_marks != $total_marks) {
        $error_message = "মোট নম্বর ($total_marks) এবং বিভাজিত নম্বরের যোগফল ($sum_marks) সমান নয়!";
    } else {
        try {
            $success_count = 0;
            foreach ($exam_types_to_process as $current_exam_type) {
                // Normalize group_name: treat NULL/empty consistently
                $gn = ($group_name === '' || $group_name === null) ? '' : $group_name;

                // DELETE existing record first (avoids NULL unique key issue)
                $del = $pdo->prepare("DELETE FROM subject_mark_distribution 
                    WHERE subject_id=? AND class_id=? AND session=? AND exam_type=?
                    AND COALESCE(group_name,'') = ?");
                $del->execute([$subject_id, $class_id, $session, $current_exam_type, $gn]);

                // INSERT fresh
                $stmt = $pdo->prepare("
                    INSERT INTO subject_mark_distribution 
                    (subject_id, class_id, session, group_name, exam_type, total_marks, cq_marks, mcq_marks, practical_marks, assignment_marks, attendance_marks, overall_pass_marks, cq_pass_marks, mcq_pass_marks, practical_pass_marks, grade_system) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ");
                
                $stmt->execute([
                    $subject_id, $class_id, $session, $gn, $current_exam_type,
                    $total_marks, $cq_marks, $mcq_marks, $practical_marks,
                    $assignment_marks, $attendance_marks, $overall_pass_marks, 
                    $cq_pass_marks, $mcq_pass_marks, $practical_pass_marks, $grade_system
                ]);
                
                $success_count++;
            }
            
            if (count($exam_types_to_process) > 1) {
                $success_message = "মার্কস বিভাজন সব ধরনের পরীক্ষার জন্য সফলভাবে সেভ করা হয়েছে! (" . $success_count . " টি রেকর্ড)";
            } else {
                $success_message = "মার্কস বিভাজন সফলভাবে সেভ করা হয়েছে!";
            }
        } catch (Exception $e) {
            $error_message = "ত্রুটি: " . $e->getMessage();
        }
    }
}
function applySubjectLayout($distributions, $layout_name = null) {
    // If no layout specified, check for default layout
    if ($layout_name === null && isset($_SESSION['default_subject_layout'])) {
        $layout_name = $_SESSION['default_subject_layout'];
    }
    
    // If we have a layout name, apply it
    if ($layout_name !== null && isset($_SESSION['subject_layout_' . $layout_name])) {
        $saved_order = explode(',', $_SESSION['subject_layout_' . $layout_name]);
        
        // Group distributions by subject_id
        $subject_groups = [];
        foreach ($distributions as $dist) {
            $subject_groups[$dist['subject_id']][] = $dist;
        }
        
        $ordered_distributions = [];
        
        // First add subjects in the saved order
        foreach ($saved_order as $subject_id) {
            if (isset($subject_groups[$subject_id])) {
                foreach ($subject_groups[$subject_id] as $dist) {
                    $ordered_distributions[] = $dist;
                }
            }
        }
        
        // Then add any remaining subjects not in the saved order
        foreach ($subject_groups as $subject_id => $dists) {
            $found = in_array($subject_id, $saved_order);
            if (!$found) {
                foreach ($dists as $dist) {
                    $ordered_distributions[] = $dist;
                }
            }
        }
        
        return $ordered_distributions;
    }
    
    // Return original distributions if no layout to apply
    return $distributions;
}

// Get search filters
$search_session = isset($_GET['search_session']) ? $_GET['search_session'] : '';
$search_class = isset($_GET['search_class']) ? (int)$_GET['search_class'] : 0;
$search_group = isset($_GET['search_group']) ? $_GET['search_group'] : '';
$search_exam_type = isset($_GET['search_exam_type']) ? $_GET['search_exam_type'] : '';

// Get existing mark distributions with search filters
$existing_distributions = [];

if ($search_session || $search_class || $search_group || $search_exam_type) {
    // Build query with search filters
    $sql = "SELECT smd.*, s.name as subject_name, s.code as subject_code, c.name as class_name, c.section, g.group_name as group_display_name
           FROM subject_mark_distribution smd
           JOIN subjects s ON smd.subject_id = s.id
           JOIN classes c ON smd.class_id = c.id
           LEFT JOIN student_groups g ON smd.group_name = g.group_name
           WHERE 1=1";
    $params = [];
    
    if ($search_session) {
        $sql .= " AND smd.session = ?";
        $params[] = $search_session;
    }
    
    if ($search_class) {
        $sql .= " AND smd.class_id = ?";
        $params[] = $search_class;
    }
    
    if ($search_group) {
        $sql .= " AND smd.group_name = ?";
        $params[] = $search_group;
    }
    
    if ($search_exam_type) {
        $sql .= " AND smd.exam_type = ?";
        $params[] = $search_exam_type;
    }
    
    $sql .= " ORDER BY smd.session DESC, c.name, s.name, smd.exam_type";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $existing_distributions = $stmt->fetchAll();
} else {
    // Get all distributions without search
    $stmt = $pdo->query("SELECT smd.*, s.name as subject_name, s.code as subject_code, c.name as class_name, c.section, g.group_name as group_display_name
           FROM subject_mark_distribution smd
           JOIN subjects s ON smd.subject_id = s.id
           JOIN classes c ON smd.class_id = c.id
           LEFT JOIN student_groups g ON smd.group_name = g.group_name
           ORDER BY smd.session DESC, c.name, s.name, smd.exam_type");
    $existing_distributions = $stmt->fetchAll();
}

// Apply custom layout if exists
$layout_to_use = isset($_GET['layout']) ? $_GET['layout'] : null;
$existing_distributions = applySubjectLayout($existing_distributions, $layout_to_use);
?>


<!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.85rem; background: linear-gradient(135deg, #667eea15 0%, #764ba215 100%); min-height: 100vh; }
        .form-label { font-size: 0.78rem; margin-bottom: 2px; font-weight: 500; }
        .card { border-radius: 10px; border: none; }
        .card-header { padding: 0.45rem 0.75rem; }
        .card-body { padding: 0.6rem 0.75rem; }
        .badge { font-size: 0.7rem; }
        th { font-size: 0.75rem; white-space: nowrap; }
        td { font-size: 0.78rem; vertical-align: middle; }

        /* Navbar gradient */
        .navbar { background: linear-gradient(135deg, #1a237e 0%, #283593 50%, #3949ab 100%) !important; }

        /* Form card */
        .form-card-header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: #fff; border-radius: 10px 10px 0 0; }
        .form-card-body { background: linear-gradient(180deg, #f8f9ff 0%, #fff 100%); }

        /* Input highlight */
        .form-control:focus, .form-select:focus { border-color: #764ba2; box-shadow: 0 0 0 0.15rem rgba(118,75,162,0.2); }

        /* Marks summary */
        #marks-summary { border-radius: 6px; font-size: 0.72rem !important; }

        /* Table card */
        .table-card-header { background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); color: #fff; border-radius: 10px 10px 0 0; }
        .table thead.table-dark th { background: linear-gradient(135deg, #2c3e50 0%, #3d5a80 100%); border: none; }

        /* Row colors */
        .table tbody tr:nth-child(odd)  { background: #f0f4ff; }
        .table tbody tr:nth-child(even) { background: #fff; }
        .table tbody tr:hover { background: #e8f4fd !important; }

        /* Search bar */
        .search-bar { background: linear-gradient(135deg, #f093fb15 0%, #f5576c15 100%); border-radius: 8px; padding: 8px 10px; margin-bottom: 8px; }

        /* Buttons */
        .btn-save-custom { background: linear-gradient(135deg, #667eea, #764ba2); border: none; color: #fff; }
        .btn-save-custom:hover { opacity: .9; color: #fff; }
        .btn-reset-custom { background: linear-gradient(135deg, #f5576c, #f093fb); border: none; color: #fff; }
        .btn-reset-custom:hover { opacity: .9; color: #fff; }

        /* Badge colors for table */
        .badge-session  { background: linear-gradient(135deg,#667eea,#764ba2) !important; }
        .badge-group    { background: linear-gradient(135deg,#11998e,#38ef7d) !important; color:#fff !important; }
        .badge-total    { background: linear-gradient(135deg,#1a237e,#3949ab) !important; }
        .badge-cq       { background: linear-gradient(135deg,#11998e,#38ef7d) !important; color:#fff !important; }
        .badge-mcq      { background: linear-gradient(135deg,#f093fb,#f5576c) !important; }
        .badge-pass     { background: linear-gradient(135deg,#f5576c,#f093fb) !important; }
        .badge-prac     { background: linear-gradient(135deg,#f7971e,#ffd200) !important; color:#333 !important; }
        .badge-asn      { background: linear-gradient(135deg,#4facfe,#00f2fe) !important; color:#333 !important; }
        .badge-att      { background: linear-gradient(135deg,#43e97b,#38f9d7) !important; color:#333 !important; }

        /* Collapse toggle btn */
        .collapse-toggle { background: rgba(255,255,255,0.2); border: 1px solid rgba(255,255,255,0.4); color: #fff; font-size: 0.72rem; }
        .collapse-toggle:hover { background: rgba(255,255,255,0.35); color: #fff; }
    </style>
</head>
<body class="bengali-text">
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary py-1">
        <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="quick_setup.php"><i class="fas fa-bolt"></i> দ্রুত সেটআপ</a>
                <a class="nav-link px-2 py-1" href="entry.php"><i class="fas fa-edit"></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">
                <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">
                <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; ?>

        <div class="row g-2">
            <!-- Left: Setup Form -->
            <div class="col-12">
                <div class="card shadow-sm">
                    <div class="card-header form-card-header d-flex align-items-center justify-content-between">
                        <span style="font-size:0.85rem;font-weight:600;"><i class="fas fa-cog me-1"></i>মার্কস বিভাজন সেটআপ</span>
                        <button class="btn btn-sm collapse-toggle py-0 px-2" type="button" data-bs-toggle="collapse" data-bs-target="#setupFormCollapse" style="font-size:0.75rem;">
                            <i class="fas fa-chevron-down"></i> ফর্ম
                        </button>
                    </div>
                    <div class="collapse show" id="setupFormCollapse">
                    <div class="card-body form-card-body p-2">
                        <form method="POST" action="?search_session=<?php echo urlencode($search_session); ?>&search_class=<?php echo $search_class; ?>&search_group=<?php echo urlencode($search_group); ?>&search_exam_type=<?php echo urlencode($search_exam_type); ?>" class="needs-validation" novalidate>
                            <input type="hidden" name="main_form" value="1">
                            <input type="hidden" name="search_session" value="<?php echo htmlspecialchars($search_session); ?>">
                            <input type="hidden" name="search_class" value="<?php echo $search_class; ?>">
                            <input type="hidden" name="search_group" value="<?php echo htmlspecialchars($search_group); ?>">
                            <input type="hidden" name="search_exam_type" value="<?php echo htmlspecialchars($search_exam_type); ?>">

                            <!-- Row 1: Main selectors -->
                            <div class="row g-1 mb-1 align-items-end">
                                <div class="col-md-3 col-6">
                                    <label class="form-label mb-0" style="font-size:0.72rem;">বিষয় <span class="text-danger">*</span></label>
                                    <select class="form-select form-select-sm" id="subject_id" name="subject_id" required>
                                        <option value="">নির্বাচন করুন</option>
                                        <?php foreach ($subjects as $subject): ?>
                                            <option value="<?php echo $subject['id']; ?>"><?php echo $subject['name'] . ' (' . $subject['code'] . ')'; ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-2 col-6">
                                    <label class="form-label mb-0" style="font-size:0.72rem;">ক্লাস <span class="text-danger">*</span></label>
                                    <select class="form-select form-select-sm" id="class_id" name="class_id" required>
                                        <option value="">নির্বাচন</option>
                                        <?php foreach ($classes as $class): ?>
                                            <option value="<?php echo $class['id']; ?>"><?php echo $class['name'] . '-' . $class['section']; ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-2 col-6">
                                    <label class="form-label mb-0" style="font-size:0.72rem;">সেশন</label>
                                    <select class="form-select form-select-sm" id="session" name="session">
                                        <option value="default">সব সেশন (ডিফল্ট)</option>
                                        <?php foreach ($sessions as $session): ?>
                                            <option value="<?php echo $session['session_name']; ?>"><?php echo $session['session_name']; ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-2 col-6">
                                    <label class="form-label mb-0" style="font-size:0.72rem;">গ্রুপ</label>
                                    <select class="form-select form-select-sm" id="group_name" name="group_name">
                                        <option value="">সাধারণ</option>
                                        <?php foreach ($groups as $group): ?>
                                            <option value="<?php echo $group['group_name']; ?>"><?php echo $group['group_name'] . ' (' . $group['group_code'] . ')'; ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-2 col-6">
                                    <label class="form-label mb-0" style="font-size:0.72rem;">পরীক্ষার ধরন</label>
                                    <select class="form-select form-select-sm" id="exam_type" name="exam_type">
                                        <option value="default">সব পরীক্ষা (ডিফল্ট)</option>
                                        <option value="all">সব (একসাথে সেভ)</option>
                                        <option value="midterm">অর্ধবার্ষিক</option>
                                        <option value="final">বার্ষিক</option>
                                        <option value="test">টেস্ট</option>
                                        <option value="assignment">অ্যাসাইনমেন্ট</option>
                                        <option value="practical">ব্যবহারিক</option>
                                    </select>
                                </div>
                                <div class="col-md-1 col-6">
                                    <label class="form-label mb-0" style="font-size:0.72rem;">গ্রেড</label>
                                    <select class="form-select form-select-sm" id="grade_system" name="grade_system">
                                        <option value="gpa">GPA</option>
                                        <option value="letter">Letter</option>
                                        <option value="percentage">%</option>
                                    </select>
                                </div>
                            </div>

                            <!-- Row 2: Marks -->
                            <div class="row g-1 mb-1 align-items-end">
                                <div class="col-md-1 col-4">
                                    <label class="form-label mb-0" style="font-size:0.72rem;">মোট <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control form-control-sm" id="total_marks" name="total_marks" min="1" max="1000" required placeholder="মোট">
                                </div>
                                <div class="col-md-1 col-4">
                                    <label class="form-label mb-0" style="font-size:0.72rem;">পাস <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control form-control-sm" id="overall_pass_marks" name="overall_pass_marks" min="1" required placeholder="পাস">
                                </div>
                                <div class="col-md-1 col-4">
                                    <label class="form-label mb-0" style="font-size:0.72rem;">CQ</label>
                                    <input type="number" class="form-control form-control-sm mark-input" id="cq_marks" name="cq_marks" min="0" value="0">
                                </div>
                                <div class="col-md-1 col-4">
                                    <label class="form-label mb-0" style="font-size:0.72rem;">MCQ</label>
                                    <input type="number" class="form-control form-control-sm mark-input" id="mcq_marks" name="mcq_marks" min="0" value="0">
                                </div>
                                <div class="col-md-1 col-4">
                                    <label class="form-label mb-0" style="font-size:0.72rem;">ব্যবহারিক</label>
                                    <input type="number" class="form-control form-control-sm mark-input" id="practical_marks" name="practical_marks" min="0" value="0">
                                </div>
                                <div class="col-md-1 col-4">
                                    <label class="form-label mb-0" style="font-size:0.72rem;">অ্যাসাইনমেন্ট</label>
                                    <input type="number" class="form-control form-control-sm mark-input" id="assignment_marks" name="assignment_marks" min="0" value="0">
                                </div>
                                <div class="col-md-1 col-4">
                                    <label class="form-label mb-0" style="font-size:0.72rem;">উপস্থিতি</label>
                                    <input type="number" class="form-control form-control-sm mark-input" id="attendance_marks" name="attendance_marks" min="0" value="0">
                                </div>
                                <!-- Optional pass marks inline -->
                                <div class="col-md-1 col-4">
                                    <label class="form-label mb-0" style="font-size:0.72rem;">CQ পাস</label>
                                    <input type="number" class="form-control form-control-sm" id="cq_pass_marks" name="cq_pass_marks" min="0" placeholder="-">
                                </div>
                                <div class="col-md-1 col-4">
                                    <label class="form-label mb-0" style="font-size:0.72rem;">MCQ পাস</label>
                                    <input type="number" class="form-control form-control-sm" id="mcq_pass_marks" name="mcq_pass_marks" min="0" placeholder="-">
                                </div>
                                <div class="col-md-1 col-4">
                                    <label class="form-label mb-0" style="font-size:0.72rem;">Prac পাস</label>
                                    <input type="number" class="form-control form-control-sm" id="practical_pass_marks" name="practical_pass_marks" min="0" placeholder="-">
                                </div>
                                <div class="col-md-2 col-12 d-flex align-items-end gap-1">
                                    <div class="alert py-1 px-2 mb-0 flex-grow-1" id="marks-summary" style="font-size:0.72rem;white-space:nowrap;">
                                        বিভাজিত: <strong><span id="total-distributed">0</span></strong>
                                    </div>
                                </div>
                            </div>

                            <!-- Row 3: Buttons -->
                            <div class="d-flex gap-1 justify-content-end">
                                <button type="submit" name="action" value="delete_filters" class="btn btn-reset-custom btn-sm py-0"
                                    onclick="return confirm('নির্বাচিত ফিল্টারের মার্কস বিভাজন ডিলিট করতে চান?');">
                                    <i class="fas fa-trash-alt"></i> রিসেট
                                </button>
                                <button type="reset" class="btn btn-secondary btn-sm py-0">
                                    <i class="fas fa-undo"></i> ক্লিয়ার
                                </button>
                                <button type="submit" class="btn btn-save-custom btn-sm py-0">
                                    <i class="fas fa-save"></i> সেভ
                                </button>
                            </div>
                        </form>
                    </div>
                    </div><!-- /collapse -->
                </div>
            </div>

            <!-- Right: Distributions Table -->
            <div class="col-12">
                <div class="card shadow-sm">
                    <div class="card-header table-card-header d-flex align-items-center justify-content-between">
                        <span style="font-size:0.85rem;font-weight:600;"><i class="fas fa-list me-1"></i>বিদ্যমান মার্কস বিভাজন</span>
                        <span class="badge bg-light text-dark"><?php echo count($existing_distributions); ?> টি</span>
                    </div>
                    <div class="card-body p-2">
                        <form method="GET" action="" class="search-bar mb-2">
                            <div class="row g-1 align-items-end">
                                <div class="col">
                                    <label class="form-label" style="font-size:0.75rem;">সেশন</label>
                                    <select class="form-select form-select-sm" name="search_session">
                                        <option value="">সব</option>
                                        <?php foreach ($sessions as $session): ?>
                                            <option value="<?php echo $session['session_name']; ?>" <?php echo ($search_session == $session['session_name']) ? 'selected' : ''; ?>><?php echo $session['session_name']; ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col">
                                    <label class="form-label" style="font-size:0.75rem;">ক্লাস</label>
                                    <select class="form-select form-select-sm" name="search_class">
                                        <option value="">সব</option>
                                        <?php foreach ($classes as $class): ?>
                                            <option value="<?php echo $class['id']; ?>" <?php echo ($search_class == $class['id']) ? 'selected' : ''; ?>><?php echo $class['name'] . '-' . $class['section']; ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col">
                                    <label class="form-label" style="font-size:0.75rem;">গ্রুপ</label>
                                    <select class="form-select form-select-sm" name="search_group">
                                        <option value="">সব</option>
                                        <?php foreach ($groups as $group): ?>
                                            <option value="<?php echo $group['group_name']; ?>" <?php echo ($search_group == $group['group_name']) ? 'selected' : ''; ?>><?php echo $group['group_name']; ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col">
                                    <label class="form-label" style="font-size:0.75rem;">পরীক্ষা</label>
                                    <select class="form-select form-select-sm" name="search_exam_type">
                                        <option value="">সব</option>
                                        <option value="midterm" <?php echo ($search_exam_type == 'midterm') ? 'selected' : ''; ?>>অর্ধবার্ষিক</option>
                                        <option value="final" <?php echo ($search_exam_type == 'final') ? 'selected' : ''; ?>>বার্ষিক</option>
                                        <option value="test" <?php echo ($search_exam_type == 'test') ? 'selected' : ''; ?>>টেস্ট</option>
                                        <option value="assignment" <?php echo ($search_exam_type == 'assignment') ? 'selected' : ''; ?>>অ্যাসাইনমেন্ট</option>
                                        <option value="practical" <?php echo ($search_exam_type == 'practical') ? 'selected' : ''; ?>>ব্যবহারিক</option>
                                    </select>
                                </div>
                                <div class="col-auto">
                                    <button type="submit" class="btn btn-primary btn-sm"><i class="fas fa-search"></i></button>
                                    <a href="setup.php" class="btn btn-secondary btn-sm"><i class="fas fa-times"></i></a>
                                </div>
                            </div>
                        </form>

                        <?php if (empty($existing_distributions)): ?>
                            <div class="alert alert-info py-2 text-center small">
                                <i class="fas fa-info-circle"></i> কোন মার্কস বিভাজন পাওয়া যায়নি
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-sm table-striped table-hover align-middle mb-0" style="font-size:0.75rem;">
                                    <thead class="table-dark">
                                        <tr>
                                            <th>বিষয়</th>
                                            <th>ক্লাস</th>
                                            <th>সেশন</th>
                                            <th>গ্রুপ</th>
                                            <th>পরীক্ষা</th>
                                            <th>মোট</th>
                                            <th>CQ</th>
                                            <th>MCQ</th>
                                            <th>পাস</th>
                                            <th class="text-center">অ্যাকশন</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php
                                        $exam_labels = ['midterm'=>'অর্ধবার্ষিক','final'=>'বার্ষিক','test'=>'টেস্ট','assignment'=>'অ্যাসাইনমেন্ট','practical'=>'ব্যবহারিক','all'=>'সব','default'=>'ডিফল্ট'];
                                        foreach ($existing_distributions as $dist): ?>
                                            <tr>
                                                <td class="fw-semibold" style="white-space:nowrap;"><?php echo $dist['subject_name']; ?> <small class="text-muted">(<?php echo $dist['subject_code']; ?>)</small></td>
                                                <td style="white-space:nowrap;"><?php echo $dist['class_name'] . '-' . $dist['section']; ?></td>
                                                <td><span class="badge badge-session" style="font-size:0.68rem;"><?php echo $dist['session']; ?></span></td>
                                                <td><span class="badge badge-group" style="font-size:0.68rem;"><?php echo $dist['group_display_name'] ?: 'সাধারণ'; ?></span></td>
                                                <td style="white-space:nowrap;"><?php echo $exam_labels[$dist['exam_type']] ?? $dist['exam_type']; ?></td>
                                                <td class="fw-bold" style="color:#1a237e;"><?php echo $dist['total_marks']; ?></td>
                                                <td><?php echo $dist['cq_marks']; ?></td>
                                                <td><?php echo $dist['mcq_marks']; ?></td>
                                                <td class="fw-bold" style="color:#c62828;"><?php echo $dist['overall_pass_marks'] ?? $dist['pass_marks'] ?? '-'; ?></td>
                                                <td class="text-center" style="white-space:nowrap;">
                                                    <button class="btn btn-outline-primary btn-sm edit-btn py-0 px-1" title="এডিট"
                                                        data-subject="<?php echo $dist['subject_id']; ?>"
                                                        data-class="<?php echo $dist['class_id']; ?>"
                                                        data-session="<?php echo $dist['session']; ?>"
                                                        data-group="<?php echo $dist['group_name']; ?>"
                                                        data-exam="<?php echo $dist['exam_type']; ?>"
                                                        data-total="<?php echo $dist['total_marks']; ?>"
                                                        data-cq="<?php echo $dist['cq_marks']; ?>"
                                                        data-mcq="<?php echo $dist['mcq_marks']; ?>"
                                                        data-practical="<?php echo $dist['practical_marks']; ?>"
                                                        data-assignment="<?php echo $dist['assignment_marks']; ?>"
                                                        data-attendance="<?php echo $dist['attendance_marks']; ?>"
                                                        data-overall-pass="<?php echo $dist['overall_pass_marks'] ?? $dist['pass_marks'] ?? ''; ?>"
                                                        data-cq-pass="<?php echo $dist['cq_pass_marks'] ?? ''; ?>"
                                                        data-mcq-pass="<?php echo $dist['mcq_pass_marks'] ?? ''; ?>"
                                                        data-practical-pass="<?php echo $dist['practical_pass_marks'] ?? ''; ?>"
                                                        data-grade="<?php echo $dist['grade_system']; ?>">
                                                        <i class="fas fa-edit"></i>
                                                    </button>
                                                    <form method="POST" action="?search_session=<?php echo urlencode($search_session); ?>&search_class=<?php echo $search_class; ?>&search_group=<?php echo urlencode($search_group); ?>&search_exam_type=<?php echo urlencode($search_exam_type); ?>" onsubmit="return confirm('ডিলিট করতে চান?');" style="display:inline;">
                                                        <input type="hidden" name="delete_id" value="<?php echo $dist['id']; ?>">
                                                        <button type="submit" class="btn btn-outline-danger btn-sm py-0 px-1" title="ডিলিট"><i class="fas fa-trash-alt"></i></button>
                                                    </form>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function updateMarksTotal() {
            let total = 0;
            document.querySelectorAll('.mark-input').forEach(i => total += parseInt(i.value) || 0);
            document.getElementById('total-distributed').textContent = total;
            const totalMarks = parseInt(document.getElementById('total_marks').value) || 0;
            const el = document.getElementById('marks-summary');
            if (total === totalMarks && totalMarks > 0) {
                el.className = 'alert alert-success py-1 px-2 mt-1 mb-0';
                el.innerHTML = '<strong><i class="fas fa-check me-1"></i>বিভাজিত: ' + total + ' ✓</strong>';
            } else if (total > totalMarks) {
                el.className = 'alert alert-danger py-1 px-2 mt-1 mb-0';
                el.innerHTML = '<strong><i class="fas fa-exclamation-triangle me-1"></i>বিভাজিত: ' + total + ' (বেশি)</strong>';
            } else {
                el.className = 'alert alert-warning py-1 px-2 mt-1 mb-0';
                el.innerHTML = '<strong>বিভাজিত: ' + total + '</strong>';
            }
        }

        document.querySelectorAll('.mark-input').forEach(i => i.addEventListener('input', updateMarksTotal));
        document.getElementById('total_marks').addEventListener('input', updateMarksTotal);

        document.querySelectorAll('.edit-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                document.getElementById('subject_id').value = this.dataset.subject || '';
                document.getElementById('class_id').value = this.dataset.class || '';
                document.getElementById('session').value = this.dataset.session || '';
                document.getElementById('group_name').value = this.dataset.group || '';
                const examType = this.dataset.exam || '';
                document.getElementById('exam_type').value = examType === 'all' ? 'midterm' : examType;
                document.getElementById('total_marks').value = this.dataset.total || 0;
                document.getElementById('cq_marks').value = this.dataset.cq || 0;
                document.getElementById('mcq_marks').value = this.dataset.mcq || 0;
                document.getElementById('practical_marks').value = this.dataset.practical || 0;
                document.getElementById('assignment_marks').value = this.dataset.assignment || 0;
                document.getElementById('attendance_marks').value = this.dataset.attendance || 0;
                document.getElementById('overall_pass_marks').value = this.dataset.overallPass || 0;
                document.getElementById('cq_pass_marks').value = this.dataset.cqPass || '';
                document.getElementById('mcq_pass_marks').value = this.dataset.mcqPass || '';
                document.getElementById('practical_pass_marks').value = this.dataset.practicalPass || '';
                document.getElementById('grade_system').value = this.dataset.grade || 'gpa';
                updateMarksTotal();
                document.querySelector('.card').scrollIntoView({ behavior: 'smooth' });
            });
        });

        (() => {
            'use strict';
            window.addEventListener('load', () => {
                document.querySelectorAll('.needs-validation').forEach(form => {
                    form.addEventListener('submit', e => {
                        if (!form.checkValidity()) { e.preventDefault(); e.stopPropagation(); }
                        form.classList.add('was-validated');
                    });
                });
            });
        })();

        updateMarksTotal();
    </script>
</body>
</html>
