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

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

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $subject_id = $_POST['subject_id'];
    $class_id = $_POST['class_id'];
    $session = $_POST['session'];
    $exam_type = $_POST['exam_type'];
    $total_marks = $_POST['total_marks'];
    
    // Default distribution - can be customized later
    $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'];
    
    // Separate passing marks (optional)
    $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;
    
    // 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, 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) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE
                total_marks = VALUES(total_marks),
                cq_marks = VALUES(cq_marks),
                mcq_marks = VALUES(mcq_pass_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),
                updated_at = CURRENT_TIMESTAMP
            ");
            
            $stmt->execute([
                $subject_id, $class_id, $session, $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
            ]);
            
            $success_message = "মার্কস বিভাজন সফলভাবে সেভ করা হয়েছে!";
        } catch (Exception $e) {
            $error_message = "ত্রুটি: " . $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>দ্রুত মার্কস বিভাজন সেটআপ - স্কুল ম্যানেজমেন্ট সিস্টেম</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body class="bengali-text">
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট সিস্টেম
            </a>
            
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="../index.php">
                    <i class="fas fa-home"></i> হোম
                </a>
                <a class="nav-link" href="setup.php">
                    <i class="fas fa-cog"></i> সাধারণ সেটআপ
                </a>
                <a class="nav-link" href="entry.php">
                    <i class="fas fa-edit"></i> মার্কস এন্ট্রি
                </a>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <div class="row">
            <div class="col-md-8 mx-auto">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h4><i class="fas fa-bolt"></i> দ্রুত মার্কস বিভাজন সেটআপ</h4>
                        <p class="mb-0">খুব সহজে মার্কস বিভাজন কনফিগার করুন</p>
                    </div>
                    <div class="card-body">
                        <?php if ($success_message): ?>
                            <div class="alert alert-success alert-dismissible fade show">
                                <i class="fas fa-check-circle"></i> <?php echo $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">
                                <i class="fas fa-exclamation-triangle"></i> <?php echo $error_message; ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        <?php endif; ?>

                        <form method="POST" action="" class="needs-validation" novalidate>
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="subject_id" class="form-label">বিষয় <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">ক্লাস <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-6 mb-3">
                                    <label for="session" class="form-label">সেশন <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-6 mb-3">
                                    <label for="exam_type" class="form-label">পরীক্ষার ধরন <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>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="total_marks" class="form-label">মোট নম্বর <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control" id="total_marks" name="total_marks" min="1" max="1000" value="100" required>
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <label for="overall_pass_marks" class="form-label">সামগ্রিক পাস নম্বর <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control" id="overall_pass_marks" name="overall_pass_marks" min="1" value="40" required>
                                    <div class="form-text">পাস নম্বর কাস্টমাইজ করুন</div>
                                </div>
                            </div>
                            
                            <div class="card bg-light mb-3">
                                <div class="card-header">
                                    <h6><i class="fas fa-chart-pie"></i> নম্বর বিভাজন</h6>
                                    <small class="text-muted">মোট নম্বর 100 হলে নিচের ফরম্যাট অনুসরণ করুন</small>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label for="cq_marks" class="form-label">সৃজনশীল প্রশ্ন (CQ)</label>
                                            <input type="number" class="form-control mark-input" id="cq_marks" name="cq_marks" min="0" value="70" required>
                                        </div>
                                        
                                        <div class="col-md-6 mb-3">
                                            <label for="mcq_marks" class="form-label">বহুনির্বাচনি (MCQ)</label>
                                            <input type="number" class="form-control mark-input" id="mcq_marks" name="mcq_marks" min="0" value="30" required>
                                        </div>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-4 mb-3">
                                            <label for="practical_marks" class="form-label">ব্যবহারিক</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">অ্যাসাইনমেন্ট</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">উপস্থিতি</label>
                                            <input type="number" class="form-control mark-input" id="attendance_marks" name="attendance_marks" min="0" value="0">
                                        </div>
                                    </div>
                                    
                                    <div class="alert alert-info" id="marks-summary">
                                        <strong>মোট বিভাজিত নম্বর: <span id="total-distributed">100</span></strong>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Separate Passing Marks -->
                            <div class="card bg-light mb-3">
                                <div class="card-header">
                                    <h6><i class="fas fa-medal"></i> আলাদা পাসিং মার্কস (ঐচ্ছিক)</h6>
                                    <small class="text-muted">প্রয়োজনে CQ, MCQ, ব্যবহারিক এর জন্য আলাদা পাসিং মার্কস সেট করুন</small>
                                </div>
                                <div class="card-body">
                                    <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>

                            <div class="d-grid gap-2">
                                <button type="submit" class="btn btn-primary btn-lg">
                                    <i class="fas fa-save"></i> সেভ করুন
                                </button>
                                <button type="reset" class="btn btn-secondary">
                                    <i class="fas fa-undo"></i> ফর্ম ক্লিয়ার
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
                
                <div class="card mt-4">
                    <div class="card-header bg-info text-white">
                        <h5><i class="fas fa-lightbulb"></i> দ্রুত সেটআপ টিপস</h5>
                    </div>
                    <div class="card-body">
                        <ul>
                            <li>সব ফিল্ড পূরণ করুন</li>
                            <li>মোট নম্বর এবং বিভাজিত নম্বরের যোগফল সমান হতে হবে</li>
                            <li>পাস নম্বর অটো ক্যালকুলেটেড (40%)</li>
                            <li>প্রয়োজনে বিভাজন পরিবর্তন করুন</li>
                            <li>ব্যবহারিক/অ্যাসাইনমেন্ট/উপস্থিতি নম্বর প্রয়োজনে বাড়ান</li>
                        </ul>
                        <p class="mb-0">
                            <a href="setup.php" class="btn btn-outline-primary">
                                <i class="fas fa-cog"></i> অ্যাডভান্সড সেটআপ
                            </a>
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Calculate total distributed marks
        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');
            
            if (total === totalMarks && totalMarks > 0) {
                summaryDiv.className = 'alert alert-success';
                summaryDiv.innerHTML = '<strong><i class="fas fa-check"></i> মোট বিভাজিত নম্বর: ' + total + ' (সঠিক)</strong>';
            } else if (total > totalMarks) {
                summaryDiv.className = 'alert alert-danger';
                summaryDiv.innerHTML = '<strong><i class="fas fa-exclamation-triangle"></i> মোট বিভাজিত নম্বর: ' + total + ' (বেশি)</strong>';
            } else {
                summaryDiv.className = 'alert alert-warning';
                summaryDiv.innerHTML = '<strong><i class="fas fa-info"></i> মোট বিভাজিত নম্বর: ' + total + '</strong>';
            }
        }
        
        // Update marks total when inputs change
        document.getElementById('total_marks').addEventListener('input', updateMarksTotal);
        
        // Add event listeners
        document.querySelectorAll('.mark-input').forEach(input => {
            input.addEventListener('input', updateMarksTotal);
        });
        
        // Initialize
        updateMarksTotal();
        
        // Form validation
        (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();
                        }
                        form.classList.add('was-validated');
                    }, false);
                });
            }, false);
        })();
    </script>
</body>
</html>