<?php
// cron/followup_reminder.php
require_once __DIR__ . '/../api/_pdo_db_connect.php';

$today = date('Y-m-d');

// find due or overdue followups
$sql = "SELECT f.id, f.customer_id, f.next_followup_date, c.mobile, c.customer_name, c.assigned_to
        FROM sd_followups f
        INNER JOIN sd_customers c ON c.id = f.customer_id
        WHERE f.next_followup_date IS NOT NULL
        AND f.next_followup_date <= :today";
$stmt = $pdo->prepare($sql);
$stmt->execute([':today' => $today]);

$list = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($list as $f) {
    // You may integrate SMS/WhatsApp/Push Notification here.
    // For now, log entries into automation logs table.

    $log = $pdo->prepare("INSERT INTO sd_followup_automation_logs
                          (followup_id, customer_id, triggered_on, next_followup_date, created_at)
                          VALUES (:fid, :cid, :today, :nfd, NOW())");
    $log->execute([
        ':fid' => $f['id'],
        ':cid' => $f['customer_id'],
        ':today' => $today,
        ':nfd' => $f['next_followup_date']
    ]);
}

echo "Reminder execution completed: " . count($list) . " follow-ups processed\n";
