<?php
//filename: ajax/update_student_subjects.php
include('../includes/db.php');

$response = ['status' => 'error', 'message' => 'Invalid request'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $student_id = (int)$_POST['student_id'];
    $class_id = (int)$_POST['class_id'];
    $academic_year = $conn->real_escape_string($_POST['academic_year']);
    
    // Get student's section for this class and year
    $sectionQuery = "SELECT section_id FROM student_class_section_data 
                    WHERE student_id = $student_id 
                    AND class_id = $class_id 
                    AND academic_year = '$academic_year' 
                    AND status = 'active' 
                    LIMIT 1";
    
    $sectionResult = $conn->query($sectionQuery);
    
    if ($sectionResult->num_rows > 0) {
        $sectionRow = $sectionResult->fetch_assoc();
        $section_id = $sectionRow['section_id'];
        
        // First, get current subjects to preserve unchanged ones
        $current_subjects = array_fill(0, 7, '');
        $check_sql = "SELECT sub1, sub2, sub3, sub4, sub5, sub6, sub7 FROM studentsub 
                      WHERE student_id = $student_id 
                      AND class_id = $class_id 
                      AND section_id = $section_id 
                      AND academic_year = '$academic_year'";
        
        $check_result = $conn->query($check_sql);
        
        if ($check_result->num_rows > 0) {
            $row = $check_result->fetch_assoc();
            $current_subjects = [
                $row['sub1'], $row['sub2'], $row['sub3'], 
                $row['sub4'], $row['sub5'], $row['sub6'], $row['sub7']
            ];
        }
        
        // Process all subjects from the form (including unchanged ones)
        $subject_array = array_fill(0, 7, '');
        
        // Get all subject values from form data
        for ($i = 1; $i <= 7; $i++) {
            $field_name = 'sub' . $i;
            if (isset($_POST[$field_name])) {
                $subject_array[$i-1] = $conn->real_escape_string($_POST[$field_name]);
            }
        }
        
        // Also process changed subjects from AJAX (for backward compatibility)
        if (isset($_POST['subjects']) && is_array($_POST['subjects'])) {
            foreach ($_POST['subjects'] as $subject) {
                if (isset($subject['subject_id']) && isset($subject['new_code'])) {
                    $subject_id = str_replace('sub', '', $subject['subject_id']);
                    $index = (int)$subject_id - 1;
                    
                    if ($index >= 0 && $index < 7) {
                        $subject_array[$index] = $conn->real_escape_string($subject['new_code']);
                    }
                }
            }
        }
        
        // Check if record exists
        if ($check_result->num_rows > 0) {
            // Update existing record
            $update_sql = "UPDATE studentsub SET 
                           sub1 = '{$subject_array[0]}',
                           sub2 = '{$subject_array[1]}',
                           sub3 = '{$subject_array[2]}',
                           sub4 = '{$subject_array[3]}',
                           sub5 = '{$subject_array[4]}',
                           sub6 = '{$subject_array[5]}',
                           sub7 = '{$subject_array[6]}',
                           updated_at = NOW()
                           WHERE student_id = $student_id 
                           AND class_id = $class_id 
                           AND section_id = $section_id 
                           AND academic_year = '$academic_year'";
            
            if ($conn->query($update_sql)) {
                $response['status'] = 'success';
                $response['message'] = 'Subjects updated successfully!';
            } else {
                $response['message'] = 'Failed to update subjects: ' . $conn->error;
            }
        } else {
            // Insert new record
            $insert_sql = "INSERT INTO studentsub 
                           (student_id, class_id, section_id, sub1, sub2, sub3, sub4, sub5, sub6, sub7, academic_year, created_at, updated_at) 
                           VALUES ($student_id, $class_id, $section_id, 
                           '{$subject_array[0]}', '{$subject_array[1]}', '{$subject_array[2]}', 
                           '{$subject_array[3]}', '{$subject_array[4]}', '{$subject_array[5]}', 
                           '{$subject_array[6]}', '$academic_year', NOW(), NOW())";
            
            if ($conn->query($insert_sql)) {
                $response['status'] = 'success';
                $response['message'] = 'Subjects assigned successfully!';
            } else {
                $response['message'] = 'Failed to assign subjects: ' . $conn->error;
            }
        }
    } else {
        $response['message'] = 'Student is not assigned to any section for this class and academic year.';
    }
}

echo json_encode($response);
?>