<?php
/**
 * Cron Script: Check Class Notifications
 * 
 * This script runs periodically to check for upcoming classes and send VoIP notifications to teachers
 */

require_once(__DIR__ . '/../config/database.php');
require_once(__DIR__ . '/../classes/VoIPNotificationService.php');
require_once(__DIR__ . '/../config/voip_settings.php');

// Check if VoIP is enabled
if (!VOIP_ENABLED) {
    echo "VoIP notifications are disabled in configuration.\n";
    exit(0);
}

// Create VoIP notification service instance
$voipService = new VoIPNotificationService($pdo);

// Check for classes starting right now during school hours and send notifications
$result = $voipService->checkAndSendNotifications();

// Log the results
$logMessage = "Class notification check completed at " . date('Y-m-d H:i:s') . 
             ". Found {$result['classes_found']} classes. " .
             "Notifications sent: {$result['notifications_sent']}, " .
             "Failed: {$result['notifications_failed']}.\n";

// Output to console for cron logging
echo $logMessage;

// Also log to file
$logFile = __DIR__ . '/../logs/class_notification_cron_' . date('Y-m-d') . '.log';
file_put_contents($logFile, $logMessage, FILE_APPEND | LOCK_EX);

// Add details to log if there were notifications
if (!empty($result['details'])) {
    foreach ($result['details'] as $detail) {
        $detailLog = "Teacher: {$detail['teacher_name']}, " .
                    "Class: {$detail['class_info']}, " .
                    "Time: {$detail['time']}, " .
                    "Status: " . ($detail['notification_result']['success'] ? 'SUCCESS' : 'FAILED') . "\n";
        
        file_put_contents($logFile, $detailLog, FILE_APPEND | LOCK_EX);
    }
}

exit(0);
?>