<?php
include('../includes/db.php');

header('Content-Type: text/html; charset=utf-8');

if(isset($_POST['class_id']) && !empty($_POST['class_id']) && 
   isset($_POST['section_id']) && !empty($_POST['section_id']) &&
   isset($_POST['session_id']) && !empty($_POST['session_id']) &&
   isset($_POST['exam_id']) && !empty($_POST['exam_id'])) {
    
    $class_id = intval($_POST['class_id']);
    $section_id = intval($_POST['section_id']);
    $session_id = intval($_POST['session_id']);
    $exam_id = intval($_POST['exam_id']);
    
    try {
        // Get subjects from class_subject_mapping that are linked to the subjects table
        $query = "SELECT 
                    csm.id as mapping_id,
                    s.id,
                    s.subject_code,
                    s.subject_name,
                    s.theory_full_marks as default_theory_marks,
                    s.internal_full_marks as default_internal_marks,
                    s.theory_credit_hour as default_theory_credit,
                    s.internal_credit_hour as default_internal_credit,
                    s.type as subject_type,
                    esm.full_marks_theory,
                    esm.full_marks_internal,
                    esm.theory_credit_hour as existing_theory_credit,
                    esm.internal_credit_hour as existing_internal_credit,
                    esm.remarks
                  FROM class_subject_mapping csm
                  INNER JOIN subjects s ON csm.subject_id = s.id
                  LEFT JOIN exam_subject_marks esm ON 
                    csm.subject_id = esm.subject_id AND 
                    csm.class_id = esm.class_id AND 
                    csm.section_id = esm.section_id AND 
                    esm.session_id = ? AND 
                    esm.exam_id = ?
                  WHERE csm.class_id = ? 
                    AND csm.section_id = ?
                    AND (csm.academic_year_id = ? OR csm.academic_year_id IS NULL)
                    AND s.status = 1
                  ORDER BY s.subject_code";
        
        $stmt = $conn->prepare($query);
        $stmt->bind_param("iiiii", $session_id, $exam_id, $class_id, $section_id, $session_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if($result->num_rows > 0) {
            echo '<div class="alert alert-success">';
            echo '<i class="fa fa-check-circle"></i> ';
            echo 'Found subjects for this class-section. Enter/Edit full marks:';
            echo '</div>';
            
            echo '<div class="table-responsive">';
            echo '<table class="table table-bordered table-hover" id="marksTable">';
            echo '<thead class="thead-dark">';
            echo '<tr>';
            echo '<th width="5%">#</th>';
            echo '<th width="25%">Subject Details</th>';
            echo '<th width="15%">Theory Full Marks</th>';
            echo '<th width="15%">Internal Full Marks</th>';
            echo '<th width="10%">Theory Credit</th>';
            echo '<th width="10%">Internal Credit</th>';
            echo '<th width="15%">Remarks</th>';
            echo '</tr>';
            echo '</thead>';
            echo '<tbody>';
            
            $counter = 0;
            $total_theory = 0;
            $total_internal = 0;
            $total_theory_credit = 0;
            $total_internal_credit = 0;
            
            while($row = $result->fetch_assoc()) {
                $counter++;
                
                // Determine which values to use (existing or defaults)
                $theory_marks = !empty($row['full_marks_theory']) ? $row['full_marks_theory'] : $row['default_theory_marks'];
                $internal_marks = !empty($row['full_marks_internal']) ? $row['full_marks_internal'] : $row['default_internal_marks'];
                $theory_credit = !empty($row['existing_theory_credit']) ? $row['existing_theory_credit'] : $row['default_theory_credit'];
                $internal_credit = !empty($row['existing_internal_credit']) ? $row['existing_internal_credit'] : $row['default_internal_credit'];
                $remarks = $row['remarks'] ?? '';
                
                // Determine badge class based on subject type
                $type_class = '';
                $type_text = ucfirst($row['subject_type']);
                switch(strtolower($row['subject_type'])) {
                    case 'compulsory': $type_class = 'type-compulsory'; break;
                    case 'optional': $type_class = 'type-optional'; break;
                    case 'elective': $type_class = 'type-elective'; break;
                    default: $type_class = 'type-compulsory';
                }
                
                echo '<tr>';
                echo '<td>' . $counter . '</td>';
                echo '<td>';
                echo '<strong>' . htmlspecialchars($row['subject_name']) . '</strong><br>';
                echo '<small class="text-muted">Code: ' . htmlspecialchars($row['subject_code']) . '</small><br>';
                echo '<span class="subject-type-badge ' . $type_class . '">' . $type_text . '</span>';
                echo '<input type="hidden" name="subject_id[]" value="' . $row['id'] . '">';
                echo '</td>';
                echo '<td>';
                echo '<input type="number" step="0.01" min="0" max="1000" name="full_marks_theory[]" ';
                echo 'class="form-control marks-input" placeholder="Theory marks" ';
                echo 'value="' . htmlspecialchars($theory_marks) . '" ';
                echo 'title="Default: ' . htmlspecialchars($row['default_theory_marks']) . '" ';
                echo 'data-toggle="tooltip">';
                echo '</td>';
                echo '<td>';
                echo '<input type="number" step="0.01" min="0" max="1000" name="full_marks_internal[]" ';
                echo 'class="form-control marks-input" placeholder="Internal marks" ';
                echo 'value="' . htmlspecialchars($internal_marks) . '" ';
                echo 'title="Default: ' . htmlspecialchars($row['default_internal_marks']) . '" ';
                echo 'data-toggle="tooltip">';
                echo '</td>';
                echo '<td>';
                echo '<input type="number"
                        step="0.01"
                        min="0"
                        max="10"
                         name="theory_credit_hour[]" ';
                echo 'class="form-control credit-input" placeholder="Credit" ';
                echo 'value="' . htmlspecialchars($theory_credit) . '" ';
                echo 'title="Default: ' . htmlspecialchars($row['default_theory_credit']) . '" ';
                echo 'data-toggle="tooltip">';
                echo '</td>';
                echo '<td>';
echo '<input 
        type="number"
        step="0.01"
        min="0"
        max="10"
        name="internal_credit_hour[]"
        class="form-control credit-input"
        placeholder="Credit"
        value="' . htmlspecialchars($internal_credit) . '"
        title="Default: ' . htmlspecialchars($row['default_internal_credit']) . '"
        data-toggle="tooltip">';
echo '</td>';

                echo '<td>';
                echo '<input type="text" name="remarks[]" class="form-control" ';
                echo 'placeholder="Optional remarks" ';
                echo 'value="' . htmlspecialchars($remarks) . '">';
                echo '</td>';
                echo '</tr>';
                
                // Calculate totals
                $total_theory += floatval($theory_marks) ?: 0;
                $total_internal += floatval($internal_marks) ?: 0;
                $total_theory_credit += floatval($theory_credit) ?: 0;
                $total_internal_credit += floatval($internal_credit) ?: 0;
            }
            
            // Total row
            echo '<tr id="totalRow" class="total-row">';
            echo '<td colspan="2" class="text-right"><strong>TOTAL:</strong></td>';
            echo '<td><span id="totalTheory">' . number_format($total_theory, 2) . '</span></td>';
            echo '<td><span id="totalInternal">' . number_format($total_internal, 2) . '</span></td>';
            echo '<td><span id="totalTheoryCredit">' . number_format($total_theory_credit, 2) . '</span></td>';
            echo '<td><span id="totalInternalCredit">' . number_format($total_internal_credit, 2) . '</span></td>';
            echo '<td></td>';
            echo '</tr>';
            
            echo '</tbody>';
            echo '</table>';
            
            // Summary
            echo '<div class="row">';
            echo '<div class="col-md-12">';
            echo '<div class="alert alert-info">';
            echo '<i class="fa fa-info-circle"></i> ';
            echo 'Total: <strong>' . $counter . '</strong> subject(s) | ';
            echo 'Theory Total: <strong>' . number_format($total_theory, 2) . '</strong> | ';
            echo 'Internal Total: <strong>' . number_format($total_internal, 2) . '</strong> | ';
            echo 'Theory Credits: <strong>' . number_format($total_theory_credit, 2) . '</strong> | ';
            echo 'Internal Credits: <strong>' . number_format($total_internal_credit, 2) . '</strong>';
            echo '</div>';
            echo '</div>';
            echo '</div>';
            
            echo '</div>'; // Close table-responsive
            
            // Initialize tooltips
            echo '<script>';
            echo '$(document).ready(function() {';
            echo '  $(\'[data-toggle="tooltip"]\').tooltip();';
            echo '});';
            echo '</script>';
            
        } else {
            echo '<div class="alert alert-warning">';
            echo '<i class="fa fa-exclamation-triangle"></i> ';
            echo 'No active subjects found for this class-section combination. ';
            echo 'Please make sure subjects are assigned to this class-section in the Subject Allocation section.';
            echo '</div>';
        }
        
        $stmt->close();
        
    } catch (Exception $e) {
        echo '<div class="alert alert-danger">';
        echo '<i class="fa fa-exclamation-circle"></i> ';
        echo 'Database Error: ' . htmlspecialchars($e->getMessage());
        echo '</div>';
    }
    
} else {
    echo '<div class="alert alert-danger">';
    echo '<i class="fa fa-times-circle"></i> ';
    echo 'Invalid request. Please select all required fields.';
    echo '</div>';
}
?>