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

// Auth: admin/teacher only
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['user_role'], ['admin', 'teacher'])) {
    header('Location: ../login.php');
    exit();
}

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

// Ensure class_mark_distribution table exists
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS class_mark_distribution (
        id INT AUTO_INCREMENT PRIMARY KEY,
        class_id INT NOT NULL,
        group_name VARCHAR(50) NULL,
        subject_id INT NOT NULL,
        exam_type ENUM('midterm','final','test','assignment','practical','all') NOT NULL,
        total_marks DECIMAL(6,2) NOT NULL,
        cq_marks DECIMAL(6,2) DEFAULT 0,
        mcq_marks DECIMAL(6,2) DEFAULT 0,
        practical_marks DECIMAL(6,2) DEFAULT 0,
        assignment_marks DECIMAL(6,2) DEFAULT 0,
        attendance_marks DECIMAL(6,2) DEFAULT 0,
        overall_pass_marks DECIMAL(6,2) NOT NULL,
        cq_pass_marks DECIMAL(6,2) NULL,
        mcq_pass_marks DECIMAL(6,2) NULL,
        practical_pass_marks DECIMAL(6,2) NULL,
        grade_system VARCHAR(20) DEFAULT 'gpa',
        active TINYINT(1) DEFAULT 1,
        created_by INT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_class_subject_exam_group (class_id, subject_id, exam_type, group_name),
        INDEX idx_class (class_id),
        INDEX idx_subject (subject_id),
        INDEX idx_exam (exam_type),
        INDEX idx_active (active),
        CONSTRAINT fk_cmd_class FOREIGN KEY (class_id) REFERENCES classes(id) ON DELETE CASCADE,
        CONSTRAINT fk_cmd_subject FOREIGN KEY (subject_id) REFERENCES subjects(id) ON DELETE CASCADE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;");
} catch (Exception $e) {
    $error_message = 'টেবিল তৈরিতে ত্রুটি: ' . $e->getMessage();
}

// Fetch dropdown data
$classes = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' ORDER BY name, section")->fetchAll();
$subjects = $pdo->query("SELECT id, name, code FROM subjects WHERE status = 'active' ORDER BY name")->fetchAll();
$groups = $pdo->query("SELECT group_name, group_code FROM student_groups WHERE status = 'active' ORDER BY group_name")->fetchAll();

// Handle actions: activate/deactivate/delete
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['toggle_active'])) {
        $id = (int)($_POST['id'] ?? 0);
        $new_status = (int)($_POST['new_status'] ?? 1);
        try {
            $stmt = $pdo->prepare("UPDATE class_mark_distribution SET active = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
            $stmt->execute([$new_status, $id]);
            $success_message = $new_status ? 'সেটিং সক্রিয় করা হয়েছে' : 'সেটিং নিষ্ক্রিয় করা হয়েছে';
        } catch (Exception $e) {
            $error_message = 'ত্রুটি: ' . $e->getMessage();
        }
    }
    if (isset($_POST['delete_id'])) {
        $id = (int)$_POST['delete_id'];
        try {
            $stmt = $pdo->prepare('DELETE FROM class_mark_distribution WHERE id = ?');
            $stmt->execute([$id]);
            $success_message = 'রেকর্ড মুছে ফেলা হয়েছে।';
        } catch (Exception $e) {
            $error_message = 'ত্রুটি: ' . $e->getMessage();
        }
    }
}

