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

// Bulk delete by filters
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] === 'bulk_delete') {
    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 && $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 = 'Subject, Class, Session এবং Exam Type প্রদান করুন।';
        }
    } 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();

// Handle form submission (save only; skip delete actions)
if (
    $_SERVER['REQUEST_METHOD'] == 'POST'
    && !isset($_POST['delete_id'])
    && (!isset($_POST['action']) || $_POST['action'] !== 'bulk_delete')
) {
    $subject_id = $_POST['subject_id'];
    $class_id = $_POST['class_id'];
    $session = $_POST['session'];
    $group_name = $_POST['group_name'];
    $exam_type = $_POST['exam_type'];
    $total_marks = $_POST['total_marks'];
    $cq_marks = $_POST['cq_marks'];
    $mcq_marks = $_POST['mcq_marks'];
    $practical_marks = $_POST['practical_marks'];
    $assignment_marks = $_POST['assignment_marks'];
    $attendance_marks = $_POST['attendance_marks'];
    $overall_pass_marks = $_POST['overall_pass_marks'];
    $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 = $_POST['grade_system'];
    
    // 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 {
            $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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE
                total_marks = VALUES(total_marks),
                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),
                overall_pass_marks = VALUES(overall_pass_marks),
                cq_pass_marks = VALUES(cq_pass_marks),
                mcq_pass_marks = VALUES(mcq_pass_marks),
                practical_pass_marks = VALUES(practical_pass_marks),
                grade_system = VALUES(grade_system),
                updated_at = CURRENT_TIMESTAMP
            ");
            
            $stmt->execute([
                $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
            ]);
            
            $success_message = "মার্কস বিভাজন সফলভাবে সেভ করা হয়েছে!";
        } catch (Exception $e) {
            $error_message = "ত্রুটি: " . $e->getMessage();
        }
    }
}

// Get existing mark distributions with pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

$total_records = $pdo->query("SELECT COUNT(*) FROM subject_mark_distribution")->fetchColumn();
$total_pages = ceil($total_records / $limit);

