<?php

/**

 * Automated Fee Reminders

 * Run this script daily via cron to send automated reminders

 *

 * CRON: 0 9 * * * php /path/to/cron/send_fee_reminders.php

 */



// ── Cron guard ─────────────────────────────────────────────────────────

if (php_sapi_name() !== 'cli') {

    $token = $_GET['token'] ?? ($_SERVER['HTTP_X_CRON_TOKEN'] ?? '');

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

    $cron_conn = getDBConnection();

    $cron_token = '';

    if ($cron_conn instanceof mysqli) {

        $r = $cron_conn->query("SELECT setting_value FROM settings WHERE setting_key='cron_token' LIMIT 1");

        if ($r && $row = $r->fetch_assoc()) $cron_token = $row['setting_value'];

    }

    if ($cron_token === '' || $token !== $cron_token) { http_response_code(403); exit('Forbidden'); }

} else {

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

}

require_once __DIR__ . '/../ai_config.php';



$conn = getDBConnection();

$predictor = new AIPaymentPredictor();



// Get fees due in the next 3 days

$query = "SELECT 

            fs.*,

            s.id as student_id,

            s.first_name,

            s.last_name,

            s.father_name as parent_name,

            s.father_phone as phone,

            s.mother_phone as alt_phone

          FROM fee_structures fs

          JOIN students s ON s.class = fs.class_name

          WHERE fs.due_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 3 DAY)

          AND s.status = 'active'

          AND NOT EXISTS (

              SELECT 1 FROM payments p 

              WHERE p.student_id = s.id 

              AND p.fee_structure_id = fs.id

              AND p.amount_paid >= fs.amount

          )";



$result = $conn->query($query);

$reminders = [];

$sent = 0;

$failed = 0;



while ($row = $result->fetch_assoc()) {

    $reminders[] = $row;

    

    // Get AI prediction for this student

    $prediction = $predictor->predictPaymentProbability($row['student_id']);

    $riskLevel = $prediction['risk_level'];

    

    // Determine urgency based on risk and due date

    $daysUntilDue = (strtotime($row['due_date']) - time()) / 86400;

    $urgency = $daysUntilDue <= 1 ? 'URGENT' : ($riskLevel == 'Critical' ? 'IMPORTANT' : 'Reminder');

    

    // Craft message based on risk level

    if ($riskLevel == 'Critical') {

        $message = "URGENT: Dear {$row['parent_name']}, your payment of " . formatCurrency($row['amount']) . 

                   " for {$row['first_name']} ({$row['fee_type']}) is due tomorrow. " .

                   "Please make immediate payment to avoid any disruption. Thank you.";

    } elseif ($riskLevel == 'High') {

        $message = "REMINDER: Dear {$row['parent_name']}, your payment of " . formatCurrency($row['amount']) . 

                   " for {$row['first_name']} ({$row['fee_type']}) is due in {$daysUntilDue} days. " .

                   "Please arrange payment soon. Thank you.";

    } else {

        $message = "Friendly reminder: Dear {$row['parent_name']}, your payment of " . formatCurrency($row['amount']) . 

                   " for {$row['first_name']} ({$row['fee_type']}) is due on " . date('d M', strtotime($row['due_date'])) . 

                   ". Thank you for your continued support.";

    }

    

    // Send SMS to primary phone

    if (!empty($row['phone'])) {

        $result = sendSMS($row['phone'], $message);

        if ($result) $sent++; else $failed++;

    }

    

    // Try alternative phone if primary failed

    if (!empty($row['alt_phone']) && !$result) {

        $result = sendSMS($row['alt_phone'], $message);

        if ($result) $sent++;

    }

    

    // Small delay to prevent rate limiting

    usleep(200000);

}



// Log the activity

$logMessage = "Automated reminders sent: $sent successful, $failed failed";

logActivity($conn, $_SESSION['user_id'] ?? 1, 'Automated Fee Reminders', $logMessage);



echo date('Y-m-d H:i:s') . " - $logMessage\n";

?>