<?php
// process_marksentry.php
include("includes/db.php");

// Start session for any user messages (if needed)
session_start();

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Log the incoming data for debugging
error_log("Marks Entry Submission Received");
error_log("POST Data: " . print_r($_POST, true));

// Get POST data with validation
$class_id = isset($_POST['class_id']) ? intval($_POST['class_id']) : 0;
$section_id = isset($_POST['section_id']) ? intval($_POST['section_id']) : 0;
$exam_id = isset($_POST['exam_id']) ? intval($_POST['exam_id']) : 0;  // This is exam_type in marks table
$subject_id = isset($_POST['subject_id']) ? intval($_POST['subject_id']) : 0;
$mark_type = isset($_POST['mark_type']) ? trim($_POST['mark_type']) : '';
$teacher_id = isset($_POST['teacher_id']) ? intval($_POST['teacher_id']) : 0;
$full_marks = isset($_POST['full_marks']) ? floatval($_POST['full_marks']) : 100;
$academic_year_id = isset($_POST['academic_year_id']) ? intval($_POST['academic_year_id']) : 1;
$marks = isset($_POST['marks']) ? $_POST['marks'] : array();
$remarks = isset($_POST['remarks']) ? $_POST['remarks'] : array();

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

// 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();

// Get exam name for logging
$exam_query = "SELECT exam_type FROM examination_type WHERE id = ?";
$exam_stmt = $conn->prepare($exam_query);
$exam_stmt->bind_param("i", $exam_id);
$exam_stmt->execute();
$exam_result = $exam_stmt->get_result();
$exam_row = $exam_result->fetch_assoc();
$exam_name = $exam_row['exam_type'] ?? 'Unknown Exam';
$exam_stmt->close();

// Validate required fields
$errors = array();
if (!$class_id) $errors[] = "Class is required";
if (!$section_id) $errors[] = "Section 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 validation errors exist, return them
if (!empty($errors)) {
    $error_message = "Error: " . implode(", ", $errors);
    error_log($error_message);
    echo $error_message;
    exit;
}

// Get current timestamp
$current_time = date('Y-m-d H:i:s');

// Initialize counters
$insert_count = 0;
$update_count = 0;
$skipped_count = 0;
$error_count = 0;

// Start transaction for data consistency
$conn->begin_transaction();

