<?php
/**
 * VoIP Check Page
 * 
 * Allows administrators to check and test the VoIP notification system
 */

session_start();

// Include access control functions
require_once '../includes/access_control.php';
require_once '../config/database.php';
require_once '../classes/VoIPNotificationService.php';
require_once '../config/voip_settings.php';

// Check if user is logged in and is an admin
require_any_role(['admin'], '../login.php');

$user_role = $_SESSION['user_role'];
$user_id = $_SESSION['user_id'];

// Only admins can access this page
if ($user_role !== 'admin') {
    header('Location: ../index.php');
    exit();
}

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

$message = '';
$messageType = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['check_now'])) {
        // Check for classes starting now
        $result = $voipService->checkAndSendNotifications();
        
        $message = "Checked for classes starting now. Found {$result['classes_found']} classes, sent {$result['notifications_sent']} notifications.";
        $messageType = $result['notifications_sent'] > 0 ? 'success' : 'info';
    } 
    elseif (isset($_POST['test_notification'])) {
        // Test sending a notification to a specific teacher
        $teacher_id = $_POST['teacher_id'] ?? null;
        
        if ($teacher_id) {
            // Get teacher details
            $stmt = $pdo->prepare("SELECT first_name, last_name, phone FROM teachers WHERE id = ? AND status = 'active'");
            $stmt->execute([$teacher_id]);
            $teacher = $stmt->fetch();
            
            if ($teacher && !empty($teacher['phone'])) {
                $testMessage = "এটি একটি পরীক্ষামূলক VoIP নোটিফিকেশন। এটি কার্যকরভাবে কাজ করছে।";
                $result = $voipService->sendVoIPNotification($teacher['phone'], $testMessage);
                
                if ($result['success']) {
                    $message = "Test notification sent successfully to {$teacher['first_name']} {$teacher['last_name']}";
                    $messageType = 'success';
                } else {
                    $message = "Failed to send test notification: " . $result['message'];
                    $messageType = 'danger';
                }
            } else {
                $message = "Teacher not found or does not have a phone number.";
                $messageType = 'warning';
            }
        } else {
            $message = "Please select a teacher for the test notification.";
            $messageType = 'warning';
        }
    }
    elseif (isset($_POST['manual_trigger'])) {
        // Manually trigger notification for a specific class
        $class_id = $_POST['class_id'] ?? null;
        $subject_id = $_POST['subject_id'] ?? null;
        $teacher_id = $_POST['teacher_id_manual'] ?? null;
        
        if ($class_id && $subject_id && $teacher_id) {
            // Get class, subject, and teacher details
            $stmt = $pdo->prepare("
                SELECT c.name as class_name, c.section as class_section,
                       s.name as subject_name,
                       t.first_name as teacher_first_name, t.last_name as teacher_last_name, t.phone as teacher_phone
                FROM classes c, subjects s, teachers t
                WHERE c.id = ? AND s.id = ? AND t.id = ?
            ");
            $stmt->execute([$class_id, $subject_id, $teacher_id]);
            $details = $stmt->fetch();
            
            if ($details && !empty($details['teacher_phone'])) {
                $testMessage = "অধ্যাপক, আপনার ক্লাস শুরু হবে অথবা চলছে: {$details['subject_name']} - {$details['class_name']} {$details['class_section']}। অনুগ্রহ করে ক্লাসে উপস্থিত থাকুন।";
                $result = $voipService->sendVoIPNotification($details['teacher_phone'], $testMessage);
                
                if ($result['success']) {
                    $message = "Manual notification sent successfully to {$details['teacher_first_name']} {$details['teacher_last_name']}";
                    $messageType = 'success';
                } else {
                    $message = "Failed to send manual notification: " . $result['message'];
                    $messageType = 'danger';
                }
            } else {
                $message = "Could not get valid details for the selected class, subject, or teacher.";
                $messageType = 'warning';
            }
        } else {
            $message = "Please select class, subject, and teacher for manual notification.";
            $messageType = 'warning';
        }
    }
    elseif (isset($_POST['test_voice'])) {
        // This is just to show the test voice functionality
        $message = "Voice test initiated. Please check your device's audio output.";
        $messageType = 'info';
    }
}

// Get teachers for dropdown
$teachers = $pdo->query("SELECT id, first_name, last_name, phone FROM teachers WHERE status = 'active' ORDER BY first_name, last_name")->fetchAll();

