<?php
declare(strict_types=1);
session_start();
require_once '../config.php';
header('Content-Type: application/json');
if (!isset($_SESSION['user_id'])) { http_response_code(401); echo json_encode([]); exit; }
$conn = getDBConnection();
if (!$conn instanceof mysqli) { echo json_encode([]); exit; }
$sql = "SELECT pa.*, GROUP_CONCAT(CONCAT(s.first_name, ' ', s.last_name) SEPARATOR ', ') AS children
        FROM parent_accounts pa
        LEFT JOIN parent_student_link psl ON psl.parent_id = pa.id
        LEFT JOIN students s ON s.id = psl.student_id
        GROUP BY pa.id
        ORDER BY pa.created_at DESC";
$result = $conn->query($sql);
$rows = [];
while ($result && $row = $result->fetch_assoc()) { $rows[] = $row; }
echo json_encode($rows);
