<?php

/**

 * Action: Bulk notify parents (all / by class / individual) with optional SMS.

 */



if (!defined('DB_HOST')) {

    require_once __DIR__ . '/../../config.php';

}



function action_bulk_notify_parents(array $params): array

{

    $conn         = getDBConnection();

    $target       = $params['target'] ?? 'all';      // all | class | individual

    $class_name   = $params['class_name'] ?? null;

    $parent_id    = isset($params['parent_id']) ? (int) $params['parent_id'] : null;

    $title        = $params['title'] ?? 'Notification from School';

    $message      = $params['message'] ?? '';

    $send_sms     = !empty($params['send_sms']) && $params['send_sms'] !== 'false';

    $school_name  = getSettingValue('school_name') ?: 'School';

    $school_phone = getSettingValue('school_phone') ?: '';



    if (empty($message)) {

        return ['success' => false, 'error' => 'Message is required'];

    }



    // Get target parent IDs

    $parent_ids = [];

    $parent_phones = [];



    if ($target === 'individual' && $parent_id) {

        $p_stmt = $conn->prepare("SELECT id, phone FROM parent_accounts WHERE id = ?");

        $p_stmt->bind_param('i', $parent_id);

        $p_stmt->execute();

        $p_rows = $p_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

        foreach ($p_rows as $r) {

            $parent_ids[]    = (int) $r['id'];

            $parent_phones[] = $r['phone'] ?? '';

        }

    } elseif ($target === 'class' && $class_name) {

        $p_stmt = $conn->prepare(

            "SELECT DISTINCT pa.id, pa.phone

             FROM parent_accounts pa

             JOIN parent_student_link psl ON psl.parent_id = pa.id

             JOIN students s ON s.id = psl.student_id

             WHERE s.class = ? AND s.status = 'active'"

        );

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

        $p_stmt->execute();

        $p_rows = $p_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

        foreach ($p_rows as $r) {

            $parent_ids[]    = (int) $r['id'];

            $parent_phones[] = $r['phone'] ?? '';

        }

    } else {

        // All parents

        $p_result = $conn->query("SELECT id, phone FROM parent_accounts WHERE is_active = 1 OR is_active IS NULL");

        if ($p_result) {

            while ($r = $p_result->fetch_assoc()) {

                $parent_ids[]    = (int) $r['id'];

                $parent_phones[] = $r['phone'] ?? '';

            }

        }

    }



    $notified_count = 0;

    $sms_sent       = 0;

    $created_by     = $_SESSION['user_id'] ?? 0;



    foreach ($parent_ids as $idx => $pid) {

        $notif_stmt = $conn->prepare(

            "INSERT INTO parent_notifications

             (parent_id, title, message, notification_type, is_sent, sent_by, created_at)

             VALUES (?, ?, ?, 'general', 1, ?, NOW())"

        );

        $notif_stmt->bind_param('issi', $pid, $title, $message, $created_by);

        if ($notif_stmt->execute()) {

            $notified_count++;

        }



        if ($send_sms && !empty($parent_phones[$idx])) {

            $contact_line = $school_phone ? "\nEnquiries: {$school_phone}" : '';

            $sms_text = "[{$school_name}]\n{$title}\n\n{$message}{$contact_line}";

            // Allow up to 320 chars (2-part SMS) so the message is never cut mid-sentence

            if (strlen($sms_text) > 320) {

                $sms_text = substr($sms_text, 0, 317) . '...';

            }

            if (sendSMS($parent_phones[$idx], $sms_text)) {

                $sms_sent++;

            }

        }

    }



    return [

        'success'        => true,

        'notified_count' => $notified_count,

        'sms_sent'       => $sms_sent,

        'target'         => $target,

    ];

}

