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

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

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

try {
    $sql = "SELECT competency_id, competency_name FROM competencies WHERE topic_id = ? AND school_id = ? ORDER BY competency_name";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ii", $topic_id, $school_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $competencies = [];
    while ($row = $result->fetch_assoc()) {
        $competencies[] = $row;
    }
    
    echo json_encode(['success' => true, 'competencies' => $competencies]);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>