<?php
session_start();
require_once 'config.php';

header('Content-Type: application/json');

if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$activity_id = $_POST['activity_id'] ?? 0;
$subject_id = $_POST['subject_id'] ?? 0;
$stream_id = $_POST['stream_id'] ?? 0;
$school_id = $_POST['school_id'] ?? 0;
$marks_json = $_POST['marks'] ?? '';

if ($activity_id == 0 || $subject_id == 0 || $stream_id == 0 || $school_id == 0 || $marks_json == '') {
    echo json_encode(['success' => false, 'message' => 'Invalid parameters']);
    exit;
}

$marks = json_decode($marks_json, true);

if (!is_array($marks) || count($marks) == 0) {
    echo json_encode(['success' => false, 'message' => 'No marks to save']);
    exit;
}

// Get academic year and term from the activity
$sql_activity = "SELECT academic_year, term FROM integration_activities WHERE activity_id = ?";
$stmt_activity = $conn->prepare($sql_activity);
$stmt_activity->bind_param("i", $activity_id);
$stmt_activity->execute();
$result_activity = $stmt_activity->get_result();
$activity_data = $result_activity->fetch_assoc();

$academic_year = $activity_data['academic_year'] ?? date('Y');
$term = $activity_data['term'] ?? 'TERM 1';
$teacher_id = $_SESSION['id'];

try {
    // First check if the activity is published (locked)
    $check_sql = "SELECT status FROM integration_activities WHERE activity_id = ?";
    $check_stmt = $conn->prepare($check_sql);
    $check_stmt->bind_param("i", $activity_id);
    $check_stmt->execute();
    $check_result = $check_stmt->get_result();
    $activity = $check_result->fetch_assoc();
    
    if ($activity['status'] === 'Published') {
        echo json_encode(['success' => false, 'message' => 'Cannot edit marks. This activity has been published and is locked.']);
        exit;
    }
    
    $conn->begin_transaction();
    
    // Prepare insert/update statement
    $sql = "INSERT INTO integration_activity_marks 
            (activity_id, subject_id, student_id, stream_id, marks, academic_year, term, school_id) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE marks = VALUES(marks), updated_at = CURRENT_TIMESTAMP";
    
    $stmt = $conn->prepare($sql);
    
    foreach ($marks as $mark_data) {
        $student_id = $mark_data['student_id'];
        $mark = $mark_data['mark'];
        
        $stmt->bind_param("iiiidssi", $activity_id, $subject_id, $student_id, $stream_id, $mark, $academic_year, $term, $school_id);
        $stmt->execute();
    }
    
    // Update activity status to 'Captured' after saving marks
    $update_status_sql = "UPDATE integration_activities SET status = 'Captured' WHERE activity_id = ? AND status = 'Draft'";
    $update_stmt = $conn->prepare($update_status_sql);
    $update_stmt->bind_param("i", $activity_id);
    $update_stmt->execute();
    
    $conn->commit();
    echo json_encode(['success' => true, 'message' => 'Marks saved successfully! Activity status updated to Captured.']);
    
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>