try {
    // Process each student's marks
    foreach ($marks as $student_id => $mark_value) {
        $student_id = intval($student_id);
        $mark_value = trim($mark_value);
        
        // Skip if mark is empty
        if ($mark_value === '') {
            $skipped_count++;
            continue;
        }
        
        // Validate mark value
        if (!is_numeric($mark_value)) {
            error_log("Invalid marks for student $student_id: $mark_value");
            $error_count++;
            continue;
        }
        
        $mark_value = floatval($mark_value);
        
        // Validate mark range
        if ($mark_value < 0 || $mark_value > $full_marks) {
            error_log("Marks out of range for student $student_id: $mark_value (Max: $full_marks)");
            $error_count++;
            continue;
        }
        
        // Prepare remark
        $remark = isset($remarks[$student_id]) ? trim($remarks[$student_id]) : '';
        $remark = $conn->real_escape_string($remark);
        
        // Check if marks already exist in your marks table - FIXED: using exam_id as int
        $check_query = "SELECT id, marks, full_marks FROM marks 
                       WHERE student_id = ? 
                       AND class_id = ? 
                       AND section_id = ? 
                       AND subject_id = ? 
                       AND exam_type = ?  -- This is exam_id (int) from examination_type
                       AND academic_year_id = ?
                       AND mark_type = ?";
        
        $check_stmt = $conn->prepare($check_query);
        $check_stmt->bind_param("iiiiiis", $student_id, $class_id, $section_id, $subject_id, $exam_id, $academic_year_id, $mark_type);
        $check_stmt->execute();
        $check_result = $check_stmt->get_result();
        $check_stmt->close();
        
        if ($check_result->num_rows > 0) {
            // Update existing marks
            $existing = $check_result->fetch_assoc();
            $existing_id = $existing['id'];
            $existing_marks = $existing['marks'];
            $existing_full_marks = $existing['full_marks'];
            
            // Check if there's actually a change
            if ($existing_marks != $mark_value || $existing_full_marks != $full_marks) {
                $update_query = "UPDATE marks 
                                SET marks = ?, 
                                    full_marks = ?,
                                    entered_by = ?,
                                    updated_by = ?,
                                    updated_at = ?
                                WHERE id = ?";
                
                $update_stmt = $conn->prepare($update_query);
                $update_stmt->bind_param("ddiisi", $mark_value, $full_marks, $teacher_id, $teacher_id, $current_time, $existing_id);
                
                if ($update_stmt->execute()) {
                    $update_count++;
                    error_log("Updated marks for student $student_id: $mark_value/$full_marks by $teacher_name");
                } else {
                    $error_count++;
                    error_log("Update failed for student $student_id: " . $update_stmt->error);
                }
                $update_stmt->close();
            } else {
                $skipped_count++; // No change, skip
            }
        } else {
            // Insert new marks - FIXED: using exam_id for exam_type field
            $insert_query = "INSERT INTO marks 
                            (student_id, class_id, section_id, subject_id, exam_type, 
                             full_marks, marks, entered_by, updated_by, academic_year_id, 
                             mark_type, created_at, updated_at) 
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            
            $insert_stmt = $conn->prepare($insert_query);
            $insert_stmt->bind_param("iiiiiddiiisss", 
                $student_id, $class_id, $section_id, $subject_id, $exam_id,  // exam_id goes to exam_type field
                $full_marks, $mark_value, $teacher_id, $teacher_id, $academic_year_id,
                $mark_type, $current_time, $current_time);
            
            if ($insert_stmt->execute()) {
                $insert_count++;
                error_log("Inserted marks for student $student_id: $mark_value/$full_marks by $teacher_name (Exam: $exam_name, Type: $mark_type)");
            } else {
                $error_count++;
                error_log("Insert failed for student $student_id: " . $insert_stmt->error);
                
                // Check for duplicate entry error
                if (strpos($insert_stmt->error, "Duplicate entry") !== false) {
                    error_log("Duplicate entry detected for student $student_id, trying update instead");
                    
                    // Try to update instead
                    $update_query = "UPDATE marks 
                                    SET marks = ?, 
                                        full_marks = ?,
                                        entered_by = ?,
                                        updated_by = ?,
                                        updated_at = ?
                                    WHERE student_id = ? 
                                    AND class_id = ? 
                                    AND section_id = ? 
                                    AND subject_id = ? 
                                    AND exam_type = ? 
                                    AND academic_year_id = ?
                                    AND mark_type = ?";
                    
                    $update_stmt = $conn->prepare($update_query);
                    $update_stmt->bind_param("ddiiiiiiiis", 
                        $mark_value, $full_marks, $teacher_id, $teacher_id, $current_time,
                        $student_id, $class_id, $section_id, $subject_id, $exam_id, $academic_year_id, $mark_type);
                    
                    if ($update_stmt->execute()) {
                        $update_count++;
                        error_log("Updated marks after duplicate detection for student $student_id");
                    } else {
                        error_log("Update also failed for student $student_id: " . $update_stmt->error);
                    }
                    $update_stmt->close();
                }
            }
            $insert_stmt->close();
        }
    }
    
    // Commit transaction
    $conn->commit();
    
    // Prepare success message
    $message_parts = array();
    if ($insert_count > 0) {
        $message_parts[] = "$insert_count new marks inserted";
    }
    if ($update_count > 0) {
        $message_parts[] = "$update_count marks updated";
    }
    if ($skipped_count > 0) {
        $message_parts[] = "$skipped_count unchanged entries skipped";
    }
    if ($error_count > 0) {
        $message_parts[] = "$error_count errors occurred";
    }
    
    $message = "Marks submitted successfully! " . implode(", ", $message_parts) . ".";
    
    // Add teacher and exam info
    $message .= " (Teacher: $teacher_name, Exam: $exam_name, Type: $mark_type)";
    
    // Log success
    error_log("Marks entry successful: " . $message);
    
    // Return success message
    echo $message;
    
} catch (Exception $e) {
    // Rollback transaction on error
    $conn->rollback();
    
    // Log error
    error_log("Transaction failed: " . $e->getMessage());
    error_log("Error trace: " . $e->getTraceAsString());
    
    // Return error message
    echo "Error: Transaction failed. " . $e->getMessage();
    
    // Send HTTP error code
    http_response_code(500);
}

// Close database connection
$conn->close();
?>