<?php
/**
 * VoIP Notification Service Class
 * 
 * Handles VoIP notifications for teachers when their class routine time arrives
 */
require_once __DIR__ . '/../config/voip_settings.php';

class VoIPNotificationService {
    
    private $pdo;
    private $logPath;
    
    /**
     * Constructor - Initialize VoIP notification service
     * 
     * @param PDO $pdo Database connection
     */
    public function __construct(PDO $pdo) {
        $this->pdo = $pdo;
        
        // Set up log directory
        $this->logPath = VOIP_LOG_PATH;
        if (!is_dir($this->logPath)) {
            @mkdir($this->logPath, 0755, true);
        }
    }
    
    /**
     * Check for upcoming classes and send VoIP notifications
     * 
     * @param int|null $teacherId Optional teacher ID to check for specific teacher
     * @return array Result of notification attempts
     */
    public function checkAndSendNotifications($teacherId = null) {
        $currentTime = date('H:i:s');
        $currentDay = strtolower(date('l')); // e.g., 'monday', 'tuesday'
        
        // Query to find classes happening now according to the routine schedule
        $sql = "
            SELECT t.*, 
                   c.name as class_name, 
                   c.section as class_section,
                   s.name as subject_name, 
                   s.code as subject_code,
                   te.first_name as teacher_first_name, 
                   te.last_name as teacher_last_name,
                   te.phone as teacher_phone
            FROM timetable t
            JOIN classes c ON t.class_id = c.id
            JOIN subjects s ON t.subject_id = s.id
            JOIN teachers te ON t.teacher_id = te.id
            WHERE t.day_of_week = ?
            AND t.status = 'active'
            AND TIME(t.start_time) = ?
            AND t.academic_year IN (
                SELECT session_name FROM academic_sessions WHERE status = 'active'
            )
        ";
        
        $params = [$currentDay, $currentTime];
        
        if ($teacherId) {
            $sql .= " AND t.teacher_id = ?";
            $params[] = $teacherId;
        }
        
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($params);
        $upcomingClasses = $stmt->fetchAll();
        
        $results = [
            'notifications_sent' => 0,
            'notifications_failed' => 0,
            'classes_found' => count($upcomingClasses),
            'details' => []
        ];
        
        foreach ($upcomingClasses as $class) {
            $notificationResult = $this->sendVoIPNotification(
                $class['teacher_phone'], 
                $this->buildNotificationMessage($class)
            );
            
            $results['details'][] = [
                'teacher_id' => $class['teacher_id'],
                'teacher_name' => $class['teacher_first_name'] . ' ' . $class['teacher_last_name'],
                'class_info' => $class['class_name'] . ' - ' . $class['class_section'] . ' (' . $class['subject_name'] . ')',
                'time' => $class['start_time'] . ' - ' . $class['end_time'],
                'notification_result' => $notificationResult
            ];
            
            if ($notificationResult['success']) {
                $results['notifications_sent']++;
            } else {
                $results['notifications_failed']++;
            }
        }
        
        return $results;
    }
    
    /**
     * Build notification message in Bengali
     * 
     * @param array $class Class information
     * @return string Bengali notification message
     */
    private function buildNotificationMessage($class) {
        // Use the template from config and replace placeholders
        $message = CLASS_STARTING_MESSAGE;
        
        // Ensure all messages are in Bengali
        $day_bn = [
            'sunday' => 'রবিবার',
            'monday' => 'সোমবার', 
            'tuesday' => 'মঙ্গলবার',
            'wednesday' => 'বুধবার',
            'thursday' => 'বৃহস্পতিবার',
            'friday' => 'শুক্রবার',
            'saturday' => 'শনিবার'
        ];
        
        $day = $day_bn[$class['day_of_week']] ?? $class['day_of_week'];
        $startTime = date('g:i A', strtotime($class['start_time']));
        $endTime = date('g:i A', strtotime($class['end_time']));
        
        $message = str_replace('{{SUBJECT}}', $class['subject_name'], $message);
        $message = str_replace('{{CLASS_NAME}}', $class['class_name'], $message);
        $message = str_replace('{{CLASS_SECTION}}', $class['class_section'], $message);
        $message = str_replace('{{START_TIME}}', $startTime, $message);
        $message = str_replace('{{END_TIME}}', $endTime, $message);
        $message = str_replace('{{DAY}}', $day, $message);
        
        return $message;
    }
    
