<?php
session_start();
include '../../includes/db_connection.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: /school_management/public/index.php");
    exit();
}

$message = '';
$error = '';
$success_count = 0;
$fail_count = 0;

// Handle form submission for multiple results
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $student_id = $_POST['student_id'];
    $exam_id = $_POST['exam_id'];
    $subjects = $_POST['subject_id'];
    $marks = $_POST['marks'];

    if (count($subjects) != count($marks)) {
        $error = "প্রদত্ত ডেটাতে অসামঞ্জস্য রয়েছে।";
    } else {
        $sql = "INSERT INTO exam_results (student_id, subject_id, exam_id, marks) VALUES (?, ?, ?, ?)";
        $stmt = $conn->prepare($sql);
        
        if ($stmt === false) {
            $error = "SQL কোয়েরি তৈরিতে সমস্যা: " . $conn->error;
        } else {
            for ($i = 0; $i < count($subjects); $i++) {
                $subject_id = $subjects[$i];
                $mark = $marks[$i];

                if (!empty($subject_id) && !empty($mark)) {
                    $stmt->bind_param("iiid", $student_id, $subject_id, $exam_id, $mark);
                    if ($stmt->execute()) {
                        $success_count++;
                    } else {
                        $fail_count++;
                        error_log("Result insert failed for student $student_id, subject $subject_id: " . $stmt->error);
                    }
                }
            }
            $stmt->close();

            if ($success_count > 0) {
                $message = "$success_count টি ফলাফল সফলভাবে যুক্ত করা হয়েছে!";
            }
            if ($fail_count > 0) {
                $error .= " $fail_count টি ফলাফল যুক্ত করার সময় সমস্যা হয়েছে।";
            }
        }
    }
}

// Fetch classes and exams for dropdowns
$classes_sql = "SELECT class_id, class_name FROM classes ORDER BY class_name";
$classes_result = $conn->query($classes_sql);

