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

$response = array('status' => 'error', 'message' => 'Unknown error');

if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $exam_id = intval($_POST['exam_id']);
    $subject_id = intval($_POST['subject_id']);
    $class_id = intval($_POST['class_id']);
    $section_id = intval($_POST['section_id']);
    $marks_data = json_decode($_POST['marks'], true);
    
    if(empty($marks_data)) {
        $response['message'] = 'No marks data received';
        echo json_encode($response);
        exit;
    }
    
    $conn->begin_transaction();
    
    try {
        foreach($marks_data as $mark) {
            $student_id = intval($mark['student_id']);
            $theory = floatval($mark['theory']);
            $practical = floatval($mark['practical']);
            $internal = floatval($mark['internal']);
            $total = floatval($mark['total']);
            $remark = $conn->real_escape_string($mark['remark']);
            
            // Check if marks already exist
            $check_query = "SELECT id FROM student_marks 
                           WHERE student_id = ? 
                           AND exam_id = ? 
                           AND subject_id = ? 
                           AND class_id = ? 
                           AND section_id = ?";
            
            $stmt = $conn->prepare($check_query);
            $stmt->bind_param("iiiii", $student_id, $exam_id, $subject_id, $class_id, $section_id);
            $stmt->execute();
            $check_result = $stmt->get_result();
            
            if($check_result->num_rows > 0) {
                // Update existing marks
                $update_query = "UPDATE student_marks SET 
                                theory_marks = ?, 
                                practical_marks = ?, 
                                internal_marks = ?, 
                                total_marks = ?, 
                                remarks = ?, 
                                updated_at = NOW() 
                                WHERE student_id = ? 
                                AND exam_id = ? 
                                AND subject_id = ? 
                                AND class_id = ? 
                                AND section_id = ?";
                
                $update_stmt = $conn->prepare($update_query);
                $update_stmt->bind_param("ddddsiiiii", $theory, $practical, $internal, $total, $remark, 
                                        $student_id, $exam_id, $subject_id, $class_id, $section_id);
                $update_stmt->execute();
                $update_stmt->close();
            } else {
                // Insert new marks
                $insert_query = "INSERT INTO student_marks 
                                (student_id, exam_id, subject_id, class_id, section_id, 
                                theory_marks, practical_marks, internal_marks, total_marks, 
                                remarks, created_at, updated_at) 
                                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())";
                
                $insert_stmt = $conn->prepare($insert_query);
                $insert_stmt->bind_param("iiiiidddds", $student_id, $exam_id, $subject_id, $class_id, $section_id,
                                       $theory, $practical, $internal, $total, $remark);
                $insert_stmt->execute();
                $insert_stmt->close();
            }
            
            $stmt->close();
        }
        
        $conn->commit();
        $response['status'] = 'success';
        $response['message'] = 'Marks saved successfully for ' . count($marks_data) . ' students';
        
    } catch(Exception $e) {
        $conn->rollback();
        $response['message'] = 'Error saving marks: ' . $e->getMessage();
    }
} else {
    $response['message'] = 'Invalid request method';
}

echo json_encode($response);
?>