<?php
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/notification_helper.php';

try {
    $db = getDBConnection(true);

    // 1. Create a custom template
    $stmt = $db->prepare("INSERT INTO notification_templates (template_name, subject, body, channels_csv) VALUES (?, ?, ?, ?)");
    $stmt->execute(['test_verification_template', 'Welcome to {{event_title}}', 'Hello {{username}}, you are registered for {{event_title}} at {{location}}.', 'in_app,email']);
    
    // 2. Fetch and confirm
    $temp = $db->query("SELECT * FROM notification_templates WHERE template_name = 'test_verification_template'")->fetch();
    if (!$temp) {
        throw new Exception("Failed to insert custom template.");
    }
    
    // 3. Dispatch manual broadcast via template
    $user_id = $db->query("SELECT id FROM users LIMIT 1")->fetchColumn();
    if ($user_id) {
        $sent = sendMultichannelNotification($user_id, 'test_verification_template', [
            'event_title' => 'Deep Learning Summit 2026',
            'location' => 'Block C Auditoria'
        ]);
        if (!$sent) {
            throw new Exception("Failed to send template notification.");
        }
        
        // Check log entry
        $log = $db->query("SELECT * FROM notifications WHERE user_id = $user_id ORDER BY id DESC LIMIT 1")->fetch();
        if (strpos($log['message'], 'Deep Learning Summit 2026') === false) {
            throw new Exception("Log message placeholder replacement failed.");
        }
    }

    // 4. Delete the custom template
    $db->prepare("DELETE FROM notification_templates WHERE template_name = 'test_verification_template'")->execute();
    $temp_deleted = $db->query("SELECT COUNT(*) FROM notification_templates WHERE template_name = 'test_verification_template'")->fetchColumn();
    if ($temp_deleted > 0) {
        throw new Exception("Failed to delete custom template.");
    }

    echo "Notification Module Verification: SUCCESS!\n";
} catch (Exception $e) {
    echo "Notification Module Verification: FAILED: " . $e->getMessage() . "\n";
}