$existing_distributions = $pdo->prepare("
    SELECT smd.*, s.name as subject_name, s.code as subject_code, c.name as class_name, c.section
    FROM subject_mark_distribution smd
    JOIN subjects s ON smd.subject_id = s.id
    JOIN classes c ON smd.class_id = c.id
    ORDER BY smd.session DESC, c.name, s.name, smd.exam_type
    LIMIT ? OFFSET ?
");
$existing_distributions->execute([$limit, $offset]);
$existing_distributions = $existing_distributions->fetchAll();
?>

<!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.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/animate.css@4.1.1/animate.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
    <style>
        :root {
            --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --success-gradient: linear-gradient(135deg, #56ab2f 0%, #a8e6cf 100%);
            --warning-gradient: linear-gradient(135deg, #f39c12 0%, #f7dc6f 100%);
            --danger-gradient: linear-gradient(135deg, #e74c3c 0%, #f1948a 100%);
            --info-gradient: linear-gradient(135deg, #3498db 0%, #85c1e9 100%);
            --dark-gradient: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
        }

        body {
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            min-height: 100vh;
        }

        .main-container {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            margin: 20px 0;
            overflow: hidden;
        }

        .header-section {
            background: var(--primary-gradient);
            color: white;
            padding: 30px;
            text-align: center;
            position: relative;
            overflow: hidden;
        }

        .header-section::before {
            content: '';
            position: absolute;
            top: -50%;
            left: -50%;
            width: 200%;
            height: 200%;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="25" cy="25" r="1" fill="white" opacity="0.1"/><circle cx="75" cy="75" r="1" fill="white" opacity="0.1"/><circle cx="50" cy="10" r="1" fill="white" opacity="0.1"/><circle cx="10" cy="90" r="1" fill="white" opacity="0.1"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
            animation: float 20s ease-in-out infinite;
        }

        @keyframes float {
            0%, 100% { transform: translateY(0px) rotate(0deg); }
            50% { transform: translateY(-20px) rotate(180deg); }
        }

        .form-section {
            background: white;
            border-radius: 20px;
            padding: 30px;
            margin: 20px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            position: relative;
            overflow: hidden;
        }

        .form-section::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: var(--primary-gradient);
        }

        .marks-distribution-card {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border-radius: 15px;
            padding: 25px;
            margin: 20px 0;
            border: 2px solid transparent;
            background-clip: padding-box;
            position: relative;
        }

        .marks-distribution-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: var(--primary-gradient);
            border-radius: 15px;
            padding: 2px;
            mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
            mask-composite: exclude;
            z-index: -1;
        }

        .form-control, .form-select {
            border-radius: 12px;
            border: 2px solid #e9ecef;
            padding: 15px 20px;
            font-size: 16px;
            transition: all 0.3s ease;
            background: rgba(255, 255, 255, 0.9);
        }

        .form-control:focus, .form-select:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.25rem rgba(102, 126, 234, 0.15);
            transform: translateY(-2px);
            background: white;
        }

        .btn-modern {
            border-radius: 12px;
            padding: 12px 30px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 1px;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }

        .btn-modern::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
            transition: left 0.5s;
        }

        .btn-modern:hover::before {
            left: 100%;
        }

        .btn-modern:hover {
            transform: translateY(-3px);
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
        }

        .distribution-table {
            background: white;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
        }

        .table thead th {
            background: var(--primary-gradient);
            color: white;
            border: none;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 1px;
            padding: 20px 15px;
        }

        .table tbody tr {
            transition: all 0.3s ease;
            border-bottom: 1px solid #f8f9fa;
        }

        .table tbody tr:hover {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            transform: scale(1.01);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }

        .marks-summary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 20px;
            text-align: center;
            margin: 20px 0;
            position: relative;
            overflow: hidden;
        }

        .marks-summary.success {
            background: var(--success-gradient);
        }

        .marks-summary.warning {
            background: var(--warning-gradient);
        }

        .marks-summary.danger {
            background: var(--danger-gradient);
        }

        .progress-ring {
            width: 120px;
            height: 120px;
            margin: 0 auto 20px;
        }

        .progress-ring circle {
            fill: none;
            stroke-width: 8;
            stroke-linecap: round;
            transform: rotate(-90deg);
            transform-origin: 50% 50%;
            transition: stroke-dasharray 0.5s ease;
        }

        .alert-modern {
            border-radius: 15px;
            border: none;
            padding: 20px;
            margin: 20px 0;
            position: relative;
            overflow: hidden;
        }

        .alert-modern::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 4px;
            height: 100%;
            background: currentColor;
        }

        .pagination-modern .page-link {
            border-radius: 10px;
            margin: 0 5px;
            border: none;
            padding: 12px 18px;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .pagination-modern .page-link:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }

        .floating-action-btn {
            position: fixed;
            bottom: 30px;
            right: 30px;
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: var(--primary-gradient);
            color: white;
            border: none;
            font-size: 24px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
            transition: all 0.3s ease;
            z-index: 1000;
        }

        .floating-action-btn:hover {
            transform: scale(1.1) rotate(90deg);
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.3);
        }

        .stats-card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            text-align: center;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }

        .stats-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: var(--primary-gradient);
        }

        .stats-card:hover {
            transform: translateY(-10px);
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
        }

        .stats-number {
            font-size: 3rem;
            font-weight: bold;
            background: var(--primary-gradient);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        @media (max-width: 768px) {
            .main-container {
                margin: 10px;
                border-radius: 15px;
            }
            
            .form-section {
                margin: 10px;
                padding: 20px;
            }
            
            .floating-action-btn {
                bottom: 20px;
                right: 20px;
                width: 50px;
                height: 50px;
                font-size: 20px;
            }
        }
    </style>
</head>
<body class="bengali-text">
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark" style="background: var(--primary-gradient);">
        <div class="container-fluid">
            <a class="navbar-brand animate__animated animate__fadeInLeft" href="../index.php">
                <i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট সিস্টেম
            </a>
            
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            
            <div class="collapse navbar-collapse" id="navbarNav">
                <div class="navbar-nav ms-auto">
                    <a class="nav-link animate__animated animate__fadeInRight" href="../index.php">
                        <i class="fas fa-home"></i> হোম
                    </a>
                    <a class="nav-link animate__animated animate__fadeInRight" href="entry.php">
                        <i class="fas fa-edit"></i> মার্কস এন্ট্রি
                    </a>
                    <a class="nav-link animate__animated animate__fadeInRight" href="setup.php">
                        <i class="fas fa-cog"></i> সাধারণ সেটআপ
                    </a>
                    <a class="nav-link animate__animated animate__fadeInRight" href="quick_setup.php">
                        <i class="fas fa-bolt"></i> দ্রুত সেটআপ
                    </a>
                </div>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <div class="main-container animate__animated animate__fadeInUp">
            <!-- Header Section -->
            <div class="header-section">
                <h1 class="display-4 mb-3">
                    <i class="fas fa-chart-pie"></i> উন্নত মার্কস বিভাজন সেটআপ
                </h1>
                <p class="lead mb-0">বিষয় ভিত্তিক মার্কস বিভাজন এবং গ্রেডিং সিস্টেম কনফিগারেশন</p>
            </div>

            <!-- Stats Section -->
            <div class="row p-4">
                <div class="col-md-3 mb-3">
                    <div class="stats-card animate__animated animate__fadeInUp" style="animation-delay: 0.1s;">
                        <i class="fas fa-book text-primary mb-3" style="font-size: 2rem;"></i>
                        <div class="stats-number"><?php echo count($subjects); ?></div>
                        <div class="text-muted">মোট বিষয়</div>
                    </div>
                </div>
                <div class="col-md-3 mb-3">
                    <div class="stats-card animate__animated animate__fadeInUp" style="animation-delay: 0.2s;">
                        <i class="fas fa-school text-success mb-3" style="font-size: 2rem;"></i>
                        <div class="stats-number"><?php echo count($classes); ?></div>
                        <div class="text-muted">মোট ক্লাস</div>
                    </div>
                </div>
                <div class="col-md-3 mb-3">
                    <div class="stats-card animate__animated animate__fadeInUp" style="animation-delay: 0.3s;">
                        <i class="fas fa-calendar text-warning mb-3" style="font-size: 2rem;"></i>
                        <div class="stats-number"><?php echo count($sessions); ?></div>
                        <div class="text-muted">সক্রিয় সেশন</div>
                    </div>
                </div>
                <div class="col-md-3 mb-3">
                    <div class="stats-card animate__animated animate__fadeInUp" style="animation-delay: 0.4s;">
                        <i class="fas fa-cogs text-info mb-3" style="font-size: 2rem;"></i>
                        <div class="stats-number"><?php echo $total_records; ?></div>
                        <div class="text-muted">কনফিগার করা বিভাজন</div>
                    </div>
                </div>
            </div>

            <div class="row">
                <!-- Form Section -->
                <div class="col-lg-6">
                    <div class="form-section animate__animated animate__fadeInLeft">
                        <h4 class="mb-4">
                            <i class="fas fa-plus-circle text-primary"></i> নতুন মার্কস বিভাজন
                        </h4>

                        <?php if ($success_message): ?>
                            <div class="alert alert-success alert-modern animate__animated animate__bounceIn">
                                <i class="fas fa-check-circle"></i> <?php echo $success_message; ?>
                            </div>
                        <?php endif; ?>

                        <?php if ($error_message): ?>
                            <div class="alert alert-danger alert-modern animate__animated animate__shakeX">
                                <i class="fas fa-exclamation-triangle"></i> <?php echo $error_message; ?>
                            </div>
                        <?php endif; ?>

                        <form method="POST" action="" class="needs-validation" novalidate>
                            <!-- Basic Information -->
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="subject_id" class="form-label">
                                        <i class="fas fa-book text-primary"></i> বিষয় <span class="text-danger">*</span>
                                    </label>
                                    <select class="form-select" 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-6 mb-3">
                                    <label for="class_id" class="form-label">
                                        <i class="fas fa-school text-success"></i> ক্লাস <span class="text-danger">*</span>
                                    </label>
                                    <select class="form-select" id="class_id" name="class_id" required>
                                        <option value="">নির্বাচন করুন</option>
                                        <?php foreach ($classes as $class): ?>
                                            <option value="<?php echo $class['id']; ?>">
                                                <?php echo $class['name'] . ' - ' . $class['section']; ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label for="session" class="form-label">
                                        <i class="fas fa-calendar text-warning"></i> সেশন <span class="text-danger">*</span>
                                    </label>
                                    <select class="form-select" id="session" name="session" required>
                                        <option value="">নির্বাচন করুন</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-4 mb-3">
                                    <label for="group_name" class="form-label">
                                        <i class="fas fa-users text-info"></i> গ্রুপ
                                    </label>
                                    <select class="form-select" 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-4 mb-3">
                                    <label for="exam_type" class="form-label">
                                        <i class="fas fa-clipboard-list text-danger"></i> পরীক্ষার ধরন <span class="text-danger">*</span>
                                    </label>
                                    <select class="form-select" id="exam_type" name="exam_type" required>
                                        <option value="">নির্বাচন করুন</option>
                                        <option value="midterm">অর্ধবার্ষিক</option>
                                        <option value="final">বার্ষিক</option>
                                        <option value="test">টেস্ট</option>
                                        <option value="assignment">অ্যাসাইনমেন্ট</option>
                                        <option value="practical">ব্যবহারিক</option>
                                    </select>
                                </div>
                            </div>
                            
                            <!-- Total Marks Section -->
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="total_marks" class="form-label">
                                        <i class="fas fa-calculator text-primary"></i> মোট নম্বর <span class="text-danger">*</span>
                                    </label>
                                    <input type="number" class="form-control" id="total_marks" name="total_marks" min="1" max="1000" required>
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <label for="overall_pass_marks" class="form-label">
                                        <i class="fas fa-check-circle text-success"></i> সামগ্রিক পাস নম্বর <span class="text-danger">*</span>
                                    </label>
                                    <input type="number" class="form-control" id="overall_pass_marks" name="overall_pass_marks" min="1" required>
                                </div>
                            </div>
                            
                            <!-- Marks Distribution -->
                            <div class="marks-distribution-card">
                                <h6 class="mb-4">
                                    <i class="fas fa-chart-pie text-primary"></i> নম্বর বিভাজন
                                </h6>
                                
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="cq_marks" class="form-label">
                                            <i class="fas fa-pen-fancy text-primary"></i> সৃজনশীল প্রশ্ন (CQ)
                                        </label>
                                        <input type="number" class="form-control mark-input" id="cq_marks" name="cq_marks" min="0" value="0">
                                    </div>
                                    
                                    <div class="col-md-6 mb-3">
                                        <label for="mcq_marks" class="form-label">
                                            <i class="fas fa-list-ul text-success"></i> বহুনির্বাচনি (MCQ)
                                        </label>
                                        <input type="number" class="form-control mark-input" id="mcq_marks" name="mcq_marks" min="0" value="0">
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-4 mb-3">
                                        <label for="practical_marks" class="form-label">
                                            <i class="fas fa-flask text-warning"></i> ব্যবহারিক
                                        </label>
                                        <input type="number" class="form-control mark-input" id="practical_marks" name="practical_marks" min="0" value="0">
                                    </div>
                                    
                                    <div class="col-md-4 mb-3">
                                        <label for="assignment_marks" class="form-label">
                                            <i class="fas fa-tasks text-info"></i> অ্যাসাইনমেন্ট
                                        </label>
                                        <input type="number" class="form-control mark-input" id="assignment_marks" name="assignment_marks" min="0" value="0">
                                    </div>
                                    
                                    <div class="col-md-4 mb-3">
                                        <label for="attendance_marks" class="form-label">
                                            <i class="fas fa-user-check text-danger"></i> উপস্থিতি
                                        </label>
                                        <input type="number" class="form-control mark-input" id="attendance_marks" name="attendance_marks" min="0" value="0">
                                    </div>
                                </div>
                                
                                <!-- Progress Ring for Marks Distribution -->
                                <div class="text-center">
                                    <svg class="progress-ring" viewBox="0 0 120 120">
                                        <circle cx="60" cy="60" r="50" stroke="#e9ecef" stroke-width="8" fill="none"/>
                                        <circle cx="60" cy="60" r="50" stroke="#667eea" stroke-width="8" fill="none" 
                                                stroke-dasharray="0 314" id="progress-circle"/>
                                    </svg>
                                    <div class="marks-summary" id="marks-summary">
                                        <h5><i class="fas fa-calculator"></i> মোট বিভাজিত নম্বর: <span id="total-distributed">0</span></h5>
                                        <p class="mb-0" id="distribution-status">নম্বর বিভাজন করুন</p>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Separate Passing Marks -->
                            <div class="marks-distribution-card">
                                <h6 class="mb-4">
                                    <i class="fas fa-medal text-warning"></i> আলাদা পাসিং মার্কস (ঐচ্ছিক)
                                </h6>
                                
                                <div class="row">
                                    <div class="col-md-4 mb-3">
                                        <label for="cq_pass_marks" class="form-label">CQ পাসিং মার্কস</label>
                                        <input type="number" class="form-control" id="cq_pass_marks" name="cq_pass_marks" min="0" placeholder="ঐচ্ছিক">
                                    </div>
                                    
                                    <div class="col-md-4 mb-3">
                                        <label for="mcq_pass_marks" class="form-label">MCQ পাসিং মার্কস</label>
                                        <input type="number" class="form-control" id="mcq_pass_marks" name="mcq_pass_marks" min="0" placeholder="ঐচ্ছিক">
                                    </div>
                                    
                                    <div class="col-md-4 mb-3">
                                        <label for="practical_pass_marks" class="form-label">Practical পাসিং মার্কস</label>
                                        <input type="number" class="form-control" id="practical_pass_marks" name="practical_pass_marks" min="0" placeholder="ঐচ্ছিক">
                                    </div>
                                </div>
                            </div>
                            
                            <div class="mb-4">
                                <label for="grade_system" class="form-label">
                                    <i class="fas fa-star text-warning"></i> গ্রেড সিস্টেম
                                </label>
                                <select class="form-select" id="grade_system" name="grade_system">
                                    <option value="gpa">GPA</option>
                                    <option value="letter">Letter Grade</option>
                                    <option value="percentage">Percentage</option>
                                </select>
                            </div>

                            <!-- Action Buttons -->
                            <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                                <button type="submit" name="action" value="bulk_delete" class="btn btn-danger btn-modern" 
                                        onclick="return confirm('নির্বাচিত ফিল্টারের মার্কস বিভাজন ডিলিট করতে চান?');">
                                    <i class="fas fa-trash-alt"></i> বাল্ক ডিলিট
                                </button>
                                <button type="reset" class="btn btn-secondary btn-modern">
                                    <i class="fas fa-undo"></i> রিসেট
                                </button>
                                <button type="submit" class="btn btn-primary btn-modern">
                                    <i class="fas fa-save"></i> সেভ করুন
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
                
                <!-- Existing Distributions -->
                <div class="col-lg-6">
                    <div class="form-section animate__animated animate__fadeInRight">
                        <h4 class="mb-4">
                            <i class="fas fa-list text-primary"></i> বিদ্যমান মার্কস বিভাজন
                        </h4>
                        
                        <?php if (empty($existing_distributions)): ?>
                            <div class="text-center py-5">
                                <i class="fas fa-inbox text-muted" style="font-size: 4rem;"></i>
                                <h5 class="text-muted mt-3">কোন মার্কস বিভাজন পাওয়া যায়নি</h5>
                                <p class="text-muted">নতুন মার্কস বিভাজন তৈরি করুন</p>
                            </div>
                        <?php else: ?>
                            <div class="distribution-table">
                                <div class="table-responsive">
                                    <table class="table table-hover mb-0">
                                        <thead>
                                            <tr>
                                                <th><i class="fas fa-book"></i> বিষয়</th>
                                                <th><i class="fas fa-school"></i> ক্লাস</th>
                                                <th><i class="fas fa-calendar"></i> সেশন</th>
                                                <th><i class="fas fa-chart-pie"></i> বিভাজন</th>
                                                <th><i class="fas fa-cogs"></i> অ্যাকশন</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($existing_distributions as $dist): ?>
                                                <tr class="animate__animated animate__fadeInUp">
                                                    <td>
                                                        <strong><?php echo $dist['subject_name']; ?></strong><br>
                                                        <small class="text-muted"><?php echo $dist['subject_code']; ?></small>
                                                    </td>
                                                    <td>
                                                        <span class="badge bg-primary"><?php echo $dist['class_name'] . '-' . $dist['section']; ?></span><br>
                                                        <small class="text-muted"><?php echo $dist['group_name'] ?: 'সাধারণ'; ?></small>
                                                    </td>
                                                    <td>
                                                        <span class="badge bg-success"><?php echo $dist['session']; ?></span><br>
                                                        <small class="text-muted">
                                                            <?php 
                                                            $exam_types = [
                                                                'midterm' => 'অর্ধবার্ষিক',
                                                                'final' => 'বার্ষিক',
                                                                'test' => 'টেস্ট',
                                                                'assignment' => 'অ্যাসাইনমেন্ট',
                                                                'practical' => 'ব্যবহারিক'
                                                            ];
                                                            echo $exam_types[$dist['exam_type']] ?? $dist['exam_type'];
                                                            ?>
                                                        </small>
                                                    </td>
                                                    <td>
                                                        <div class="small">
                                                            <strong class="text-primary">মোট: <?php echo $dist['total_marks']; ?></strong><br>
                                                            <div class="row g-1">
                                                                <div class="col-6">CQ: <?php echo $dist['cq_marks']; ?></div>
                                                                <div class="col-6">MCQ: <?php echo $dist['mcq_marks']; ?></div>
                                                                <?php if ($dist['practical_marks'] > 0): ?>
                                                                    <div class="col-6">Practical: <?php echo $dist['practical_marks']; ?></div>
                                                                <?php endif; ?>
                                                                <?php if ($dist['assignment_marks'] > 0): ?>
                                                                    <div class="col-6">Assignment: <?php echo $dist['assignment_marks']; ?></div>
                                                                <?php endif; ?>
                                                            </div>
                                                            <hr class="my-1">
                                                            <strong class="text-success">পাস: <?php echo $dist['overall_pass_marks']; ?></strong>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div class="btn-group-vertical" role="group">
                                                            <button class="btn btn-sm btn-outline-primary edit-btn mb-1" title="এডিট"
                                                                    data-id="<?php echo $dist['id']; ?>"
                                                                    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']; ?>"
                                                                    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="" onsubmit="return confirm('এই রেকর্ডটি ডিলিট করতে চান?');" style="display:inline;">
                                                                <input type="hidden" name="delete_id" value="<?php echo $dist['id']; ?>">
                                                                <button type="submit" class="btn btn-sm btn-outline-danger" title="ডিলিট">
                                                                    <i class="fas fa-trash-alt"></i>
                                                                </button>
                                                            </form>
                                                        </div>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            
                            <!-- Pagination -->
                            <?php if ($total_pages > 1): ?>
                                <nav class="mt-4">
                                    <ul class="pagination pagination-modern justify-content-center">
                                        <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                            <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                                <a class="page-link" href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                                            </li>
                                        <?php endfor; ?>
                                    </ul>
                                </nav>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Floating Action Button -->
    <button class="floating-action-btn" onclick="scrollToTop()" title="উপরে যান">
        <i class="fas fa-arrow-up"></i>
    </button>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Enhanced marks calculation with visual feedback
        function updateMarksTotal() {
            const markInputs = document.querySelectorAll('.mark-input');
            let total = 0;
            
            markInputs.forEach(input => {
                total += parseInt(input.value) || 0;
            });
            
            document.getElementById('total-distributed').textContent = total;
            
            const totalMarks = parseInt(document.getElementById('total_marks').value) || 0;
            const summaryDiv = document.getElementById('marks-summary');
            const statusDiv = document.getElementById('distribution-status');
            const progressCircle = document.getElementById('progress-circle');
            
            // Calculate progress percentage
            const percentage = totalMarks > 0 ? (total / totalMarks) * 100 : 0;
            const circumference = 2 * Math.PI * 50; // radius = 50
            const strokeDasharray = (percentage / 100) * circumference;
            
            progressCircle.style.strokeDasharray = `${strokeDasharray} ${circumference}`;
            
            if (total === totalMarks && totalMarks > 0) {
                summaryDiv.className = 'marks-summary success animate__animated animate__pulse';
                statusDiv.innerHTML = '<i class="fas fa-check-circle"></i> সঠিক বিভাজন';
                progressCircle.style.stroke = '#56ab2f';
            } else if (total > totalMarks) {
                summaryDiv.className = 'marks-summary danger animate__animated animate__shakeX';
                statusDiv.innerHTML = '<i class="fas fa-exclamation-triangle"></i> অতিরিক্ত নম্বর';
                progressCircle.style.stroke = '#e74c3c';
            } else if (total > 0) {
                summaryDiv.className = 'marks-summary warning animate__animated animate__bounce';
                statusDiv.innerHTML = '<i class="fas fa-clock"></i> আরো নম্বর প্রয়োজন';
                progressCircle.style.stroke = '#f39c12';
            } else {
                summaryDiv.className = 'marks-summary';
                statusDiv.innerHTML = 'নম্বর বিভাজন করুন';
                progressCircle.style.stroke = '#667eea';
            }
        }
        
        // Add event listeners with animation
        document.querySelectorAll('.mark-input').forEach(input => {
            input.addEventListener('input', function() {
                this.classList.add('animate__animated', 'animate__pulse');
                setTimeout(() => {
                    this.classList.remove('animate__animated', 'animate__pulse');
                }, 600);
                updateMarksTotal();
            });
        });
        
        document.getElementById('total_marks').addEventListener('input', function() {
            const total = parseInt(this.value) || 0;
            const passMarks = Math.ceil(total * 0.4);
            document.getElementById('overall_pass_marks').value = passMarks;
            updateMarksTotal();
        });
        
        // Enhanced edit functionality
        document.querySelectorAll('.edit-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                // Add loading animation
                this.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
                
                setTimeout(() => {
                    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;
                    document.getElementById('exam_type').value = this.dataset.exam;
                    document.getElementById('total_marks').value = this.dataset.total;
                    document.getElementById('cq_marks').value = this.dataset.cq;
                    document.getElementById('mcq_marks').value = this.dataset.mcq;
                    document.getElementById('practical_marks').value = this.dataset.practical;
                    document.getElementById('assignment_marks').value = this.dataset.assignment;
                    document.getElementById('attendance_marks').value = this.dataset.attendance;
                    document.getElementById('overall_pass_marks').value = this.dataset.overallPass;
                    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;
                    
                    updateMarksTotal();
                    
                    // Scroll to form with smooth animation
                    document.querySelector('.form-section').scrollIntoView({ 
                        behavior: 'smooth',
                        block: 'start'
                    });
                    
                    // Restore button
                    this.innerHTML = '<i class="fas fa-edit"></i>';
                    
                    // Add highlight animation to form
                    const formSection = document.querySelector('.form-section');
                    formSection.classList.add('animate__animated', 'animate__pulse');
                    setTimeout(() => {
                        formSection.classList.remove('animate__animated', 'animate__pulse');
                    }, 1000);
                }, 500);
            });
        });
        
        // Scroll to top function
        function scrollToTop() {
            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
        }
        
        // Form validation with enhanced feedback
        (function() {
            'use strict';
            window.addEventListener('load', function() {
                var forms = document.getElementsByClassName('needs-validation');
                var validation = Array.prototype.filter.call(forms, function(form) {
                    form.addEventListener('submit', function(event) {
                        if (form.checkValidity() === false) {
                            event.preventDefault();
                            event.stopPropagation();
                            
                            // Add shake animation to invalid fields
                            const invalidFields = form.querySelectorAll(':invalid');
                            invalidFields.forEach(field => {
                                field.classList.add('animate__animated', 'animate__shakeX');
                                setTimeout(() => {
                                    field.classList.remove('animate__animated', 'animate__shakeX');
                                }, 600);
                            });
                        }
                        form.classList.add('was-validated');
                    }, false);
                });
            }, false);
        })();
        
        // Initialize animations and calculations
        document.addEventListener('DOMContentLoaded', function() {
            updateMarksTotal();
            
            // Add stagger animation to table rows
            const tableRows = document.querySelectorAll('tbody tr');
            tableRows.forEach((row, index) => {
                row.style.animationDelay = `${index * 0.1}s`;
            });
            
            // Add hover effects to cards
            const cards = document.querySelectorAll('.stats-card');
            cards.forEach(card => {
                card.addEventListener('mouseenter', function() {
                    this.classList.add('animate__animated', 'animate__pulse');
                });
                
                card.addEventListener('mouseleave', function() {
                    this.classList.remove('animate__animated', 'animate__pulse');
                });
            });
        });
        
        // Auto-save functionality (optional)
        let autoSaveTimeout;
        document.querySelectorAll('input, select').forEach(input => {
            input.addEventListener('change', function() {
                clearTimeout(autoSaveTimeout);
                autoSaveTimeout = setTimeout(() => {
                    // Show auto-save indicator
                    const indicator = document.createElement('div');
                    indicator.className = 'alert alert-info alert-modern animate__animated animate__fadeInDown';
                    indicator.innerHTML = '<i class="fas fa-save"></i> অটো-সেভ সক্রিয়...';
                    indicator.style.position = 'fixed';
                    indicator.style.top = '20px';
                    indicator.style.right = '20px';
                    indicator.style.zIndex = '9999';
                    document.body.appendChild(indicator);
                    
                    setTimeout(() => {
                        indicator.remove();
                    }, 2000);
                }, 3000);
            });
        });
    </script>
</body>
</html>