<?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;
$stream_id = $_POST['stream_id'] ?? 0;
$subject_id = $_POST['subject_id'] ?? 0;
$topic_id = $_POST['topic_id'] ?? 0;
$competency_id = $_POST['competency_id'] ?? 0;
$title = trim($_POST['title'] ?? '');
$description = trim($_POST['description'] ?? '');
$due_date = $_POST['due_date'] ?? '';

if ($school_id == 0 || $teacher_id == 0 || $stream_id == 0 || $subject_id == 0 || $topic_id == 0 || $competency_id == 0 || $title == '' || $due_date == '') {
    echo json_encode(['success' => false, 'message' => 'All required fields must be filled']);
    exit;
}

// Get current academic year and term
$sql_term = "SELECT academic_year, term_name FROM academic_years_terms WHERE school_id = ? AND is_current_term = 1 LIMIT 1";
$stmt_term = $conn->prepare($sql_term);
$stmt_term->bind_param("i", $school_id);
$stmt_term->execute();
$result_term = $stmt_term->get_result();
$term_data = $result_term->fetch_assoc();

$academic_year = $term_data['academic_year'] ?? date('Y');
$term = $term_data['term_name'] ?? 'TERM 1';

try {
    $sql = "INSERT INTO integration_activities 
            (school_id, teacher_user_id, subject_id, stream_id, topic_id, competency_id, academic_year, term, title, description, due_date, status) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'Draft')";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("iiiiiiissss", $school_id, $teacher_id, $subject_id, $stream_id, $topic_id, $competency_id, $academic_year, $term, $title, $description, $due_date);
    
    if ($stmt->execute()) {
        echo json_encode(['success' => true, 'message' => 'Integration activity created successfully!']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error creating activity']);
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>