<?php

/**

 * Scores Manual Entry Form

 */

require_once '../../config.php';

$conn = getDBConnection();



// Get students for dropdown

$students = $conn->query("SELECT id, student_id, first_name, last_name, class FROM students WHERE status = 'active' ORDER BY first_name");



// Get subjects for dropdown

$subjects = $conn->query("SELECT id, subject_name, subject_code FROM subjects WHERE active = 'yes' ORDER BY subject_name");



// Get terms and academic year

$currentYear = date('Y');

$academicYear = $currentYear . '-' . ($currentYear + 1);

$terms = ['1', '2', '3'];

?>

<div class="row-counter">

    <span><i class="fas fa-chart-line me-2"></i>Entering Scores - <span id="row-count">1</span> record(s)</span>

    <button type="button" class="btn btn-sm btn-primary" onclick="addRow()">

        <i class="fas fa-plus me-2"></i>Add Another Score

    </button>

</div>



<div id="rows-container">

    <!-- Row 1 -->

    <div class="data-row mb-4 p-3 border rounded">

        <div class="d-flex justify-content-between mb-3">

            <h6 class="text-primary">Score Record #1</h6>

            <span class="remove-row" onclick="removeRow(this)" title="Remove this score">

                <i class="fas fa-times-circle"></i>

            </span>

        </div>

        

        <div class="row">

            <div class="col-md-6 mb-3">

                <label class="form-label">Student <span class="text-danger">*</span></label>

                <select class="form-select student-select" name="scores[0][student_id]" required>

                    <option value="">Select Student</option>

                    <?php while($student = $students->fetch_assoc()): ?>

                    <option value="<?php echo $student['id']; ?>" data-class="<?php echo $student['class']; ?>">

                        <?php echo $student['first_name'] . ' ' . $student['last_name'] . ' (' . $student['student_id'] . ' - ' . $student['class'] . ')'; ?>

                    </option>

                    <?php endwhile; ?>

                </select>

            </div>

            <div class="col-md-6 mb-3">

                <label class="form-label">Subject <span class="text-danger">*</span></label>

                <select class="form-select subject-select" name="scores[0][subject_id]" required>

                    <option value="">Select Subject</option>

                    <?php 

                    mysqli_data_seek($subjects, 0);

                    while($subject = $subjects->fetch_assoc()): 

                    ?>

                    <option value="<?php echo $subject['id']; ?>">

                        <?php echo $subject['subject_name'] . ' (' . $subject['subject_code'] . ')'; ?>

                    </option>

                    <?php endwhile; ?>

                </select>

            </div>

        </div>

        

        <div class="row">

            <div class="col-md-3 mb-3">

                <label class="form-label">Class Score (%)</label>

                <input type="number" step="0.01" class="form-control class-score" name="scores[0][class_score]" min="0" max="100" value="0">

            </div>

            <div class="col-md-3 mb-3">

                <label class="form-label">Exam Score (%)</label>

                <input type="number" step="0.01" class="form-control exam-score" name="scores[0][exam_score]" min="0" max="100" value="0">

            </div>

            <div class="col-md-3 mb-3">

                <label class="form-label">Total Score</label>

                <input type="number" step="0.01" class="form-control total-score" name="scores[0][total_score]" readonly>

            </div>

            <div class="col-md-3 mb-3">

                <label class="form-label">Grade</label>

                <input type="text" class="form-control grade" name="scores[0][grade]" readonly placeholder="Auto-calculated">

            </div>

        </div>

        

        <div class="row">

            <div class="col-md-2 mb-3">

                <label class="form-label">Raw Class Score</label>

                <input type="number" step="0.01" class="form-control" name="scores[0][raw_class_score]" value="0">

            </div>

            <div class="col-md-2 mb-3">

                <label class="form-label">Raw Exam Score</label>

                <input type="number" step="0.01" class="form-control" name="scores[0][raw_exam_score]" value="0">

            </div>

            <div class="col-md-2 mb-3">

                <label class="form-label">Weighted Class</label>

                <input type="number" step="0.01" class="form-control" name="scores[0][weighted_class_score]" value="0">

            </div>

            <div class="col-md-2 mb-3">

                <label class="form-label">Weighted Exam</label>

                <input type="number" step="0.01" class="form-control" name="scores[0][weighted_exam_score]" value="0">

            </div>

            <div class="col-md-2 mb-3">

                <label class="form-label">Remark</label>

                <input type="text" class="form-control remark" name="scores[0][remark]" readonly placeholder="Auto">

            </div>

            <div class="col-md-2 mb-3">

                <label class="form-label">Position</label>

                <input type="text" class="form-control" name="scores[0][position]" placeholder="Optional">

            </div>

        </div>

        

        <div class="row">

            <div class="col-md-4 mb-3">

                <label class="form-label">Term <span class="text-danger">*</span></label>

                <select class="form-select" name="scores[0][term]" required>

                    <option value="">Select Term</option>

                    <option value="1">First Term</option>

                    <option value="2">Second Term</option>

                    <option value="3">Third Term</option>

                </select>

            </div>

            <div class="col-md-4 mb-3">

                <label class="form-label">Academic Year <span class="text-danger">*</span></label>

                <input type="text" class="form-control" name="scores[0][academic_year]" value="<?php echo $academicYear; ?>" required>

            </div>

            <div class="col-md-4 mb-3">

                <label class="form-label">Exam Date</label>

                <input type="date" class="form-control" name="scores[0][exam_date]">

            </div>

        </div>

        

        <div class="row">

            <div class="col-md-12 mb-3">

                <label class="form-label">Teacher's Comment</label>

                <textarea class="form-control" name="scores[0][teacher_comment]" rows="2" placeholder="Optional comment"></textarea>

            </div>

        </div>

    </div>

