<?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;
}

// Check if user is admin (role = 1)
if ($_SESSION['role'] != 1) {
    echo json_encode(['success' => false, 'message' => 'Only administrators can publish activities']);
    exit;
}

$activity_id = $_POST['activity_id'] ?? 0;
$school_id = $_POST['school_id'] ?? 0;

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

try {
    // Update activity status to 'Published'
    $sql = "UPDATE integration_activities SET status = 'Published' WHERE activity_id = ? AND school_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ii", $activity_id, $school_id);
    $stmt->execute();
    
    if ($stmt->affected_rows > 0) {
        echo json_encode(['success' => true, 'message' => 'Activity published successfully. Marks entry is now locked.']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Activity not found or already published']);
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>