<?php
require_once('../../includes/config.php');

// Fetch students with fees due in 3 days
$targetDate = date('Y-m-d', strtotime('+3 days'));

$sql = "SELECT s.student_name, s.parent_phone, fa.total_amount, fa.due_month 
        FROM fee_assign fa
        JOIN students s ON fa.student_id = s.id
        WHERE fa.due_date = :target AND fa.payment_status != 'Paid'";

$stmt = $pdo->prepare($sql);
$stmt->execute([':target' => $targetDate]);
$students = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($students as $s) {
    $phone = "91" . $s['parent_phone']; // Adjust country code
    $msg = "Reminder: Dear Parent, fee for {$s['student_name']} (Month: {$s['due_month']}) of ₹{$s['total_amount']} is due on " . date('d-M', strtotime($targetDate)) . ". Please ignore if already paid.";

    // Call Node.js Bridge
    $ch = curl_init('http://localhost:3000/send-message');
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['phone' => $phone, 'message' => $msg]));
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_exec($ch);
    curl_close($ch);

    // Sleep 15 seconds to prevent WhatsApp ban
    sleep(15);
}?>