</div>



<script>

let rowCount = 1;



// Reset student data

<?php mysqli_data_seek($students, 0); ?>



function addRow() {

    const container = document.getElementById('rows-container');

    const template = container.children[0].cloneNode(true);

    

    // Update indices

    rowCount++;

    template.querySelectorAll('[name^="scores"]').forEach(input => {

        const name = input.getAttribute('name');

        input.setAttribute('name', name.replace(/\[\d+\]/, `[${rowCount-1}]`));

        if (input.type === 'select-one') {

            input.selectedIndex = 0;

        } else if (input.classList.contains('total-score') || 

                   input.classList.contains('grade') || 

                   input.classList.contains('remark')) {

            input.value = '';

        } else if (input.type !== 'date') {

            input.value = input.name.includes('score') && !input.classList.contains('total-score') ? '0' : '';

        }

    });

    

    // Update header

    template.querySelector('h6.text-primary').textContent = `Score Record #${rowCount}`;

    

    container.appendChild(template);

    document.getElementById('row-count').textContent = rowCount;

    

    // Attach calculation listeners

    attachCalculationListeners();

}



function removeRow(btn) {

    if (rowCount > 1) {

        btn.closest('.data-row').remove();

        rowCount--;

        document.getElementById('row-count').textContent = rowCount;

        

        // Renumber remaining rows

        document.querySelectorAll('.data-row').forEach((row, index) => {

            row.querySelector('h6.text-primary').textContent = `Score Record #${index + 1}`;

            row.querySelectorAll('[name^="scores"]').forEach(input => {

                const name = input.getAttribute('name');

                input.setAttribute('name', name.replace(/\[\d+\]/, `[${index}]`));

            });

        });

        

        attachCalculationListeners();

    }

}



// Calculate total and grade

function calculateTotal(row) {

    const classScore = parseFloat(row.querySelector('.class-score').value) || 0;

    const examScore = parseFloat(row.querySelector('.exam-score').value) || 0;

    const total = classScore + examScore;

    

    const totalInput = row.querySelector('.total-score');

    totalInput.value = total.toFixed(2);

    

    // Calculate grade (simple grading - you can adjust based on your grade_boundaries table)

    let grade = '';

    let remark = '';

    

    if (total >= 80) {

        grade = 'A';

        remark = 'Excellent';

    } else if (total >= 70) {

        grade = 'B';

        remark = 'Very Good';

    } else if (total >= 60) {

        grade = 'C';

        remark = 'Good';

    } else if (total >= 50) {

        grade = 'D';

        remark = 'Pass';

    } else if (total >= 40) {

        grade = 'E';

        remark = 'Poor';

    } else {

        grade = 'F';

        remark = 'Fail';

    }

    

    row.querySelector('.grade').value = grade;

    row.querySelector('.remark').value = remark;

}



// Attach listeners to all rows

function attachCalculationListeners() {

    document.querySelectorAll('.data-row').forEach(row => {

        const classInput = row.querySelector('.class-score');

        const examInput = row.querySelector('.exam-score');

        

        // Remove existing listeners

        const newClass = classInput.cloneNode(true);

        const newExam = examInput.cloneNode(true);

        classInput.parentNode.replaceChild(newClass, classInput);

        examInput.parentNode.replaceChild(newExam, examInput);

        

        // Add new listeners

        newClass.addEventListener('input', () => calculateTotal(row));

        newExam.addEventListener('input', () => calculateTotal(row));

    });

}



// Initialize listeners

attachCalculationListeners();

</script>