<?php
/**
 * Action: Send AI-personalized fee reminder SMS to parents of students with balances.
 */

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

function action_send_fee_reminders(array $params): array
{
    $conn       = getDBConnection();
    $class_name = $params['class_name'] ?? null;
    $min_balance = (float) ($params['min_balance'] ?? 0.01);
    $academic_year = $params['academic_year'] ?? getSettingValue('academic_year') ?? date('Y');
    $school_name   = getSettingValue('school_name') ?: 'the school';
    $school_phone  = getSettingValue('school_phone') ?: '';

    // Pre-aggregated on both sides — see ai/fee_balance.php. The previous
    // inline join double-counted a fee for every extra instalment paid against
    // it, so parents were being texted an inflated amount.
    $students = rbcOutstandingBalances($conn, $academic_year, $class_name, $min_balance);

    $sent_count   = 0;
    $failed_count = 0;
    $notified     = [];

    foreach ($students as $student) {
        $name    = trim($student['first_name'] . ' ' . $student['last_name']);
        $class   = $student['class'];
        $balance = number_format((float) $student['balance'], 2);

        // Ask AI to personalize the message
        $ai_result = RBCAIEngine::generate(
            "Write a professional school fee reminder SMS for a parent. " .
            "Student: {$name}, Class: {$class}, School: {$school_name}, " .
            "Outstanding balance: GHS {$balance}, School phone: {$school_phone}. " .
            "Start with the school name in square brackets. Address the parent formally. " .
            "State the student name, class, and exact amount owed. " .
            "Include a polite call-to-action (visit fees office or call the number). " .
            "Close with 'Thank you.' Keep the entire message under 320 characters.",
            "You are a professional school communications officer. " .
            "Write clear, courteous, and formal SMS messages that represent the school well. " .
            "Never use slang, abbreviations, or informal language."
        );

        if ($ai_result['success']) {
            $sms_text = trim($ai_result['content']);
        } else {
            $contact_line = $school_phone ? " Call: {$school_phone}." : '';
            $sms_text = "[{$school_name}] Dear Parent/Guardian,\n{$name} ({$class}) has an outstanding fee balance of GHS {$balance}. Kindly visit the school fees office to settle this at your earliest convenience.{$contact_line}\nThank you.";
        }

        // Allow up to 320 chars (2-part SMS) so messages are never cut mid-sentence
        if (strlen($sms_text) > 320) {
            $sms_text = substr($sms_text, 0, 317) . '...';
        }

        $phones = array_filter([
            $student['father_phone'] ?? '',
            $student['mother_phone'] ?? '',
        ]);

        $ok = false;
        foreach ($phones as $phone) {
            if (!empty(trim($phone))) {
                $sent = sendSMS($phone, $sms_text);
                if ($sent) $ok = true;
            }
        }

        if ($ok) {
            $sent_count++;
            $notified[] = $name;
        } else {
            $failed_count++;
        }
    }

    return [
        'success'           => true,
        'sent_count'        => $sent_count,
        'failed_count'      => $failed_count,
        'students_notified' => $notified,
        'total_found'       => count($students),
    ];
}
