<?php
declare(strict_types=1);
session_start();
require_once '../../config.php';
header('Content-Type: application/json');
if (!isset($_SESSION['parent_id'])) { http_response_code(401); echo json_encode([]); exit; }
$conn = getDBConnection();
if (!$conn instanceof mysqli) { echo json_encode([]); exit; }
$folder = trim((string) ($_POST['folder'] ?? 'inbox'));
$sender = $folder === 'sent' ? 'parent' : 'admin';
$parentId = (int) $_SESSION['parent_id'];
$stmt = $conn->prepare(
    "SELECT pm.*, u.full_name AS admin_name
     FROM parent_messages pm
     LEFT JOIN users u ON u.id = pm.admin_id
     WHERE pm.parent_id = ? AND pm.sender = ?
     ORDER BY pm.created_at DESC"
);
$stmt->bind_param('is', $parentId, $sender);
$stmt->execute();
$result = $stmt->get_result();
$rows = [];
while ($row = $result->fetch_assoc()) { $rows[] = $row; }
$stmt->close();
if ($folder === 'inbox') {
    $mark = $conn->prepare("UPDATE parent_messages SET is_read = 1 WHERE parent_id = ? AND sender = 'admin'");
    $mark->bind_param('i', $parentId);
    $mark->execute();
    $mark->close();
}
echo json_encode($rows);