// Save handler
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_cmd'])) {
    $class_id = (int)($_POST['class_id'] ?? 0);
    $group_name = trim($_POST['group_name'] ?? '');
    $subject_id = (int)($_POST['subject_id'] ?? 0);
    $exam_type = trim($_POST['exam_type'] ?? '');
    $total_marks = (float)($_POST['total_marks'] ?? 0);
    $cq_marks = (float)($_POST['cq_marks'] ?? 0);
    $mcq_marks = (float)($_POST['mcq_marks'] ?? 0);
    $practical_marks = (float)($_POST['practical_marks'] ?? 0);
    $assignment_marks = (float)($_POST['assignment_marks'] ?? 0);
    $attendance_marks = (float)($_POST['attendance_marks'] ?? 0);
    $overall_pass_marks = (float)($_POST['overall_pass_marks'] ?? 0);
    $cq_pass_marks = strlen($_POST['cq_pass_marks'] ?? '') ? (float)$_POST['cq_pass_marks'] : null;
    $mcq_pass_marks = strlen($_POST['mcq_pass_marks'] ?? '') ? (float)$_POST['mcq_pass_marks'] : null;
    $practical_pass_marks = strlen($_POST['practical_pass_marks'] ?? '') ? (float)$_POST['practical_pass_marks'] : null;
    $grade_system = trim($_POST['grade_system'] ?? 'gpa');
    $active = isset($_POST['active']) ? 1 : 0;

    if (!$class_id || !$subject_id || !$exam_type || !$total_marks || !$overall_pass_marks) {
        $error_message = 'আবশ্যক সব ফিল্ড প্রদান করুন।';
    } else {
        $sum = $cq_marks + $mcq_marks + $practical_marks + $assignment_marks + $attendance_marks;
        if (abs($sum - $total_marks) > 0.0001) {
            $error_message = 'মোট নম্বর এবং বিভাজিত নম্বরের যোগফল সমান নয়।';
        } else {
            try {
                $exam_types = $exam_type === 'all' ? ['all','midterm','final','test','assignment','practical'] : [$exam_type];
                $count = 0;
                foreach ($exam_types as $et) {
                    $stmt = $pdo->prepare("INSERT INTO class_mark_distribution
                        (class_id, group_name, subject_id, 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, active, created_by)
                        VALUES (?, NULLIF(?, ''), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                        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),
                            active=VALUES(active),
                            updated_at=CURRENT_TIMESTAMP");
                    $stmt->execute([
                        $class_id, $group_name, $subject_id, $et,
                        $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, $active, $_SESSION['user_id'] ?? null
                    ]);
                    $count++;
                }
                $success_message = ($exam_type === 'all') ? "সব পরীক্ষার জন্য {$count} টি রেকর্ড সেভ হয়েছে (সহ সাধারণ 'all' রেকর্ড)" : 'সেটিং সেভ হয়েছে';
            } catch (Exception $e) {
                $error_message = 'ত্রুটি: ' . $e->getMessage();
            }
        }
    }
}

// Filters
$filter_class = isset($_GET['filter_class']) ? (int)$_GET['filter_class'] : 0;
$filter_group = isset($_GET['filter_group']) ? trim($_GET['filter_group']) : '';
$filter_subject = isset($_GET['filter_subject']) ? (int)$_GET['filter_subject'] : 0;
$filter_exam = isset($_GET['filter_exam']) ? trim($_GET['filter_exam']) : '';

// Edit mode
$edit_id = isset($_GET['edit_id']) ? (int)$_GET['edit_id'] : 0;
$edit_row = null;
if ($edit_id) {
    try {
        $stmt = $pdo->prepare("SELECT cmd.*, c.name as class_name, c.section, s.name as subject_name FROM class_mark_distribution cmd JOIN classes c ON cmd.class_id=c.id JOIN subjects s ON cmd.subject_id=s.id WHERE cmd.id=?");
        $stmt->execute([$edit_id]);
        $edit_row = $stmt->fetch();
    } catch (Exception $e) {}
}

