<?php

header('Content-Type: application/json');

error_reporting(E_ALL);

ini_set('display_errors', 0);



if (session_status() === PHP_SESSION_NONE) {

    session_start();

}



if (!isset($_SESSION['user_id'])) {

    echo json_encode(['success' => false, 'message' => 'Not authenticated']);

    exit;

}



require_once '../config.php';



$action = $_GET['action'] ?? '';

$conn = getDBConnection();



if (!$conn) {

    echo json_encode(['success' => false, 'message' => 'Database connection failed']);

    exit;

}



if ($action === 'send') {

    $alert_type     = trim((string) ($_POST['alert_type']     ?? ''));

    $recipient_type = trim((string) ($_POST['recipient_type'] ?? ''));

    $student_id     = intval($_POST['student_id'] ?? 0);

    $class_name     = trim((string) ($_POST['class_name']     ?? ''));

    $subject        = trim((string) ($_POST['subject']        ?? ''));

    $message        = trim((string) ($_POST['message']        ?? ''));



    if (empty($alert_type) || empty($recipient_type) || empty($message)) {

        echo json_encode(['success' => false, 'message' => 'Please fill all required fields']);

        exit;

    }



    // Get recipients based on type — use prepared statements throughout

    $recipients = [];



    if ($recipient_type === 'individual' && $student_id > 0) {

        $stmt = $conn->prepare("SELECT * FROM students WHERE id = ? LIMIT 1");

        $stmt->bind_param('i', $student_id);

        $stmt->execute();

        $result = $stmt->get_result();

        if ($row = $result->fetch_assoc()) $recipients[] = $row;

        $stmt->close();

    } elseif ($recipient_type === 'class' && $class_name !== '') {

        $stmt = $conn->prepare("SELECT * FROM students WHERE class = ? AND status = 'active'");

        $stmt->bind_param('s', $class_name);

        $stmt->execute();

        $result = $stmt->get_result();

        while ($row = $result->fetch_assoc()) $recipients[] = $row;

        $stmt->close();

    } elseif ($recipient_type === 'all') {

        $result = $conn->query("SELECT * FROM students WHERE status = 'active'");

        if ($result) while ($row = $result->fetch_assoc()) $recipients[] = $row;

    }



    if (empty($recipients)) {

        echo json_encode(['success' => false, 'message' => 'No recipients found']);

        exit;

    }



    // Simulate sending (in production, integrate with SMS/Email APIs)

    $successCount = 0;

    foreach ($recipients as $recipient) {

        $recipientEmail = $recipient['email'] ?? '';

        $recipientPhone = $recipient['phone'] ?? '';

        

        // For demo, we just save to database

        $recipientContact = $alert_type === 'sms' ? $recipientPhone : $recipientEmail;

        

        $stmt = $conn->prepare("INSERT INTO notifications (student_id, type, recipient, subject, message, status, sent_at) VALUES (?, ?, ?, ?, ?, ?, NOW())");

        $status = 'sent'; // Simulated success

        $stmt->bind_param("isssss", $recipient['id'], $alert_type, $recipientContact, $subject, $message, $status);

        

        if ($stmt->execute()) {

            $successCount++;

        }

        $stmt->close();

    }



    if ($successCount > 0) {

        echo json_encode(['success' => true, 'message' => "Alert sent to $successCount recipient(s) successfully"]);

    } else {

        echo json_encode(['success' => false, 'message' => 'Failed to send alerts']);

    }

}

else {

    echo json_encode(['success' => false, 'message' => 'Invalid action']);

}



$conn->close();

?>