<?php
/**
 * Action: Send a WhatsApp broadcast to parents (all or by class).
 * Requires the whatsapp_comms add-on and a configured Cloud API connection.
 */

if (!defined('DB_HOST')) {
    require_once __DIR__ . '/../../config.php';
}
require_once __DIR__ . '/../../includes/whatsapp_lib.php';

function action_send_whatsapp_broadcast(array $params): array
{
    if (!function_exists('hasModule') || !hasModule('whatsapp_comms')) {
        return ['success' => false, 'error' => 'The WhatsApp add-on is not active for this school.'];
    }
    if (!wa_is_configured()) {
        return ['success' => false, 'error' => 'WhatsApp is not configured. Set it up on the WhatsApp page first.'];
    }

    $conn       = getDBConnection();
    $target     = $params['target'] ?? 'all';         // all | class
    $class_name = trim((string) ($params['class_name'] ?? ''));
    $message    = trim((string) ($params['message'] ?? ''));
    if ($message === '') return ['success' => false, 'error' => 'A message is required.'];

    if ($target === 'class' && $class_name !== '') {
        $stmt = $conn->prepare("SELECT first_name, last_name, father_phone, mother_phone, phone
                                FROM students WHERE status='active' AND class=?");
        $stmt->bind_param('s', $class_name);
    } else {
        $stmt = $conn->prepare("SELECT first_name, last_name, father_phone, mother_phone, phone
                                FROM students WHERE status='active'");
    }
    $stmt->execute();
    $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

    $sent = 0; $failed = 0; $skipped = 0;
    $seen = [];
    foreach ($rows as $r) {
        $phone = trim((string) ($r['father_phone'] ?: $r['mother_phone'] ?: $r['phone'] ?: ''));
        if ($phone === '') { $skipped++; continue; }
        $norm = wa_format_phone($phone);
        if (isset($seen[$norm])) continue;   // de-dupe siblings sharing a number
        $seen[$norm] = true;
        $res = sendWhatsApp($phone, $message);
        if (!empty($res['success'])) $sent++; else $failed++;
    }

    return [
        'success' => true,
        'message' => "WhatsApp broadcast complete — {$sent} sent, {$failed} failed, {$skipped} without a number.",
        'sent'    => $sent, 'failed' => $failed, 'skipped' => $skipped,
        'scope'   => $target === 'class' ? $class_name : 'all parents',
    ];
}
