<?php
session_start();
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

include "../include/config.php";

// Check login and instructor role
if (!isset($_SESSION['email'])) {
    header("location:../index.php");
    exit();
}

if (isset($_POST['submit_work'])) {
    $submission_id = $_POST['submission_id'] ?? '';
    $marks = $_POST['marks'] ?? '';
    $feedback = $_POST['feedback'] ?? '';
    $instructor_email = $_SESSION['email'];
    
    if (!empty($submission_id) && !empty($marks)) {
        // Start transaction
        $conn->begin_transaction();
        
        try {
            // 1. Get submission details
            $stmt = $conn->prepare("SELECT s.student_id, s.assignment_id, a.course, a.period as term, a.year, a.intake, a.program
                                    FROM submit s
                                    JOIN assignments a ON s.assignment_id = a.id
                                    WHERE s.id = ? AND a.email = ?");
            $stmt->bind_param("is", $submission_id, $instructor_email);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($result->num_rows > 0) {
                $submission = $result->fetch_assoc();
                $student_id = $submission['student_id'];
                $course = $submission['course'];
                $term = $submission['term'];
                $year = $submission['year'];
                $intake = $submission['intake'];
                $program = $submission['program'];
                
                // 2. Update the submission with marks and feedback
                $update_stmt = $conn->prepare("UPDATE submit SET marks = ?, feedback = ?, graded_at = NOW() WHERE id = ?");
                $update_stmt->bind_param("ssi", $marks, $feedback, $submission_id);
                $update_stmt->execute();
                $update_stmt->close();
                
                // 3. Check if result already exists
                $check_stmt = $conn->prepare("SELECT id, ca, ca1, ca2 FROM results 
                                              WHERE studentid = ? 
                                              AND course = ? 
                                              AND term = ? 
                                              AND year = ? 
                                              AND intake = ?");
                $check_stmt->bind_param("sssss", $student_id, $course, $term, $year, $intake);
                $check_stmt->execute();
                $check_result = $check_stmt->get_result();
                
                if ($check_result->num_rows > 0) {
                    // Update existing result
                    $existing = $check_result->fetch_assoc();
                    
                    // Determine which CA field to update based on existing values
                    if (empty($existing['ca']) || $existing['ca'] == 0) {
                        $update_field = 'ca';
                        $update_value = $marks;
                    } elseif (empty($existing['ca1']) || $existing['ca1'] == 0) {
                        $update_field = 'ca1';
                        $update_value = $marks;
                    } elseif (empty($existing['ca2']) || $existing['ca2'] == 0) {
                        $update_field = 'ca2';
                        $update_value = $marks;
                    } else {
                        // All CA fields have values, update CA (first one)
                        $update_field = 'ca';
                        $update_value = $marks;
                    }
                    
                    $update_result = $conn->prepare("UPDATE results SET $update_field = ?, email = ? WHERE id = ?");
                    $update_result->bind_param("ssi", $update_value, $instructor_email, $existing['id']);
                    $update_result->execute();
                    $update_result->close();
                } else {
                    // Insert new result
                    $insert_result = $conn->prepare("INSERT INTO results (studentid, course, term, year, intake, ca, ca1, ca2, exam, email) 
                                                    VALUES (?, ?, ?, ?, ?, ?, 0, 0, 0, ?)");
                    $insert_result->bind_param("sssssss", $student_id, $course, $term, $year, $intake, $marks, $instructor_email);
                    $insert_result->execute();
                    $insert_result->close();
                }
                
                $check_stmt->close();
            }
            
            $stmt->close();
            
            // Commit transaction
            $conn->commit();
            
            $_SESSION['success'] = "Grade saved successfully and updated in results!";
            header("Location: assignment.php#submissions");
            exit();
            
        } catch (Exception $e) {
            // Rollback transaction on error
            $conn->rollback();
            $_SESSION['error'] = "Error: " . $e->getMessage();
            header("Location: post_assignment.php#submissions");
            exit();
        }
    } else {
        $_SESSION['error'] = "Please provide all required information";
        header("Location: post_assignment.php#submissions");
        exit();
    }
}

// If not POST request, redirect back
header("Location: post_assignment.php");
exit();
?>