<?php
/**
 * Trigger Class VoIP Notification
 * 
 * This script handles the specific URL mentioned in the request:
 * http://localhost/bidda/teachers/routine.php?session_id=8&class_id=12&teacher_id=8
 * 
 * This script will check if there's a class scheduled for the specified parameters
 * and send a VoIP notification to the teacher if the class is about to start.
 */

session_start();

// Include required files
require_once('config/database.php');
require_once('classes/VoIPNotificationService.php');
require_once('config/voip_settings.php');

// Check if VoIP is enabled
if (!VOIP_ENABLED) {
    http_response_code(503);
    die("VoIP notifications are disabled in configuration.");
}

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

// Validate parameters
if (!$session_id || !$class_id || !$teacher_id) {
    http_response_code(400);
    die("Missing required parameters: session_id, class_id, teacher_id");
}

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

// Get session name
$stmt = $pdo->prepare("SELECT session_name FROM academic_sessions WHERE id = ? AND status = 'active'");
$stmt->execute([$session_id]);
$session = $stmt->fetch();

if (!$session) {
    http_response_code(404);
    die("Session not found or inactive: $session_id");
}

// Get current day and time
$currentDay = strtolower(date('l'));
$currentTime = date('H:i:s');

// Find class schedules that match the criteria according to the routine
$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) = ?
";

$stmt = $pdo->prepare($sql);
$stmt->execute([
    $teacher_id, 
    $class_id, 
    $session['session_name'], 
    $currentDay, 
    $currentTime
]);

$matchingClasses = $stmt->fetchAll();

if (empty($matchingClasses)) {
    // No classes found that are happening now according to the routine
    echo "No classes found for teacher ID $teacher_id, class ID $class_id, and session ID $session_id that are starting exactly now according to the routine.\n";
    echo "Current time: " . date('Y-m-d H:i:s') . "\n";
    echo "Current day: " . ucfirst($currentDay) . "\n";
    echo "Parameters checked: session_id=$session_id, class_id=$class_id, teacher_id=$teacher_id\n";
    echo "Note: No routine class scheduled for this exact time means no VoIP announcement will occur.\n";
    http_response_code(200);
    exit();
}

// Send VoIP notifications for each matching class
$results = [];
foreach ($matchingClasses as $class) {
    $message = "অধ্যাপক, আপনার ক্লাস শুরু হবে অথবা চলছে: {$class['subject_name']} - {$class['class_name']} {$class['class_section']}। সময়: {$class['start_time']} - {$class['end_time']}। অনুগ্রহ করে ক্লাসে উপস্থিত থাকুন।";
    
    $result = $voipService->sendVoIPNotification($class['teacher_phone'], $message);
    
    $results[] = [
        'class' => $class['class_name'] . ' ' . $class['class_section'],
        'subject' => $class['subject_name'],
        'time' => $class['start_time'] . ' - ' . $class['end_time'],
        'result' => $result
    ];
}

// Return results
header('Content-Type: application/json');
echo json_encode([
    'status' => 'success',
    'message' => 'Notifications processed',
    'classes_matched' => count($matchingClasses),
    'notifications_sent' => count(array_filter($results, function($item) {
        return $item['result']['success'];
    })),
    'details' => $results
], JSON_UNESCAPED_UNICODE);

?>