// Handle edit update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_cmd'])) {
    $eid = (int)($_POST['edit_id'] ?? 0);
    $class_id = (int)($_POST['class_id'] ?? 0);
    $group_name = trim($_POST['group_name'] ?? '');
    $subject_id = (int)($_POST['subject_id'] ?? 0);
    $exam_type = trim($_POST['exam_type'] ?? '');
    $total_marks = (float)($_POST['total_marks'] ?? 0);
    $cq_marks = (float)($_POST['cq_marks'] ?? 0);
    $mcq_marks = (float)($_POST['mcq_marks'] ?? 0);
    $practical_marks = (float)($_POST['practical_marks'] ?? 0);
    $assignment_marks = (float)($_POST['assignment_marks'] ?? 0);
    $attendance_marks = (float)($_POST['attendance_marks'] ?? 0);
    $overall_pass_marks = (float)($_POST['overall_pass_marks'] ?? 0);
    $cq_pass_marks = strlen($_POST['cq_pass_marks'] ?? '') ? (float)$_POST['cq_pass_marks'] : null;
    $mcq_pass_marks = strlen($_POST['mcq_pass_marks'] ?? '') ? (float)$_POST['mcq_pass_marks'] : null;
    $practical_pass_marks = strlen($_POST['practical_pass_marks'] ?? '') ? (float)$_POST['practical_pass_marks'] : null;
    $grade_system = trim($_POST['grade_system'] ?? 'gpa');
    $active = isset($_POST['active']) ? 1 : 0;

    if (!$class_id || !$subject_id || !$exam_type || !$total_marks || !$overall_pass_marks) {
        $error_message = 'আবশ্যক সব ফিল্ড প্রদান করুন।';
    } else {
        $sum = $cq_marks + $mcq_marks + $practical_marks + $assignment_marks + $attendance_marks;
        if (abs($sum - $total_marks) > 0.0001) {
            $error_message = 'মোট নম্বর এবং বিভাজিত নম্বরের যোগফল সমান নয়।';
        } else {
            try {
                $exam_types_update = $exam_type === 'all' ? ['all','midterm','final','test','assignment','practical'] : [$exam_type];
                $count = 0;
                foreach ($exam_types_update as $et) {
                    $stmt = $pdo->prepare("INSERT INTO class_mark_distribution
                        (class_id, group_name, subject_id, 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, active, created_by)
                        VALUES (?, NULLIF(?, ''), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                        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),
                            active=VALUES(active),
                            updated_at=CURRENT_TIMESTAMP");
                    $stmt->execute([
                        $class_id, $group_name, $subject_id, $et,
                        $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, $active, $_SESSION['user_id'] ?? null
                    ]);
                    $count++;
                }
                $success_message = ($exam_type === 'all') ? "সেটিং আপডেট হয়েছে ({$count} টি রেকর্ড)" : 'সেটিং আপডেট হয়েছে';
                header('Location: class_based_setup.php');
                exit();
            } catch (Exception $e) {
                $error_message = 'ত্রুটি: ' . $e->getMessage();
            }
        }
    }
}

// Fetch existing CMDs
$sql = "SELECT cmd.*, c.name as class_name, c.section, s.name as subject_name
        FROM class_mark_distribution cmd
        JOIN classes c ON cmd.class_id = c.id
        JOIN subjects s ON cmd.subject_id = s.id
        WHERE 1=1";
