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

// Set JSON header for AJAX response
header('Content-Type: application/json');

// Get POST data
$class_id = isset($_POST['class_id']) ? intval($_POST['class_id']) : 0;
$section_ids = isset($_POST['section_ids']) ? $_POST['section_ids'] : [];
$subject_id = intval($_POST['subject_id'] ?? 0);
$mark_type = isset($_POST['mark_type']) ? trim($_POST['mark_type']) : '';
$marks = isset($_POST['marks']) ? $_POST['marks'] : [];
$remarks = isset($_POST['remarks']) ? $_POST['remarks'] : [];
$teacher_id = isset($_POST['teacher_id']) ? intval($_POST['teacher_id']) : 0;
$exam_id = intval($_POST['exam_id'] ?? 0);
$full_marks = floatval($_POST['full_marks'] ?? 0);

// Log the request for debugging
error_log("Marks submission - Class: $class_id, Exam: $exam_id, Subject: $subject_id, Type: $mark_type, Teacher: $teacher_id");

// Get academic year
$ay_query = "SELECT year_id FROM academic_years WHERE status = 'active' LIMIT 1";
$ay_result = $conn->query($ay_query);
$academic_year = $ay_result->fetch_assoc();
$academic_year_id = $academic_year['year_id'] ?? 1;

// Get teacher name for logging
$teacher_query = "SELECT name FROM teachers WHERE teacher_id = ?";
$teacher_stmt = $conn->prepare($teacher_query);
$teacher_stmt->bind_param("i", $teacher_id);
$teacher_stmt->execute();
$teacher_result = $teacher_stmt->get_result();
$teacher = $teacher_result->fetch_assoc();
$teacher_name = $teacher['name'] ?? 'Unknown';
$teacher_stmt->close();

// Validate required fields
$errors = array();
if (!$class_id) $errors[] = "Class is required";
if (!$exam_id) $errors[] = "Exam is required";
if (!$subject_id) $errors[] = "Subject is required";
if (empty($mark_type)) $errors[] = "Marks type is required";
if (!$teacher_id) $errors[] = "Teacher is required";
if (empty($marks)) $errors[] = "No marks entered";

if (!empty($errors)) {
    echo json_encode(['success' => false, 'message' => implode(', ', $errors)]);
    exit;
}

// Validate mark_type (must be 'theory' or 'practical' based on your table enum)
if (!in_array($mark_type, ['theory', 'practical'])) {
    if (in_array($mark_type, ['internal', 'assignment', 'project', 'oral'])) {
        $mark_type = 'practical';
    } else {
        $mark_type = 'theory';
    }
}

// Get subject full marks if not provided
if ($full_marks == 0) {
    $subject_query = "SELECT theory_full_marks, internal_full_marks FROM subjects WHERE id = ?";
    $subject_stmt = $conn->prepare($subject_query);
    $subject_stmt->bind_param("i", $subject_id);
    $subject_stmt->execute();
    $subject_result = $subject_stmt->get_result();
    $subject_data = $subject_result->fetch_assoc();
    $subject_stmt->close();
    $full_marks = ($mark_type == 'theory') ? ($subject_data['theory_full_marks'] ?? 100) : ($subject_data['internal_full_marks'] ?? 50);
}

// Initialize counters
$insert_count = 0;
$update_count = 0;
$skip_count = 0;
$duplicate_count = 0;
$error_count = 0;
$error_messages = [];

