<?php
// admin/sms-cron.php - Run every minute via cron
require_once '../includes/config.php';
require_once '../includes/sms_config.php';

// Process scheduled SMS
$stmt = $pdo->prepare("
    SELECT ss.*, c.title_bn as course_name 
    FROM scheduled_sms ss 
    LEFT JOIN courses c ON ss.course_id = c.id 
    WHERE ss.is_sent = 0 AND ss.scheduled_at <= NOW()
");
$stmt->execute();
$pending_sms = $stmt->fetchAll();

foreach($pending_sms as $sms_item) {
    $sent = 0;
    
    if($sms_item['recipient_type'] == 'single' && !empty($sms_item['recipient_phone'])) {
        if(isset($sms)) {
            $result = $sms->sendSMS($sms_item['recipient_phone'], $sms_item['message']);
            if($result) $sent = 1;
        }
    } elseif($sms_item['recipient_type'] == 'course_students' && $sms_item['course_id']) {
        $stmt2 = $pdo->prepare("
            SELECT u.phone FROM users u 
            JOIN enrollments e ON u.id = e.user_id 
            WHERE e.course_id = ? AND e.payment_status = 'completed' AND u.phone IS NOT NULL
        ");
        $stmt2->execute([$sms_item['course_id']]);
        $phones = $stmt2->fetchAll();
        
        if(isset($sms)) {
            foreach($phones as $p) {
                $result = $sms->sendSMS($p['phone'], $sms_item['message']);
                if($result) $sent++;
            }
        }
    }
    
    // Mark as sent
    $pdo->prepare("UPDATE scheduled_sms SET is_sent = 1, sent_at = NOW() WHERE id = ?")->execute([$sms_item['id']]);
}

echo "Processed: " . count($pending_sms) . " SMS batches\n";
?>