// Get classes for dropdown
$classes = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' ORDER BY name, section")->fetchAll();

// Get subjects for dropdown
$subjects = $pdo->query("SELECT id, name, code FROM subjects WHERE status = 'active' ORDER BY name")->fetchAll();

?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ভয়েজ চেক - ক্লাস রুটিন নোটিফিকেশন সিস্টেম</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
    <style>
        .voice-test-section {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 10px;
            padding: 20px;
            margin-top: 20px;
        }
        .voice-test-btn {
            background: rgba(255,255,255,0.2);
            border: 2px solid rgba(255,255,255,0.3);
            color: white;
            transition: all 0.3s ease;
        }
        .voice-test-btn:hover {
            background: rgba(255,255,255,0.3);
            transform: scale(1.05);
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand d-flex align-items-center" href="../index.php">
                <i class="fas fa-graduation-cap me-2"></i>
                <span>স্কুল ম্যানেজমেন্ট সিস্টেম</span>
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="../index.php">
                            <i class="fas fa-home me-1"></i> হোম
                        </a>
                    </li>
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
                            <i class="fas fa-user me-1"></i> <?php echo $_SESSION['username']; ?>
                        </a>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="../profile.php"><i class="fas fa-user-circle me-2"></i> প্রোফাইল</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="../logout.php"><i class="fas fa-sign-out-alt me-2"></i> লগআউট</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header bg-gradient">
                        <h5 class="mb-0"><i class="fas fa-phone-volume me-2"></i> ভয়েজ নোটিফিকেশন চেক</h5>
                    </div>
                    <div class="card-body">
                        <?php if ($message): ?>
                            <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show">
                                <i class="fas fa-<?php echo $messageType == 'success' ? 'check-circle' : ($messageType == 'danger' ? 'exclamation-triangle' : ($messageType == 'warning' ? 'exclamation-circle' : 'info-circle')); ?> me-2"></i>
                                <?php echo $message; ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        <?php endif; ?>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="card bg-light mb-4">
                                    <div class="card-header">
                                        <h6 class="mb-0"><i class="fas fa-clock me-2"></i> বর্তমান সময় চেক</h6>
                                    </div>
                                    <div class="card-body">
                                        <p><strong>বর্তমান সময়:</strong> <?php echo date('Y-m-d H:i:s'); ?></p>
                                        <p><strong>বর্তমান দিন:</strong> <?php echo ucfirst(date('l')); ?></p>
                                        <p><strong>স্কুল ঘন্টা:</strong> ৭:০০ পূর্বাহ্ন - ৬:০০ অপরাহ্ন</p>
                                        <p><strong>VoIP সক্রিয়:</strong> <?php echo VOIP_ENABLED ? 'হ্যাঁ' : 'না'; ?></p>
                                        
                                        <form method="POST" class="mt-3">
                                            <button type="submit" name="check_now" class="btn btn-primary w-100">
                                                <i class="fas fa-search me-2"></i> এখনই চেক করুন
                                            </button>
                                            <small class="text-muted">এই মুহূর্তে শুরু হওয়া ক্লাসগুলি পরীক্ষা করুন</small>
                                        </form>
                                    </div>
                                </div>
                                
                                <div class="card bg-light">
                                    <div class="card-header">
                                        <h6 class="mb-0"><i class="fas fa-comment-dots me-2"></i> টেস্ট নোটিফিকেশন</h6>
                                    </div>
                                    <div class="card-body">
                                        <form method="POST">
                                            <div class="mb-3">
                                                <label for="teacher_id" class="form-label">শিক্ষক নির্বাচন করুন</label>
                                                <select class="form-select" id="teacher_id" name="teacher_id" required>
                                                    <option value="">নির্বাচন করুন</option>
                                                    <?php foreach ($teachers as $teacher): ?>
                                                        <option value="<?php echo $teacher['id']; ?>">
                                                            <?php echo htmlspecialchars($teacher['first_name'] . ' ' . $teacher['last_name']); ?>
                                                            <?php if (!empty($teacher['phone'])): ?>(<?php echo htmlspecialchars($teacher['phone']); ?>)<?php endif; ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            
                                            <button type="submit" name="test_notification" class="btn btn-success w-100">
                                                <i class="fas fa-paper-plane me-2"></i> টেস্ট নোটিফিকেশন পাঠান
                                            </button>
                                            <small class="text-muted">নির্বাচিত শিক্ষককে টেস্ট VoIP নোটিফিকেশন পাঠান</small>
                                        </form>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-md-6">
                                <div class="card bg-light">
                                    <div class="card-header">
                                        <h6 class="mb-0"><i class="fas fa-bullhorn me-2"></i> ম্যানুয়াল নোটিফিকেশন</h6>
                                    </div>
                                    <div class="card-body">
                                        <form method="POST">
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <div class="mb-3">
                                                        <label for="class_id" class="form-label">ক্লাস</label>
                                                        <select class="form-select" id="class_id" name="class_id" required>
                                                            <option value="">নির্বাচন করুন</option>
                                                            <?php foreach ($classes as $class): ?>
                                                                <option value="<?php echo $class['id']; ?>">
                                                                    <?php echo htmlspecialchars($class['name'] . ' ' . $class['section']); ?>
                                                                </option>
                                                            <?php endforeach; ?>
                                                        </select>
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <div class="mb-3">
                                                        <label for="subject_id" class="form-label">বিষয়</label>
                                                        <select class="form-select" id="subject_id" name="subject_id" required>
                                                            <option value="">নির্বাচন করুন</option>
                                                            <?php foreach ($subjects as $subject): ?>
                                                                <option value="<?php echo $subject['id']; ?>">
                                                                    <?php echo htmlspecialchars($subject['name'] . ' (' . $subject['code'] . ')'); ?>
                                                                </option>
                                                            <?php endforeach; ?>
                                                        </select>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label for="teacher_id_manual" class="form-label">শিক্ষক</label>
                                                <select class="form-select" id="teacher_id_manual" name="teacher_id_manual" required>
                                                    <option value="">নির্বাচন করুন</option>
                                                    <?php foreach ($teachers as $teacher): ?>
                                                        <option value="<?php echo $teacher['id']; ?>">
                                                            <?php echo htmlspecialchars($teacher['first_name'] . ' ' . $teacher['last_name']); ?>
                                                            <?php if (!empty($teacher['phone'])): ?>(<?php echo htmlspecialchars($teacher['phone']); ?>)<?php endif; ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            
                                            <button type="submit" name="manual_trigger" class="btn btn-info w-100">
                                                <i class="fas fa-bullhorn me-2"></i> ম্যানুয়াল নোটিফিকেশন ট্রিগার
                                            </button>
                                            <small class="text-muted">নির্বাচিত ক্লাস/বিষয়/শিক্ষকের জন্য নোটিফিকেশন পাঠান</small>
                                        </form>
                                    </div>
                                </div>
                                
                                <div class="card bg-light mt-4">
                                    <div class="card-header">
                                        <h6 class="mb-0"><i class="fas fa-info-circle me-2"></i> সিস্টেম তথ্য</h6>
                                    </div>
                                    <div class="card-body">
                                        <p><strong>পরীক্ষা ব্যবধান:</strong> <?php echo VOIP_CHECK_INTERVAL; ?> সেকেন্ড</p>
                                        <p><strong>নোটিফিকেশন উইন্ডো:</strong> <?php echo VOIP_NOTIFICATION_WINDOW; ?> সেকেন্ড</p>
                                        <p><strong>প্রভাইডার:</strong> <?php echo VOIP_PROVIDER; ?></p>
                                        <p><strong>লগ সক্রিয়:</strong> <?php echo VOIP_LOG_ENABLED ? 'হ্যাঁ' : 'না'; ?></p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Voice Test Section -->
                        <div class="voice-test-section">
                            <h5 class="text-center mb-4">
                                <i class="fas fa-volume-up me-2"></i> ভয়েস টেস্ট অপশন
                            </h5>
                            <div class="text-center">
                                <button type="button" class="btn voice-test-btn btn-lg mb-3" onclick="testVoiceAlert()">
                                    <i class="fas fa-play-circle fa-2x me-3"></i>
                                    <div class="fs-5">ভয়েস টেস্ট করুন</div>
                                    <small>ক্লিক করে ভয়েস আউটপুট চেক করুন</small>
                                </button>
                                <div class="mt-3">
                                    <small class="text-white-50">ব্রাউজারের অডিও সক্ষম করুন এবং ভলিউম চেক করুন</small>
                                </div>
                            </div>
                        </div>
                        
                        <div class="mt-4">
                            <a href="routine.php" class="btn btn-secondary">
                                <i class="fas fa-arrow-left me-2"></i> ক্লাস রুটিনে ফিরুন
                            </a>
                            <a href="../view_teacher_schedule.php" class="btn btn-info">
                                <i class="fas fa-calendar-check me-2"></i> শিক্ষকের সময়সূচী দেখুন
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function testVoiceAlert() {
            // Create a test message in Bengali
            const message = "এটি একটি টেস্ট ভয়েস নোটিফিকেশন। ভয়েস সিস্টেম সঠিকভাবে কাজ করছে।";
            
            // Check if browser supports speech synthesis
            if ('speechSynthesis' in window) {
                // Wait for voices to be loaded
                if (speechSynthesis.getVoices().length === 0) {
                    // If no voices available yet, wait for the voiceschanged event
                    document.addEventListener('DOMContentLoaded', function() {
                        speechSynthesis.onvoiceschanged = function() {
                            speakWithBengaliVoice(message);
                        };
                    });
                    
                    // Also try a timeout as backup
                    setTimeout(function() {
                        if (speechSynthesis.getVoices().length === 0) {
                            // If still no voices after waiting, use default
                            speakWithDefaultVoice(message);
                        }
                    }, 1000);
                } else {
                    // Voices are already available, proceed directly
                    speakWithBengaliVoice(message);
                }
            } else {
                alert('আপনার ব্রাউজার ভয়েস সিনথেসিস সাপোর্ট করে না।');
            }
        }
        
        function speakWithBengaliVoice(message) {
            // Create a new speech synthesis utterance
            const utterance = new SpeechSynthesisUtterance(message);
            
            // Set language to Bengali
            utterance.lang = 'bn-BD';
            
            // Get voices after they are loaded
            const voices = speechSynthesis.getVoices();
            let bengaliVoice = null;
            
            // Look for Bengali voices first
            for (let i = 0; i < voices.length; i++) {
                if (voices[i].lang.toLowerCase().includes('bn') || 
                    voices[i].lang.toLowerCase().includes('bengali')) {
                    bengaliVoice = voices[i];
                    console.log('Found Bengali voice:', voices[i].name, voices[i].lang);
                    break;
                }
            }
            
            // If no Bengali voice found, look for Indian regional voices
            if (!bengaliVoice) {
                for (let i = 0; i < voices.length; i++) {
                    if (voices[i].lang.toLowerCase().includes('in') || 
                        voices[i].lang.toLowerCase().includes('india')) {
                        bengaliVoice = voices[i];
                        console.log('Found India regional voice:', voices[i].name, voices[i].lang);
                        break;
                    }
                }
            }
            
            // If a Bengali voice is found, use it
            if (bengaliVoice) {
                utterance.voice = bengaliVoice;
                console.log('Using Bengali voice:', bengaliVoice.name, bengaliVoice.lang);
            } else {
                console.log('No Bengali voice found, using default voice');
                // If no Bengali voice is found, use the first available voice
                if (voices.length > 0) {
                    utterance.voice = voices[0];
                }
            }
            
            // Set other properties
            utterance.rate = 0.8; // Slightly slower for clarity
            utterance.pitch = 1.0;
            utterance.volume = 1.0;
            
            // Speak the message
            speechSynthesis.speak(utterance);
            
            // Show feedback
            alert('ভয়েস টেস্ট চালু হয়েছে। আপনার ডিভাইসে বাংলা ভয়েস আসা উচিত।');
        }
        
        function speakWithDefaultVoice(message) {
            // Fallback function when we can't wait for voices
            const utterance = new SpeechSynthesisUtterance(message);
            utterance.lang = 'bn-BD';
            utterance.rate = 0.8;
            utterance.pitch = 1.0;
            utterance.volume = 1.0;
            
            // Speak with default settings
            speechSynthesis.speak(utterance);
            
            alert('ভয়েস টেস্ট চালু হয়েছে। আপনার ডিভাইসে বাংলা ভয়েস আসা উচিত।');
        }
        
        // Also set up voiceschanged handler for when the page loads
        window.speechSynthesis.onvoiceschanged = function() {
            console.log('Voices loaded:', speechSynthesis.getVoices().length);
        };
    </script>
</body>
</html>