$exams_sql = "SELECT exam_id, exam_name FROM exams ORDER BY exam_name";
$exams_result = $conn->query($exams_sql);
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>নতুন ফলাফল যুক্ত করুন</title>
    <link rel="stylesheet" href="/school_management/public/css/style.css">
    <style>
        .form-container {
            width: 700px;
            margin: 20px auto;
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        .form-container h2 {
            text-align: center;
            color: #333;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        .form-group select, .form-group input, .form-group textarea {
            width: 100%;
            padding: 8px;
            box-sizing: border-box;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
        .result-row {
            display: flex;
            gap: 10px;
            margin-bottom: 10px;
            align-items: flex-end;
        }
        .result-row .form-group {
            flex: 1;
            margin-bottom: 0;
        }
        .result-row .remove-btn {
            background-color: #dc3545;
            color: white;
            border: none;
            padding: 8px 12px;
            border-radius: 4px;
            cursor: pointer;
            height: 38px;
        }
        .add-btn {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 4px;
            cursor: pointer;
            margin-top: 10px;
        }
        .form-buttons {
            text-align: center;
            margin-top: 20px;
        }
        .form-buttons button, .form-buttons a {
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
            border: none;
            border-radius: 5px;
            color: white;
            background-color: #28a745;
            transition: background-color 0.3s;
            text-decoration: none;
            display: inline-block;
            margin: 0 5px;
        }
        .form-buttons button:hover, .form-buttons a:hover {
            background-color: #218838;
        }
        .message-success {
            color: green;
            text-align: center;
            font-weight: bold;
        }
        .message-error {
            color: red;
            text-align: center;
            font-weight: bold;
        }
        .hidden-template {
            display: none;
        }
    </style>
</head>
<body>
<div class="header">
    <h1>স্কুল ম্যানেজমেন্ট সিস্টেম</h1>
    <div class="nav">
        <a href="/school_management/public/dashboard.php">ড্যাশবোর্ড</a>
        <a href="/school_management/public/students/students_list.php">শিক্ষার্থী</a>
        <a href="/school_management/public/teachers/teachers_list.php">শিক্ষক</a>
        <a href="/school_management/public/fees/fee_collection.php">ফি সংগ্রহ</a>
        <a href="/school_management/public/subjects/subjects_list.php">বিষয়সমূহ</a>
        <a href="/school_management/public/exam_results/add_exam_result.php">পরীক্ষা</a>
        <a href="/school_management/public/attendance/record_attendance.php">উপস্থিতি</a>
        <a href="/school_management/public/change_password.php">পাসওয়ার্ড পরিবর্তন</a>
        <a href="/school_management/public/logout.php">লগআউট</a>
    </div>
</div>
<div class="content">
    <div class="form-container">
        <h2>নতুন ফলাফল যুক্ত করুন</h2>
        <?php if ($message): ?>
            <p class="message-success"><?php echo $message; ?></p>
        <?php endif; ?>
        <?php if ($error): ?>
            <p class="message-error"><?php echo $error; ?></p>
        <?php endif; ?>

        <form action="add_exam_result.php" method="POST">
            <div class="form-group">
                <label for="class_id">শ্রেণি নির্বাচন করুন:</label>
                <select id="class_id" name="class_id" required>
                    <option value="">নির্বাচন করুন</option>
                    <?php while($row = $classes_result->fetch_assoc()): ?>
                        <option value="<?php echo htmlspecialchars($row['class_id']); ?>">
                            <?php echo htmlspecialchars($row['class_name']); ?>
                        </option>
                    <?php endwhile; ?>
                </select>
            </div>

            <div class="form-group">
                <label for="student_id">শিক্ষার্থীর নাম:</label>
                <select id="student_id" name="student_id" required disabled>
                    <option value="">আগে একটি শ্রেণি নির্বাচন করুন</option>
                </select>
            </div>
            
            <div class="form-group">
                <label for="exam_id">পরীক্ষার ধরন:</label>
                <select id="exam_id" name="exam_id" required>
                    <option value="">নির্বাচন করুন</option>
                    <?php while($row = $exams_result->fetch_assoc()): ?>
                        <option value="<?php echo htmlspecialchars($row['exam_id']); ?>">
                            <?php echo htmlspecialchars($row['exam_name']); ?>
                        </option>
                    <?php endwhile; ?>
                </select>
            </div>

            <div id="results-container">
                </div>
            
            <button type="button" class="add-btn" id="add-subject-btn">আরো বিষয় যোগ করুন</button>

            <div class="form-buttons">
                <button type="submit">ফলাফল যোগ করুন</button>
                <a href="exam_report.php" class="button">ফলাফল তালিকা</a>
            </div>
        </form>

        <div id="result-template" class="hidden-template">
            <div class="result-row">
                <div class="form-group">
                    <label>বিষয়:</label>
                    <select name="subject_id[]">
                        <option value="">নির্বাচন করুন</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>নম্বর:</label>
                    <input type="number" step="0.01" name="marks[]" placeholder="প্রাপ্ত নম্বর">
                </div>
                <button type="button" class="remove-btn">মুছুন</button>
            </div>
        </div>
    </div>
</div>
<div class="footer">
    <p>&copy; <?php echo date("Y"); ?> স্কুল ম্যানেজমেন্ট সিস্টেম। সর্বস্বত্ব সংরক্ষিত।</p>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const classSelect = document.getElementById('class_id');
    const studentSelect = document.getElementById('student_id');
    const addSubjectBtn = document.getElementById('add-subject-btn');
    const resultsContainer = document.getElementById('results-container');
    const resultTemplate = document.getElementById('result-template');

    function fetchSubjects(classId) {
        fetch(`/school_management/public/subjects/get_subjects_by_class.php?class_id=${classId}`)
            .then(response => response.json())
            .then(subjects => {
                let subjectOptions = '<option value="">নির্বাচন করুন</option>';
                subjects.forEach(subject => {
                    subjectOptions += `<option value="${subject.subject_id}">${subject.subject_name}</option>`;
                });
                resultTemplate.querySelector('select[name="subject_id[]"]').innerHTML = subjectOptions;
                resultsContainer.innerHTML = ''; // Clear previous subjects
                if (subjects.length > 0) {
                    addSubjectBtn.click();
                }
            })
            .catch(error => {
                console.error('Error fetching subjects:', error);
                resultTemplate.querySelector('select[name="subject_id[]"]').innerHTML = '<option value="">বিষয় লোড করতে সমস্যা হয়েছে</option>';
            });
    }

    function fetchStudents(classId) {
        studentSelect.innerHTML = '<option value="">শিক্ষার্থী লোড হচ্ছে...</option>';
        studentSelect.disabled = true;

        if (classId === "") {
            studentSelect.innerHTML = '<option value="">আগে একটি শ্রেণি নির্বাচন করুন</option>';
            studentSelect.disabled = true;
            return;
        }

        fetch(`/school_management/public/students/get_students_by_class.php?class_id=${classId}`)
            .then(response => response.json())
            .then(students => {
                let options = '<option value="">নির্বাচন করুন</option>';
                students.forEach(student => {
                    options += `<option value="${student.student_id}">${student.first_name} ${student.last_name} (${student.class_roll})</option>`;
                });
                studentSelect.innerHTML = options;
                studentSelect.disabled = false;
            })
            .catch(error => {
                console.error('Error fetching students:', error);
                studentSelect.innerHTML = '<option value="">শিক্ষার্থী লোড করতে সমস্যা হয়েছে</option>';
            });
    }

    classSelect.addEventListener('change', function() {
        const selectedClassId = this.value;
        if (selectedClassId) {
            fetchStudents(selectedClassId);
            fetchSubjects(selectedClassId);
        }
    });

    addSubjectBtn.addEventListener('click', function() {
        const newRow = resultTemplate.querySelector('.result-row').cloneNode(true);
        newRow.querySelector('select[name="subject_id[]"]').required = true;
        newRow.querySelector('input[name="marks[]"]').required = true;
        resultsContainer.appendChild(newRow);
    });

    resultsContainer.addEventListener('click', function(e) {
        if (e.target.classList.contains('remove-btn')) {
            e.target.closest('.result-row').remove();
        }
    });
});
</script>

</body>
</html>