<?php
// get_students.php - WITH DISABLED INPUT FOR EXISTING MARKS
include("includes/db.php");

error_reporting(E_ALL);
ini_set('display_errors', 1);

if ($_SERVER["REQUEST_METHOD"] != "POST") {
    die("Invalid request!");
}

$classId = intval($_POST["classId"] ?? 0);
$subjectId = intval($_POST["subjectId"] ?? 0);
$examId = intval($_POST["examId"] ?? 0);
$markType = $_POST["markType"] ?? 'theory';

if ($classId == 0 || $subjectId == 0 || $examId == 0) {
    die("Invalid parameters!");
}

// Get subject details
$subjectQuery = $conn->query("
    SELECT 
        s.subject_code, 
        s.subject_name,
        COALESCE(esm.full_marks_theory, 100) as full_marks_theory,
        COALESCE(esm.full_marks_internal, 50) as full_marks_internal
    FROM subjects s
    LEFT JOIN exam_subject_marks esm ON esm.subject_id = s.id 
        AND esm.exam_id = $examId 
        AND esm.class_id = $classId
    WHERE s.id = $subjectId
");

if (!$subjectQuery || $subjectQuery->num_rows == 0) {
    die("Subject not found!");
}

$subjectRow = $subjectQuery->fetch_assoc();
$subjectCode = $subjectRow['subject_code'];
$subjectName = $subjectRow['subject_name'];
$fullMarksTheory = floatval($subjectRow['full_marks_theory']);
$fullMarksInternal = floatval($subjectRow['full_marks_internal']);

// Get students
$studentQuery = $conn->query("
    SELECT DISTINCT s.student_id, s.regd_id, s.name,
           COALESCE(sn.symbol_no, 'N/A') AS symbol_no
    FROM students s
    LEFT JOIN symbolno_data sn ON s.student_id = sn.student_id AND sn.exam_id = $examId
    WHERE s.class_id = $classId 
    AND s.status = 'active'
    AND EXISTS (
        SELECT 1 FROM studentsub st 
        WHERE st.student_id = s.student_id 
        AND (
            st.sub1 = '$subjectCode' OR st.sub2 = '$subjectCode' OR 
            st.sub3 = '$subjectCode' OR st.sub4 = '$subjectCode' OR 
            st.sub5 = '$subjectCode' OR st.sub6 = '$subjectCode' OR 
            st.sub7 = '$subjectCode'
        )
    )
    ORDER BY 
        CASE WHEN sn.symbol_no = 'N/A' THEN 1 ELSE 0 END,
        sn.symbol_no,
        s.name
");

if ($studentQuery->num_rows == 0) {
    echo '<div class="alert alert-warning">No students found for this subject.</div>';
    exit;
}

// Display header
echo '<div class="card mb-3 border-primary">';
// echo '<div class="card-header bg-primary text-white">';
// echo '<h4 class="mb-0"><i class="bi bi-journal-text"></i> ' . htmlspecialchars($subjectName) . '<strong>     (Subject Code:</strong> <span class="badge bg-info">' . htmlspecialchars($subjectCode) . '</span>)</h4>';
// echo '</div>';
echo '<div class="card-body">';
echo '<div class="row">';
echo '<div class="col-md-8">';

echo '<strong>Full Marks: [TH:</strong> <span class="badge bg-success">' . number_format($fullMarksTheory, 2) . ' </span>';

echo '<strong>|| IN:</strong> <span class="badge bg-warning">' . number_format($fullMarksInternal, 2) . '</span>';

echo '<strong>|| Marking Type:</strong> <span class="badge bg-primary">' . ($markType == 'theory' ? 'Theory' : 'Internal') . '</span>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';



// Student count
// echo '<div class="alert alert-info mb-3">';
// echo '<i class="bi bi-people-fill"></i> Found <strong>' . $studentQuery->num_rows . '</strong> student(s)';
// echo '</div>';

// Start table
echo '<div class="table-responsive">';
echo '<table class="table table-bordered table-hover table-sm">';
echo '<thead class="table-dark">';
echo '<tr>';
echo '<th width="auto">#</th>';
// echo '<th width="auto">Symbol No</th>';
echo '<th>Student Name</th>';
// echo '<th width="auto">Reg ID</th>';
// echo '<th width="120" class="text-center">Theory<br><small class="text-muted">Max: ' . $fullMarksTheory . '</small></th>';
// echo '<th width="120" class="text-center">Internal<br><small class="text-muted">Max: ' . $fullMarksInternal . '</small></th>';
echo '<th width="auto" class="text-center">Enter ' . ($markType == 'theory' ? 'Theory' : 'Internal') . ' Marks</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';

$sn = 1;
$hasExistingMarks = false;
while ($row = $studentQuery->fetch_assoc()) {
    $studentId = $row['student_id'];
    $symbolNo = $row['symbol_no'];
    
    // Get existing marks
    $marksQuery = $conn->query("
        SELECT mark_type, marks 
        FROM marks 
        WHERE student_id = $studentId 
        AND exam_type = $examId 
        AND subject_id = $subjectId 
        AND class_id = $classId
    ");
    
    $theoryMarks = '';
    $practicalMarks = '';
    while ($m = $marksQuery->fetch_assoc()) {
        if ($m['mark_type'] == 'theory') {
            $theoryMarks = number_format(floatval($m['marks']), 2);
        } elseif ($m['mark_type'] == 'practical') {
            $practicalMarks = number_format(floatval($m['marks']), 2);
        }
    }
    
    $currentMarks = ($markType == 'theory') ? $theoryMarks : $practicalMarks;
    $maxMarks = ($markType == 'theory') ? $fullMarksTheory : $fullMarksInternal;
    
    // Check if marks exist for this mark type
    $hasMarks = ($markType == 'theory' && !empty($theoryMarks)) || 
                ($markType == 'practical' && !empty($practicalMarks));
    
    if ($hasMarks) {
        $hasExistingMarks = true;
    }
    
    echo '<tr>';
    echo '<td class="text-center">' . $sn++ . '</td>';
    // echo '<td class="text-center"><strong>' . ($symbolNo == 'N/A' ? '-' : $symbolNo) . '</strong></td>';
    echo '<td><strong>'. htmlspecialchars($row['name']). '</strong><p><strong><span style="color:Red">  (Sym.No:' . ($symbolNo == 'N/A' ? '-' : $symbolNo) . ')</span></strong>'.'</td>';
    
    // Theory marks
    // echo '<td class="text-center align-middle">';
    // if ($theoryMarks) {
    //     $percentage = ($theoryMarks / $fullMarksTheory * 100);
    //     $badgeClass = ($percentage >= 40) ? 'bg-success' : 'bg-danger';
    //     echo '<span class="badge ' . $badgeClass . '">' . $theoryMarks . '</span>';
    //     echo '<br><small class="text-muted">' . number_format($percentage, 1) . '%</small>';
    // } else {
    //     echo '<span class="badge bg-secondary">Not Entered</span>';
    // }
    // echo '</td>';
    
    // Internal marks
    // echo '<td class="text-center align-middle">';
    // if ($practicalMarks) {
    //     $percentage = ($practicalMarks / $fullMarksInternal * 100);
    //     $badgeClass = ($percentage >= 40) ? 'bg-success' : 'bg-danger';
    //     echo '<span class="badge ' . $badgeClass . '">' . $practicalMarks . '</span>';
    //     echo '<br><small class="text-muted">' . number_format($percentage, 1) . '%</small>';
    // } else {
    //     echo '<span class="badge bg-secondary">Not Entered</span>';
    // }
    // echo '</td>';
    
    // Input field - DISABLED if marks exist
    echo '<td class="text-center">';
    echo '<div class="form-group-sm">';
    
    if ($hasMarks) {
        // Input is DISABLED because marks already exist
        echo '<input type="number" 
                     step="0.01" 
                     min="0" 
                     max="' . $maxMarks . '"
                     name="marks[' . $studentId . ']" 
                     class="form-control col-md-8" 
                     value="' . $currentMarks . '" 
                     disabled
                     style="height: 36px; background-color: #e9ecef; cursor: not-allowed;">';
       
        echo '</div>';
    } else {
        // Input is ENABLED - no marks exist yet
        echo '<input type="number" 
                     step="0.01" 
                     min="0" 
                     max="' . $maxMarks . '"
                     name="marks[' . $studentId . ']" 
                     class="form-control col-md-8"
                     value="' . $currentMarks . '" 
                     placeholder="Enter '. $markType.' marks"
                     data-max="' . $maxMarks . '"
                     style="height: 36px;">';
        //echo '<span class="input-group-text" style="height: 36px;">/' . number_format($maxMarks, 2) . '</span>';
    }
    
    echo '</div>';
    echo '</td>';
    
    echo '</tr>';
}
// Add warning if some marks already exist
if ($hasExistingMarks) {
    echo '<div class="alert alert-warning mt-3">';
    echo '<i class="bi bi-exclamation-triangle"></i> <strong>Note:</strong> Marks Already Entered and Saved. ';
    echo 'Locked fields cannot be modified here. To update existing marks, contact the administrator.';
    echo '</div>';
}
echo '</tbody>';
echo '</table>';
echo '</div>';



// Add validation script
echo '<script>
$(document).ready(function() {
    // Only bind to enabled inputs
    $(".marks-input:not(:disabled)").on("input", function() {
        var max = parseFloat($(this).data("max"));
        var value = parseFloat($(this).val()) || 0;
        
        if (value > max) {
            $(this).addClass("is-invalid");
            $(this).next(".invalid-feedback").remove();
            $(this).after(\'<div class="invalid-feedback" style="color:Red">Marks cannot exceed \' + max.toFixed(2) + \'</div>\');
        } else if (value < 0) {
            $(this).addClass("is-invalid");
            $(this).next(".invalid-feedback").remove();
            $(this).after(\'<div class="invalid-feedback">Marks cannot be negative</div>\');
        } else {
            $(this).removeClass("is-invalid");
            $(this).next(".invalid-feedback").remove();
        }
    });
});
</script>';

$conn->close();
?>