// Process each student's marks
foreach ($marks as $student_id => $mark) {
    $student_id = intval($student_id);
    $mark = trim($mark);
    
    // Skip empty marks
    if ($mark === '') {
        $skip_count++;
        continue;
    }
    
    // Validate mark
    if (!is_numeric($mark)) {
        $error_count++;
        $error_messages[] = "Invalid mark for student ID $student_id";
        continue;
    }
    
    $mark = floatval($mark);
    
    if ($mark < 0 || $mark > $full_marks) {
        $error_count++;
        $error_messages[] = "Mark out of range for student ID $student_id ($mark/$full_marks)";
        continue;
    }
    
    $remark = isset($remarks[$student_id]) ? trim($remarks[$student_id]) : '';
    
    // Get section_id for this student - but note: marks table might have NULL section_id
    $section_query = "SELECT section_id FROM student_class_section_data WHERE student_id = ? AND class_id = ? AND status = 'active' LIMIT 1";
    $section_stmt = $conn->prepare($section_query);
    $section_stmt->bind_param("ii", $student_id, $class_id);
    $section_stmt->execute();
    $section_result = $section_stmt->get_result();
    $section_row = $section_result->fetch_assoc();
    $section_id_val = $section_row['section_id'] ?? null; // Allow NULL
    $section_stmt->close();
    
    // Important: For marks table, section_id can be NULL, so we need to handle NULL in the check
    // The unique key might be: student_id, class_id, subject_id, exam_type, mark_type (without section_id)
    // Based on your unique key: 'unique_marks_entry' (`student_id`,`class_id`,`subject_id`,`exam_type`,`mark_type`)
    // So we should NOT include section_id in the check!
    
    // Check if record exists using the actual unique key fields (without section_id)
    $check_query = "SELECT id, marks, full_marks FROM marks 
                    WHERE student_id = ? 
                    AND class_id = ? 
                    AND subject_id = ? 
                    AND exam_type = ? 
                    AND academic_year_id = ? 
                    AND mark_type = ?";
    $check_stmt = $conn->prepare($check_query);
    $check_stmt->bind_param("iiiiis", $student_id, $class_id, $subject_id, $exam_id, $academic_year_id, $mark_type);
    $check_stmt->execute();
    $check_result = $check_stmt->get_result();
    
    if ($check_result->num_rows > 0) {
        // Record exists - check if update needed
        $existing = $check_result->fetch_assoc();
        
        // Check if marks are different
        if ($existing['marks'] != $mark || $existing['full_marks'] != $full_marks) {
            // Update existing record
            $update_query = "UPDATE marks SET marks = ?, full_marks = ?, remarks = ?, updated_by = ?, updated_at = NOW() 
                            WHERE id = ?";
            $update_stmt = $conn->prepare($update_query);
            $update_stmt->bind_param("ddsii", $mark, $full_marks, $remark, $teacher_id, $existing['id']);
            if ($update_stmt->execute()) {
                $update_count++;
                error_log("Updated marks for student $student_id: $mark/$full_marks by teacher $teacher_id");
            } else {
                $error_count++;
                $error_messages[] = "Failed to update student ID $student_id: " . $update_stmt->error;
            }
            $update_stmt->close();
        } else {
            // No change needed - skip
            $skip_count++;
            error_log("Skipped (no change) for student $student_id: $mark/$full_marks");
        }
    } else {
        // No existing record - safe to insert
        $insert_query = "INSERT INTO marks (student_id, class_id, section_id, subject_id, 
                         exam_type, academic_year_id, mark_type, full_marks, marks, remarks, entered_by, created_at) 
                         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, date('Y-m-d H:i:s'))";
        $insert_stmt = $conn->prepare($insert_query);
        
        // Handle NULL section_id properly
        if ($section_id_val === null) {
            $insert_stmt->bind_param("iiiiiissdsi", $student_id, $class_id, $section_id_val, $subject_id,
                                      $exam_id, $academic_year_id, $mark_type, $full_marks, $mark, $remark, $teacher_id);
        } else {
            $insert_stmt->bind_param("iiiiiissdsi", $student_id, $class_id, $section_id_val, $subject_id,
                                      $exam_id, $academic_year_id, $mark_type, $full_marks, $mark, $remark, $teacher_id);
        }
        
        if ($insert_stmt->execute()) {
            $insert_count++;
            error_log("Inserted marks for student $student_id: $mark/$full_marks by teacher $teacher_id (Type: $mark_type)");
        } else {
            // Check for duplicate entry error
            if (strpos($insert_stmt->error, 'Duplicate entry') !== false) {
                $duplicate_count++;
                error_log("Duplicate entry detected for student $student_id - skipping");
                
                // Try to update instead of insert
                $update_query = "UPDATE marks SET marks = ?, full_marks = ?, remarks = ?, updated_by = ?, updated_at = date('Y-m-d H:i:s') 
                                WHERE student_id = ? AND class_id = ? AND subject_id = ? 
                                AND exam_type = ? AND academic_year_id = ? AND mark_type = ?";
                $update_stmt = $conn->prepare($update_query);
                $update_stmt->bind_param("ddsiiiiiiis", 
                    $mark, $full_marks, $remark, $teacher_id,
                    $student_id, $class_id, $subject_id, $exam_id, $academic_year_id, $mark_type);
                
                if ($update_stmt->execute()) {
                    $update_count++;
                    error_log("Updated marks (duplicate) for student $student_id: $mark/$full_marks");
                } else {
                    $error_count++;
                    $error_messages[] = "Duplicate entry for student ID $student_id - marks already exist";
                    error_log("Failed to update duplicate for student $student_id: " . $update_stmt->error);
                }
                $update_stmt->close();
            } else {
                $error_count++;
                $error_messages[] = "Failed to insert for student ID $student_id: " . $insert_stmt->error;
                error_log("Insert failed for student $student_id: " . $insert_stmt->error);
            }
        }
        $insert_stmt->close();
    }
    $check_stmt->close();
}

// Prepare response message
$message_parts = [];

if ($insert_count > 0) {
    $message_parts[] = "$insert_count new marks inserted";
}
if ($update_count > 0) {
    $message_parts[] = "$update_count marks updated";
}
if ($skip_count > 0) {
    $message_parts[] = "$skip_count unchanged entries skipped";
}
if ($duplicate_count > 0) {
    $message_parts[] = "$duplicate_count duplicate entries skipped";
}
if ($error_count > 0) {
    $message_parts[] = "$error_count errors occurred";
}

$success = ($insert_count > 0 || $update_count > 0);

// Determine the appropriate icon and title for the response
$response_icon = '';
$response_title = '';

if ($insert_count > 0 || $update_count > 0) {
    $response_icon = 'success';
    $response_title = 'Success!';
} elseif ($duplicate_count > 0 && $insert_count == 0 && $update_count == 0) {
    $response_icon = 'info';
    $response_title = 'No Changes';
    $message_parts = ["All entries were duplicates. No new marks saved."];
} elseif ($skip_count > 0 && $insert_count == 0 && $update_count == 0) {
    $response_icon = 'info';
    $response_title = 'No Changes';
    $message_parts = ["No changes detected. All entries were already up to date."];
} else {
    $response_icon = 'warning';
    $response_title = 'Partial Success';
    if (empty($message_parts)) {
        $message_parts = ["No marks were saved. Please check your entries."];
    }
}

$response = [
    'success' => $success,
    'title' => $response_title,
    'icon' => $response_icon,
    'message' => implode(', ', $message_parts),
    'details' => [
        'inserted' => $insert_count,
        'updated' => $update_count,
        'skipped' => $skip_count,
        'duplicates' => $duplicate_count,
        'errors' => $error_count
    ]
];

if (!empty($error_messages)) {
    $response['error_details'] = $error_messages;
}

// Log the response
error_log("Marks save response: " . json_encode($response));

// Return JSON response
echo json_encode($response);

$conn->close();
?>