<?php
declare(strict_types=1);
session_start();
require_once '../../config.php';
require_once '../helpers.php';
header('Content-Type: application/json');
if (!isset($_SESSION['parent_id'])) { http_response_code(401); echo json_encode(['success'=>false]); exit; }
portalCsrfVerify();
$conn = getDBConnection();
if (!$conn instanceof mysqli) { echo json_encode(['success'=>false, 'message'=>'Database connection failed']); exit; }
$parentId = (int) $_SESSION['parent_id'];
$subject = trim((string) ($_POST['subject'] ?? ''));
$message = trim((string) ($_POST['message'] ?? ''));
if ($subject === '' || $message === '') { echo json_encode(['success'=>false, 'message'=>'Subject and message are required']); exit; }
$stmt = $conn->prepare("INSERT INTO parent_messages (parent_id, sender, subject, message) VALUES (?, 'parent', ?, ?)");
$stmt->bind_param('iss', $parentId, $subject, $message);
$stmt->execute();
$stmt->close();
$_actCheck = $conn->query("SHOW TABLES LIKE 'user_activities'");
if ($_actCheck && $_actCheck->num_rows > 0) {
    $activity = $conn->prepare("INSERT INTO user_activities (user_id, activity) VALUES (?, ?)");
    $adminId = (int) ($_SESSION['user_id'] ?? 0);
    $activityText = 'Parent message received: ' . $subject;
    $activity->bind_param('is', $adminId, $activityText);
    $activity->execute();
    $activity->close();
}
echo json_encode(['success'=>true, 'message'=>'Message sent successfully']);
