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

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

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

try {
    $sql = "SELECT 
                ia.activity_id,
                ia.title,
                ia.description,
                ia.due_date,
                ia.status,
                ia.stream_id,
                ia.subject_id,
                c.class_name,
                cs.stream_name,
                s.subject_name,
                t.topic_name
            FROM integration_activities ia
            INNER JOIN streams cs ON ia.stream_id = cs.stream_id
            INNER JOIN classes c ON cs.class_id = c.class_id
            INNER JOIN subjects s ON ia.subject_id = s.subject_id
            INNER JOIN topics t ON ia.topic_id = t.topic_id
            WHERE ia.school_id = ? AND ia.teacher_user_id = ?
            ORDER BY ia.created_at DESC";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ii", $school_id, $teacher_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $activities = [];
    while ($row = $result->fetch_assoc()) {
        $activities[] = $row;
    }
    
    echo json_encode(['success' => true, 'activities' => $activities]);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>