$params = [];
if ($filter_class) { $sql .= " AND cmd.class_id = ?"; $params[] = $filter_class; }
if ($filter_group !== '') { $sql .= " AND IFNULL(cmd.group_name,'') = ?"; $params[] = $filter_group; }
if ($filter_subject) { $sql .= " AND cmd.subject_id = ?"; $params[] = $filter_subject; }
if ($filter_exam !== '') { $sql .= " AND cmd.exam_type = ?"; $params[] = $filter_exam; }
$sql .= " ORDER BY c.name, c.section, s.name, cmd.exam_type";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$items = $stmt->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.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary: #006747;
            --accent: #F42A41;
            --blue: #1976d2;
            --purple: #7b1fa2;
            --orange: #ff9800;
            --pink: #e91e63;
            --teal: #009688;
            --bg-grad: radial-gradient( ellipse at 10% 10%, rgba(0,103,71,.10) 0%, rgba(25,118,210,.10) 35%, rgba(244,42,65,.08) 65%, rgba(0,0,0,0) 100% );
        }
        body {
            font-family: 'Hind Siliguri', -apple-system, Segoe UI, Roboto, 'Helvetica Neue', Arial, 'Noto Sans', 'Liberation Sans', 'Apple Color Emoji', 'Segoe UI Emoji';
            background: #f6fbf9;
            background-image: var(--bg-grad);
            min-height: 100vh;
        }
        .navbar {
            background: linear-gradient(135deg, var(--primary) 0%, #20c997 50%, var(--blue) 100%) !important;
            border-bottom: 3px solid var(--accent);
        }
        .card {
            border: none;
            border-radius: 14px;
            box-shadow: 0 10px 24px rgba(0,0,0,0.08);
            overflow: hidden;
        }
        .card-header {
            border: none;
            color: #fff;
            background: linear-gradient(135deg, var(--blue) 0%, var(--purple) 100%);
        }
        .card.bg-light .card-header {
            background: linear-gradient(135deg, var(--orange) 0%, #ff5722 100%);
            color: #fff;
        }
        .badge { font-size: 10px; padding: 4px 6px; border-radius: 8px; }
        .badge.bg-primary { background: linear-gradient(135deg, #2196f3 0%, #00bcd4 100%) !important; }
        .badge.bg-success { background: linear-gradient(135deg, #43a047 0%, #66bb6a 100%) !important; }
        .badge.bg-info { background: linear-gradient(135deg, #26c6da 0%, #00acc1 100%) !important; }
        .badge.bg-danger { background: linear-gradient(135deg, #e53935 0%, #ff5252 100%) !important; }
        .badge.bg-secondary { background: linear-gradient(135deg, #607d8b 0%, #90a4ae 100%) !important; }
        .badge.bg-dark { background: linear-gradient(135deg, #37474f 0%, #263238 100%) !important; }
        .table thead.table-dark {
            background: linear-gradient(135deg, var(--blue) 0%, var(--purple) 100%);
        }
        .form-control, .form-select {
            border-radius: 10px;
            border: 1px solid rgba(0,0,0,0.08);
        }
        .form-control:focus, .form-select:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 .2rem rgba(0,103,71,.15);
        }
        .btn-success {
            background: linear-gradient(135deg, var(--primary) 0%, #00a86b 100%);
            border: none;
        }
        .btn-success:hover { filter: brightness(1.05); }
        .btn-secondary { background: linear-gradient(135deg, #607d8b 0%, #90a4ae 100%); border: none; }
        .btn-primary { background: linear-gradient(135deg, var(--blue) 0%, var(--purple) 100%); border: none; }
        .btn-outline-danger { border-color: #ff5252; color: #ff5252; }
        .btn-outline-danger:hover { background:#ff5252; color:#fff; }
        .btn-outline-warning { border-color: #ff9800; color:#ff9800; }
        .btn-outline-warning:hover { background:#ff9800; color:#222; }
        .alert-info { background: linear-gradient(135deg, #e3f2fd, #e0f7fa); border: none; color: #0d47a1; }
        .alert-success { background: linear-gradient(135deg, #e8f5e9, #e0f2f1); border: none; color: #1b5e20; }
        .alert-danger { background: linear-gradient(135deg, #ffebee, #fbe9e7); border: none; color: #b71c1c; }
        .table-hover tbody tr:hover { background: rgba(0, 103, 71, 0.05); }
        /* One-line filters bar on top */
        .filters-bar {
            display: flex;
            align-items: center;
            gap: .4rem;
            flex-wrap: nowrap;
            overflow-x: auto;
            padding: .25rem;
            scrollbar-width: thin;
            scrollbar-color: var(--primary) transparent;
            white-space: nowrap;
        }
        .filters-bar .form-select,
        .filters-bar .btn { flex: 0 0 auto; }
        .filters-bar .form-select { width: auto; min-width: 130px; }
        .filters-bar .form-select.form-select-sm { min-width: 120px; }
        .filters-bar::-webkit-scrollbar { height: 6px; }
        .filters-bar::-webkit-scrollbar-thumb { background: rgba(0,103,71,.4); border-radius: 4px; }
    </style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-success">
  <div class="container-fluid">
    <a class="navbar-brand" href="../index.php"><i class="fas fa-cogs"></i> ক্লাস ভিত্তিক মার্কস বিভাজন</a>
    <div class="navbar-nav ms-auto">
        <a class="nav-link" href="setup.php"><i class="fas fa-wrench"></i> পুরনো মডেল</a>
        <a class="nav-link" href="entry.php"><i class="fas fa-edit"></i> মার্কস এন্ট্রি</a>
        <a class="nav-link" href="../index.php"><i class="fas fa-home"></i> হোম</a>
    </div>
  </div>
</nav>
<div class="container my-4">
  <?php if ($success_message): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="fas fa-check-circle"></i> <?= htmlspecialchars($success_message) ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
  <?php endif; ?>
  <?php if ($error_message): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fas fa-exclamation-triangle"></i> <?= htmlspecialchars($error_message) ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
  <?php endif; ?>
  <div class="row">
    <!-- নতুন/আপডেট স্থায়ী সেটিং - বামে -->
    <div class="col-md-4 mb-4">
      <div class="card">
        <div class="card-header"><strong><i class="fas fa-cog"></i> <?= $edit_row ? 'সেটিং এডিট করুন' : 'নতুন/আপডেট স্থায়ী সেটিং' ?></strong></div>
        <div class="card-body">
          <form method="POST">
            <?php if ($edit_row): ?><input type="hidden" name="edit_id" value="<?= $edit_row['id'] ?>"><?php endif; ?>
            <!-- Basic Info -->
            <div class="mb-3">
              <label class="form-label">ক্লাস <span class="text-danger">*</span></label>
              <select name="class_id" id="class_id" class="form-select" required>
                <option value="">নির্বাচন করুন</option>
                <?php foreach ($classes as $c): ?>
                  <option value="<?= $c['id'] ?>" <?= ($edit_row && $edit_row['class_id']==$c['id']) ? 'selected' : '' ?>><?= htmlspecialchars($c['name'] . ' - ' . $c['section']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="mb-3">
              <label class="form-label">গ্রুপ</label>
              <select name="group_name" id="group_name" class="form-select">
                <option value="">সাধারণ</option>
                <?php foreach ($groups as $g): ?>
                  <option value="<?= htmlspecialchars($g['group_name']) ?>" <?= ($edit_row && ($edit_row['group_name']??'') === $g['group_name']) ? 'selected' : '' ?>><?= htmlspecialchars($g['group_name'] . ' (' . $g['group_code'] . ')') ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="mb-3">
              <label class="form-label">বিষয় <span class="text-danger">*</span></label>
              <select name="subject_id" id="subject_id" class="form-select" required>
                <option value="">নির্বাচন করুন</option>
                <?php foreach ($subjects as $s): ?>
                  <option value="<?= $s['id'] ?>" <?= ($edit_row && $edit_row['subject_id']==$s['id']) ? 'selected' : '' ?>><?= htmlspecialchars($s['name'] . ' (' . $s['code'] . ')') ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="mb-3">
              <label class="form-label">পরীক্ষার ধরন <span class="text-danger">*</span></label>
              <select name="exam_type" id="exam_type" class="form-select" required>
                <option value="">নির্বাচন করুন</option>
                <option value="all" <?= ($edit_row && $edit_row['exam_type']==='all') ? 'selected' : '' ?>>সব ধরনের পরীক্ষার জন্য</option>
                <option value="midterm" <?= ($edit_row && $edit_row['exam_type']==='midterm') ? 'selected' : '' ?>>অর্ধবার্ষিক</option>
                <option value="final" <?= ($edit_row && $edit_row['exam_type']==='final') ? 'selected' : '' ?>>বার্ষিক</option>
                <option value="test" <?= ($edit_row && $edit_row['exam_type']==='test') ? 'selected' : '' ?>>টেস্ট</option>
                <option value="assignment" <?= ($edit_row && $edit_row['exam_type']==='assignment') ? 'selected' : '' ?>>অ্যাসাইনমেন্ট</option>
                <option value="practical" <?= ($edit_row && $edit_row['exam_type']==='practical') ? 'selected' : '' ?>>ব্যবহারিক</option>
              </select>
            </div>

            <!-- Total and Pass Marks -->
            <div class="row">
              <div class="col-6 mb-3">
                <label class="form-label">মোট নম্বর <span class="text-danger">*</span></label>
                <input type="number" step="1" min="1" class="form-control" name="total_marks" id="total_marks" value="<?= $edit_row ? $edit_row['total_marks']*1 : '' ?>" required>
              </div>
              <div class="col-6 mb-3">
                <label class="form-label">সামগ্রিক পাস <span class="text-danger">*</span></label>
                <input type="number" step="1" min="0" class="form-control" name="overall_pass_marks" id="overall_pass_marks" value="<?= $edit_row ? $edit_row['overall_pass_marks']*1 : '' ?>" required>
              </div>
            </div>

            <!-- Distribution Card -->
            <div class="card bg-light mb-3">
              <div class="card-header py-2"><strong><i class="fas fa-chart-pie"></i> নম্বর বিভাজন</strong></div>
              <div class="card-body">
                <div class="row">
                  <div class="col-6 mb-2">
                    <label class="form-label small">CQ</label>
                    <input type="number" step="1" min="0" class="form-control mark-input" name="cq_marks" id="cq_marks" value="<?= $edit_row ? $edit_row['cq_marks']*1 : '0' ?>">
                  </div>
                  <div class="col-6 mb-2">
                    <label class="form-label small">MCQ</label>
                    <input type="number" step="1" min="0" class="form-control mark-input" name="mcq_marks" id="mcq_marks" value="<?= $edit_row ? $edit_row['mcq_marks']*1 : '0' ?>">
                  </div>
                  <div class="col-6 mb-2">
                    <label class="form-label small">ব্যবহারিক</label>
                    <input type="number" step="1" min="0" class="form-control mark-input" name="practical_marks" id="practical_marks" value="<?= $edit_row ? $edit_row['practical_marks']*1 : '0' ?>">
                  </div>
                  <div class="col-6 mb-2">
                    <label class="form-label small">অ্যাসাইনমেন্ট</label>
                    <input type="number" step="1" min="0" class="form-control mark-input" name="assignment_marks" id="assignment_marks" value="<?= $edit_row ? $edit_row['assignment_marks']*1 : '0' ?>">
                  </div>
                  <div class="col-6 mb-2">
                    <label class="form-label small">উপস্থিতি</label>
                    <input type="number" step="1" min="0" class="form-control mark-input" name="attendance_marks" id="attendance_marks" value="<?= $edit_row ? $edit_row['attendance_marks']*1 : '0' ?>">
                  </div>
                  <div class="col-6 mb-2">
                    <label class="form-label small">মোট বিভাজিত</label>
                    <div class="alert py-2 mb-0" id="marks-summary">
                      <strong><span id="sum_marks">0</span></strong>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- Passing Marks Card -->
            <div class="card bg-light mb-3">
              <div class="card-header py-2"><strong><i class="fas fa-check-circle"></i> পাসিং মার্কস (ঐচ্ছিক)</strong></div>
              <div class="card-body">
                <div class="row">
                  <div class="col-4 mb-2">
                    <label class="form-label small">CQ</label>
                    <input type="number" step="1" min="0" class="form-control" name="cq_pass_marks" id="cq_pass_marks" placeholder="0" value="<?= ($edit_row && $edit_row['cq_pass_marks']!==null) ? $edit_row['cq_pass_marks']*1 : '' ?>">
                  </div>
                  <div class="col-4 mb-2">
                    <label class="form-label small">MCQ</label>
                    <input type="number" step="1" min="0" class="form-control" name="mcq_pass_marks" id="mcq_pass_marks" placeholder="0" value="<?= ($edit_row && $edit_row['mcq_pass_marks']!==null) ? $edit_row['mcq_pass_marks']*1 : '' ?>">
                  </div>
                  <div class="col-4 mb-2">
                    <label class="form-label small">ব্যবহারিক</label>
                    <input type="number" step="1" min="0" class="form-control" name="practical_pass_marks" id="practical_pass_marks" placeholder="0" value="<?= ($edit_row && $edit_row['practical_pass_marks']!==null) ? $edit_row['practical_pass_marks']*1 : '' ?>">
                  </div>
                </div>
              </div>
            </div>

            <!-- Grade System and Active -->
            <div class="row mb-3">
              <div class="col-6">
                <label class="form-label">গ্রেড সিস্টেম</label>
                <select class="form-select" name="grade_system" id="grade_system">
                  <option value="gpa" <?= ($edit_row && $edit_row['grade_system']==='gpa') ? 'selected' : '' ?>>GPA</option>
                  <option value="letter" <?= ($edit_row && $edit_row['grade_system']==='letter') ? 'selected' : '' ?>>Letter</option>
                  <option value="percentage" <?= ($edit_row && $edit_row['grade_system']==='percentage') ? 'selected' : '' ?>>Percentage</option>
                </select>
              </div>
              <div class="col-6 d-flex align-items-center">
                <div class="form-check form-switch mt-4">
                  <input class="form-check-input" type="checkbox" id="active" name="active" <?= (!$edit_row || $edit_row['active']) ? 'checked' : '' ?>>
                  <label class="form-check-label" for="active">সক্রিয়</label>
                </div>
              </div>
            </div>

            <!-- Buttons -->
            <div class="d-grid gap-2">
              <?php if ($edit_row): ?>
                <button type="submit" class="btn btn-primary" name="update_cmd" value="1"><i class="fas fa-save"></i> আপডেট</button>
                <a href="class_based_setup.php" class="btn btn-secondary"><i class="fas fa-times"></i> বাতিল</a>
              <?php else: ?>
                <button type="submit" class="btn btn-success" name="save_cmd" value="1"><i class="fas fa-save"></i> সেভ</button>
                <button type="reset" class="btn btn-secondary"><i class="fas fa-undo"></i> ক্লিয়ার</button>
              <?php endif; ?>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- বিদ্যমান স্থায়ী সেটিং - ডানে -->
    <div class="col-md-8">
      <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
          <strong><i class="fas fa-list"></i> বিদ্যমান স্থায়ী সেটিং</strong>
          <form class="d-flex filters-bar" method="GET">
            <select name="filter_class" class="form-select form-select-sm me-1 w-auto">
              <option value="">সব ক্লাস</option>
              <?php foreach ($classes as $c): ?>
                <option value="<?= $c['id'] ?>" <?= $filter_class==$c['id']?'selected':'' ?>><?= htmlspecialchars($c['name'] . ' - ' . $c['section']) ?></option>
              <?php endforeach; ?>
            </select>
            <select name="filter_group" class="form-select form-select-sm me-1 w-auto">
              <option value="">সব গ্রুপ</option>
              <?php foreach ($groups as $g): ?>
                <option value="<?= htmlspecialchars($g['group_name']) ?>" <?= $filter_group===$g['group_name']?'selected':'' ?>><?= htmlspecialchars($g['group_name']) ?></option>
              <?php endforeach; ?>
            </select>
            <select name="filter_subject" class="form-select form-select-sm me-1 w-auto">
              <option value="">সব বিষয়</option>
              <?php foreach ($subjects as $s): ?>
                <option value="<?= $s['id'] ?>" <?= $filter_subject==$s['id']?'selected':'' ?>><?= htmlspecialchars($s['name']) ?></option>
              <?php endforeach; ?>
            </select>
            <select name="filter_exam" class="form-select form-select-sm me-1 w-auto">
              <option value="">সব পরীক্ষা</option>
              <option value="midterm" <?= $filter_exam==='midterm'?'selected':'' ?>>অর্ধবার্ষিক</option>
              <option value="final" <?= $filter_exam==='final'?'selected':'' ?>>বার্ষিক</option>
              <option value="test" <?= $filter_exam==='test'?'selected':'' ?>>টেস্ট</option>
              <option value="assignment" <?= $filter_exam==='assignment'?'selected':'' ?>>অ্যাসাইনমেন্ট</option>
              <option value="practical" <?= $filter_exam==='practical'?'selected':'' ?>>ব্যবহারিক</option>
            </select>
            <button class="btn btn-sm btn-primary"><i class="fas fa-search"></i></button>
            <a class="btn btn-sm btn-secondary ms-1" href="class_based_setup.php"><i class="fas fa-times"></i></a>
          </form>
        </div>
        <div class="card-body">
          <?php if (empty($items)): ?>
            <div class="alert alert-info"><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">
              <thead class="table-dark">
                <tr>
                  <th>ক্লাস/গ্রুপ</th>
                  <th>বিষয়</th>
                  <th>পরীক্ষা</th>
                  <th>বিভাজন</th>
                  <th>পাস</th>
                  <th>স্ট্যাটাস</th>
                  <th>অ্যাকশন</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($items as $it): ?>
                <tr>
                  <td>
                    <div><strong><?= htmlspecialchars($it['class_name'] . '-' . $it['section']) ?></strong></div>
                    <div class="small text-muted"><?= htmlspecialchars($it['group_name'] ?: 'সাধারণ') ?></div>
                  </td>
                  <td><?= htmlspecialchars($it['subject_name']) ?></td>
                  <td>
                    <?php 
                    $labels = ['midterm'=>'অর্ধবার্ষিক','final'=>'বার্ষিক','test'=>'টেস্ট','assignment'=>'অ্যাসাইনমেন্ট','practical'=>'ব্যবহারিক','all'=>'সব'];
                    echo $labels[$it['exam_type']] ?? $it['exam_type'];
                    ?>
                  </td>
                  <td>
                    <div class="d-flex flex-wrap gap-1 small">
                      <span class="badge bg-primary">মোট: <?= $it['total_marks']*1 ?></span>
                      <span class="badge bg-success">CQ: <?= $it['cq_marks']*1 ?></span>
                      <span class="badge bg-info">MCQ: <?= $it['mcq_marks']*1 ?></span>
                      <?php if (($it['practical_marks']*1)>0): ?><span class="badge bg-secondary">Prac: <?= $it['practical_marks']*1 ?></span><?php endif; ?>
                      <?php if (($it['assignment_marks']*1)>0): ?><span class="badge bg-secondary">Assign: <?= $it['assignment_marks']*1 ?></span><?php endif; ?>
                      <?php if (($it['attendance_marks']*1)>0): ?><span class="badge bg-secondary">Att: <?= $it['attendance_marks']*1 ?></span><?php endif; ?>
                    </div>
                  </td>
                  <td>
                    <div class="d-flex flex-column small">
                      <span class="badge bg-danger">Overall: <?= $it['overall_pass_marks']*1 ?></span>
                      <?php if ($it['cq_pass_marks'] !== null): ?><span class="badge bg-dark">CQ: <?= $it['cq_pass_marks']*1 ?></span><?php endif; ?>
                      <?php if ($it['mcq_pass_marks'] !== null): ?><span class="badge bg-dark">MCQ: <?= $it['mcq_pass_marks']*1 ?></span><?php endif; ?>
                      <?php if ($it['practical_pass_marks'] !== null): ?><span class="badge bg-dark">Prac: <?= $it['practical_pass_marks']*1 ?></span><?php endif; ?>
                    </div>
                  </td>
                  <td>
                    <?php if ($it['active']): ?><span class="badge bg-success">Active</span><?php else: ?><span class="badge bg-secondary">Inactive</span><?php endif; ?>
                  </td>
                  <td>
                    <div class="btn-group btn-group-sm" role="group">
                      <a href="?edit_id=<?= $it['id'] ?>" class="btn btn-outline-primary" title="এডিট"><i class="fas fa-edit"></i></a>
                      <form method="POST" onsubmit="return confirm('স্ট্যাটাস পরিবর্তন করবেন?');">
                        <input type="hidden" name="id" value="<?= $it['id'] ?>">
                        <input type="hidden" name="new_status" value="<?= $it['active']?0:1 ?>">
                        <button class="btn btn-outline-<?= $it['active']?'warning':'success' ?>" name="toggle_active" value="1">
                          <i class="fas fa-power-off"></i>
                        </button>
                      </form>
                      <form method="POST" onsubmit="return confirm('মুছে ফেলবেন? এই কাজটি ফিরিয়ে নেওয়া যাবে না।');">
                        <input type="hidden" name="delete_id" value="<?= $it['id'] ?>">
                        <button class="btn btn-outline-danger"><i class="fas fa-trash"></i></button>
                      </form>
                    </div>
                  </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 recalc() {
    const v = n => parseInt(document.getElementById(n).value)||0;
    const sum = v('cq_marks') + v('mcq_marks') + v('practical_marks') + v('assignment_marks') + v('attendance_marks');
    document.getElementById('sum_marks').textContent = sum;
    const total = parseInt(document.getElementById('total_marks').value)||0;
    const el = document.getElementById('marks-summary');
    if (total>0 && sum===total) { el.className='alert alert-success'; el.innerHTML='মোট বিভাজিত: <strong>'+sum+'</strong> (সঠিক)'; }
    else if (sum>total) { el.className='alert alert-danger'; el.innerHTML='মোট বিভাজিত: <strong>'+sum+'</strong> (বেশি)'; }
    else { el.className='alert alert-info'; el.innerHTML='মোট বিভাজিত: <strong>'+sum+'</strong>'; }
  }
  ['cq_marks','mcq_marks','practical_marks','assignment_marks','attendance_marks','total_marks'].forEach(id=>{
    const el=document.getElementById(id); if(el){ el.addEventListener('input', recalc); }
  });
  recalc();
</script>
</body>
</html>
