<?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(['success'=>false]); exit; }
$conn = getDBConnection();
if (!$conn instanceof mysqli) { echo json_encode(['success'=>false, 'message'=>'Database connection failed']); exit; }
$title = trim((string) ($_POST['title'] ?? ''));
$message = trim((string) ($_POST['message'] ?? ''));
$alsoSms = (int) ($_POST['also_sms'] ?? 0) === 1;
$targetType = trim((string) ($_POST['target_type'] ?? 'one'));
$parentIds = [];
if ($targetType === 'all') {
    $result = $conn->query("SELECT id, phone FROM parent_accounts WHERE is_active = 1");
    while ($result && $row = $result->fetch_assoc()) { $parentIds[] = $row; }
} elseif ($targetType === 'class') {
    $className = trim((string) ($_POST['class_name'] ?? ''));
    $stmt = $conn->prepare(
        "SELECT DISTINCT pa.id, pa.phone
         FROM parent_accounts pa
         INNER JOIN parent_student_link psl ON psl.parent_id = pa.id
         INNER JOIN students s ON s.id = psl.student_id
         WHERE s.class = ? AND pa.is_active = 1"
    );
    $stmt->bind_param('s', $className);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) { $parentIds[] = $row; }
    $stmt->close();
} else {
    $parentIds[] = ['id' => (int) ($_POST['parent_id'] ?? 0), 'phone' => (string) ($_POST['phone'] ?? '')];
}
foreach ($parentIds as $parent) {
    $stmt = $conn->prepare("INSERT INTO parent_notifications (parent_id, title, message) VALUES (?, ?, ?)");
    $stmt->bind_param('iss', $parent['id'], $title, $message);
    $stmt->execute();
    $stmt->close();
    if ($alsoSms && !empty($parent['phone'])) {
        sendSMS((string) $parent['phone'], "EduTrack: {$title} - {$message}");
    }
}
echo json_encode(['success'=>true, 'message'=>'Notification sent successfully']);