    /**
     * Send VoIP notification to a teacher
     * 
     * @param string $phoneNumber Teacher's phone number
     * @param string $message Notification message
     * @return array Result of the notification attempt
     */
    public function sendVoIPNotification($phoneNumber, $message) {
        // Check if VoIP is enabled
        if (!VOIP_ENABLED) {
            return [
                'success' => false,
                'message' => 'VoIP notifications are currently disabled',
                'phone_number' => $phoneNumber,
                'timestamp' => date('Y-m-d H:i:s')
            ];
        }

        $result = [
            'success' => true,
            'message' => 'VoIP notification sent successfully',
            'phone_number' => $phoneNumber,
            'timestamp' => date('Y-m-d H:i:s')
        ];
        
        try {
            // Ensure message is in Bengali
            $bengaliMessage = $this->ensureBengaliMessage($message);
            
            // In a real implementation, this would connect to a VoIP service
            // For now, we'll simulate the process and log it
            
            // Different handling based on provider
            switch (VOIP_PROVIDER) {
                case 'SIMULATED':
                    // Simulated service for demo purposes
                    $result['message'] = 'Simulated VoIP notification sent successfully in Bengali';
                    break;
                
                case 'TWILIO':
                    // Would integrate with Twilio API
                    // $this->sendViaTwilio($phoneNumber, $bengaliMessage);
                    break;
                    
                default:
                    $result['message'] = 'Unknown VoIP provider configured';
                    $result['success'] = false;
                    break;
            }
            
            // Log the notification
            $this->logVoIPNotification($phoneNumber, $bengaliMessage, $result);
            
        } catch (Exception $e) {
            $result['success'] = false;
            $result['message'] = 'Failed to send VoIP notification: ' . $e->getMessage();
            
            // Log failure
            $this->logVoIPNotification($phoneNumber, $message, $result);
        }
        
        return $result;
    }
    
    /**
     * Ensure message is in Bengali
     * 
     * @param string $message Original message
     * @return string Bengali message
     */
    private function ensureBengaliMessage($message) {
        // Our system already uses Bengali messages, but we ensure it stays in Bengali
        // If somehow an English message gets passed, we would convert or ensure Bengali content
        
        // For now, we just return the message as-is since our system uses Bengali
        return $message;
    }
    
    /**
     * Log VoIP notification to file
     * 
     * @param string $phoneNumber Phone number
     * @param string $message Message sent
     * @param array $result Result of the notification
     */
    private function logVoIPNotification($phoneNumber, $message, $result) {
        try {
            $logFile = $this->logPath . date('Y-m-d') . '_voip_notifications.log';
            
            $logEntry = [
                'timestamp' => date('Y-m-d H:i:s'),
                'phone_number' => $phoneNumber,
                'message' => $message,
                'success' => $result['success'],
                'result_message' => $result['message'] ?? ''
            ];
            
            $logLine = json_encode($logEntry, JSON_UNESCAPED_UNICODE) . "\n";
            @file_put_contents($logFile, $logLine, FILE_APPEND | LOCK_EX);
        } catch (Exception $e) {
            error_log('VoIP Notification Logging Error: ' . $e->getMessage());
        }
    }
    
    /**
     * Schedule periodic checking for class notifications
     * This method would typically be called by a cron job every few minutes
     */
    public function schedulePeriodicCheck() {
        // This would be called by a cron job
        // For example, add this to crontab: */5 * * * * /usr/bin/php /path/to/check_voip_notifications.php
        return $this->checkAndSendNotifications();
    }
}
?>