<?php
/**
 * Class Notification Handler
 * 
 * Handles VoIP notifications when a class is scheduled to start
 */

session_start();

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

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

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

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

// Get parameters from URL
$session_id = $_GET['session_id'] ?? null;
$class_id = $_GET['class_id'] ?? null;
$teacher_id = $_GET['teacher_id'] ?? null;

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

// Check if we have the required parameters
if ($session_id && $class_id && $teacher_id) {
    // Get session name
    $sessionStmt = $pdo->prepare("SELECT session_name FROM academic_sessions WHERE id = ?");
    $sessionStmt->execute([$session_id]);
    $session = $sessionStmt->fetch();
    
    // Get class information
    $classStmt = $pdo->prepare("SELECT name, section FROM classes WHERE id = ?");
    $classStmt->execute([$class_id]);
    $class = $classStmt->fetch();
    
    // Get teacher information
    $teacherStmt = $pdo->prepare("SELECT first_name, last_name, phone FROM teachers WHERE id = ?");
    $teacherStmt->execute([$teacher_id]);
    $teacher = $teacherStmt->fetch();
    
    // Get current day and time
    $currentDay = strtolower(date('l'));
    $currentTime = date('H:i:s');
    
    // Find class schedules for this teacher, class, and session that match the current day/time
    $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.teacher_id = ?
        AND t.class_id = ?
        AND t.academic_year = ?
        AND t.day_of_week = ?
        AND t.status = 'active'
        AND (
            (TIME(t.start_time) <= ? AND TIME(t.end_time) >= ?)  -- Class is currently ongoing
            OR (TIME(t.start_time) BETWEEN ? AND ?)  -- Class starts within next 5 minutes
        )
    ";
    
    $fiveMinutesLater = date('H:i:s', strtotime('+5 minutes'));
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        $teacher_id, 
        $class_id, 
        $session['session_name'] ?? '', 
        $currentDay, 
        $currentTime, 
        $currentTime, 
        $currentTime, 
        $fiveMinutesLater
    ]);
    
    $matchingClasses = $stmt->fetchAll();
    
    $notificationResults = [];
    
    if (!empty($matchingClasses)) {
        foreach ($matchingClasses as $class) {
            // Send VoIP notification for each matching class
            $result = $voipService->sendVoIPNotification(
                $class['teacher_phone'], 
                "অধ্যাপক, আপনার ক্লাস শুরু হবে অথবা চলছে: {$class['subject_name']} - {$class['class_name']} {$class['class_section']}। সময়: {$class['start_time']} - {$class['end_time']}। অনুগ্রহ করে ক্লাসে উপস্থিত থাকুন।"
            );
            
            $notificationResults[] = [
                'class' => $class['class_name'] . ' ' . $class['class_section'],
                'subject' => $class['subject_name'],
                'time' => $class['start_time'] . ' - ' . $class['end_time'],
                'result' => $result
            ];
        }
        
        $message = "নোটিফিকেশন পাঠানো হয়েছে! মিলেছে " . count($matchingClasses) . " টি ক্লাস।";
        $messageType = 'success';
    } else {
        $message = "এই মুহূর্তে কোনো মিলে যাওয়া ক্লাস পাওয়া যায়নি।";
        $messageType = 'info';
    }
} else {
    $message = "অপর্যাপ্ত প্যারামিটার। প্রয়োজন: session_id, class_id, teacher_id";
    $messageType = 'error';
}

?>

<!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">
</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="<?php echo ($user_role == 'teacher') ? 'dashboard.php' : '../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="<?php echo ($user_role == 'teacher') ? 'dashboard.php' : '../index.php'; ?>">
                            <i class="fas fa-home me-1"></i> হোম
                        </a>
                    </li>
                    <?php if ($user_role == 'admin'): ?>
                    <li class="nav-item">
                        <a class="nav-link" href="list.php">
                            <i class="fas fa-chalkboard-teacher me-1"></i> শিক্ষক তালিকা
                        </a>
                    </li>
                    <?php endif; ?>
                    <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-bell me-2"></i> ক্লাস নোটিফিকেশন</h5>
                    </div>
                    <div class="card-body">
                        <?php if (isset($message)): ?>
                            <div class="alert alert-<?php echo $messageType == 'error' ? 'danger' : ($messageType == 'success' ? 'success' : 'info'); ?> alert-dismissible fade show">
                                <i class="fas fa-<?php echo $messageType == 'error' ? 'exclamation-triangle' : ($messageType == 'success' ? 'check-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">
                                    <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>সেশন ID:</strong> <?php echo htmlspecialchars($session_id ?? 'N/A'); ?></p>
                                        <p><strong>ক্লাস ID:</strong> <?php echo htmlspecialchars($class_id ?? 'N/A'); ?></p>
                                        <p><strong>শিক্ষক ID:</strong> <?php echo htmlspecialchars($teacher_id ?? 'N/A'); ?></p>
                                        <p><strong>বর্তমান সময়:</strong> <?php echo date('Y-m-d H:i:s'); ?></p>
                                        <p><strong>বর্তমান দিন:</strong> <?php echo ucfirst(date('l')); ?></p>
                                    </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-history me-2"></i> নোটিফিকেশন তথ্য</h6>
                                    </div>
                                    <div class="card-body">
                                        <p><strong>নোটিফিকেশন পাঠানো হয়েছে:</strong> <?php echo count($notificationResults); ?></p>
                                        <p><strong>ব্যবহারকারী ভূমিকা:</strong> <?php echo htmlspecialchars($user_role); ?></p>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <?php if (!empty($notificationResults)): ?>
                            <div class="mt-4">
                                <h5><i class="fas fa-list me-2"></i> নোটিফিকেশন বিস্তারিত</h5>
                                <div class="table-responsive">
                                    <table class="table table-striped">
                                        <thead>
                                            <tr>
                                                <th>ক্লাস</th>
                                                <th>বিষয়</th>
                                                <th>সময়</th>
                                                <th>অবস্থা</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($notificationResults as $result): ?>
                                                <tr>
                                                    <td><?php echo htmlspecialchars($result['class']); ?></td>
                                                    <td><?php echo htmlspecialchars($result['subject']); ?></td>
                                                    <td><?php echo $result['time']; ?></td>
                                                    <td>
                                                        <span class="badge bg-<?php echo $result['result']['success'] ? 'success' : 'danger'; ?>">
                                                            <?php echo $result['result']['success'] ? 'সফল' : 'ব্যর্থ'; ?>
                                                        </span>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        <?php endif; ?>

                        <div class="mt-4">
                            <a href="routine.php" class="btn btn-primary">
                                <i class="fas fa-calendar-alt 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>
</body>
</html>