<?php
define('SECURE_ACCESS', true);

$pageTitle = "Notifications Control Panel";
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/auth.php';

requireAdmin();

$currentUser = getCurrentUser();

$error = '';
$success = '';
$activeTab = $_GET['tab'] ?? 'templates';

if ($activeTab === 'channels') {
    header("Location: settings?tab=channels");
    exit();
}

// 2. Handle Template Builder Submit
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $_SESSION['flash_error'] = "Security check failed (CSRF). Please try again.";
        header("Location: notifications?tab=" . urlencode($activeTab));
        exit();
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_template'])) {
    $template_id = (int)$_POST['template_id'];
    $subject = trim($_POST['subject'] ?? '');
    $body = trim($_POST['body'] ?? '');
    
    // Collect active channels and validate against whitelist
    $channels_selected = $_POST['channels'] ?? [];
    if (!is_array($channels_selected)) {
        $channels_selected = $channels_selected ? [$channels_selected] : [];
    }
    $allowed_channels = ['in_app', 'email', 'sms', 'whatsapp'];
    $channels_selected = array_intersect($channels_selected, $allowed_channels);
    $channels_csv = implode(',', $channels_selected);

    if (empty($body)) {
        $error = "Template body cannot be empty.";
    } else {
        try {
            $stmt = $pdo->prepare("UPDATE notification_templates SET subject = ?, body = ?, channels_csv = ? WHERE id = ?");
            $stmt->execute([$subject, $body, $channels_csv, $template_id]);
            $_SESSION['flash_success'] = "Template configuration updated successfully.";
            header("Location: notifications?tab=templates");
            exit();
        } catch (PDOException $e) {
            error_log("Template update error: " . $e->getMessage());
            $error = "Failed to update template. Please try again.";
        }
    }
}

// 3. Handle Template Deletion
if (isset($_GET['action']) && $_GET['action'] === 'delete_template' && isset($_GET['id'])) {
    if (!verifyCSRFToken($_GET['csrf_token'] ?? '')) {
        $_SESSION['flash_error'] = "Security check failed (CSRF). Please try again.";
        header("Location: notifications?tab=templates");
        exit();
    }
    $deleteId = (int)$_GET['id'];
    try {
        $stmt = $pdo->prepare("DELETE FROM notification_templates WHERE id = ?");
        $stmt->execute([$deleteId]);
        $_SESSION['flash_success'] = "Notification template deleted successfully.";
    } catch (PDOException $e) {
        $_SESSION['flash_error'] = "Failed to delete template: " . $e->getMessage();
    }
    header("Location: notifications?tab=templates");
    exit();
}

// 3.5 Handle Clear Delivery Logs
if (isset($_GET['action']) && $_GET['action'] === 'clear_logs') {
    if (!verifyCSRFToken($_GET['csrf_token'] ?? '')) {
        $_SESSION['flash_error'] = "Security check failed (CSRF). Please try again.";
        header("Location: notifications?tab=logs");
        exit();
    }
    try {
        $pdo->exec("TRUNCATE TABLE notifications CASCADE");
        logAuditEvent('admin_clear_notifications', 'notifications', null, 'Truncated all notifications logs');
        $_SESSION['flash_success'] = "All delivery logs cleared successfully.";
    } catch (PDOException $e) {
        error_log("Notifications clear log error: " . $e->getMessage());
        $_SESSION['flash_error'] = "Failed to clear logs. Please try again.";
    }
    header("Location: notifications?tab=logs");
    exit();
}

// 4. Handle Create Template
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_template'])) {
    $template_name = preg_replace('/[^a-z0-9_]/', '', strtolower(trim($_POST['template_name'] ?? '')));
    $subject = trim($_POST['subject'] ?? '');
    $body = trim($_POST['body'] ?? '');
    $channels_selected = $_POST['channels'] ?? [];
    if (!is_array($channels_selected)) {
        $channels_selected = $channels_selected ? [$channels_selected] : [];
    }
    $allowed_channels = ['in_app', 'email', 'sms', 'whatsapp'];
    $channels_selected = array_intersect($channels_selected, $allowed_channels);
    $channels_csv = implode(',', $channels_selected);

    if (empty($template_name) || empty($body)) {
        $error = "Please fill in all required fields.";
    } else {
        try {
            $stmt = $pdo->prepare("INSERT INTO notification_templates (template_name, subject, body, channels_csv) VALUES (?, ?, ?, ?)");
            $stmt->execute([$template_name, $subject, $body, $channels_csv]);
            $_SESSION['flash_success'] = "Custom template '$template_name' created successfully.";
            header("Location: notifications?tab=templates");
            exit();
        } catch (PDOException $e) {
            $error = "Failed to create template: " . $e->getMessage();
        }
    }
}

// 5. Handle Manual Dispatch
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['manual_dispatch'])) {
    $template_name = trim($_POST['template_name'] ?? '');
    $target_recipient = trim($_POST['recipient'] ?? 'all');
    
    $custom_placeholder_1 = trim($_POST['placeholder_key_1'] ?? '');
    $custom_placeholder_val_1 = trim($_POST['placeholder_val_1'] ?? '');
    
    $placeholders = [];
    if (!empty($custom_placeholder_1)) {
        $placeholders[$custom_placeholder_1] = $custom_placeholder_val_1;
    }
    $placeholders['event_title'] = trim($_POST['event_title'] ?? 'Mock Annual Tech Gala');
    $placeholders['location'] = trim($_POST['location'] ?? 'Virtual Hub');
    $placeholders['start_date'] = trim($_POST['start_date'] ?? date('M d, H:i'));
    $placeholders['status'] = trim($_POST['status'] ?? 'Active');
    $placeholders['amount'] = trim($_POST['amount'] ?? '250.00');

    require_once __DIR__ . '/../../includes/notification_helper.php';

    try {
        if ($target_recipient === 'all') {
            $stmt = $pdo->query("SELECT id FROM users");
            $users = $stmt->fetchAll(PDO::FETCH_COLUMN);
            $count = 0;
            foreach ($users as $uid) {
                if (sendMultichannelNotification($uid, $template_name, $placeholders)) {
                    $count++;
                }
            }
            $_SESSION['flash_success'] = "Manually dispatched notification to $count users.";
        } else {
            $uid = (int)$target_recipient;
            if (sendMultichannelNotification($uid, $template_name, $placeholders)) {
                $_SESSION['flash_success'] = "Manually dispatched notification to 1 user.";
            } else {
                $error = "Failed to dispatch notification.";
            }
        }
        if (empty($error)) {
            header("Location: notifications?tab=logs");
            exit();
        }
    } catch (PDOException $e) {
        $error = "Manual dispatch failed: " . $e->getMessage();
    }
}

// 6. Fetch data for tabs
$channels = [];
$templates = [];
$dispatch_logs = [];
$users_list = [];

try {
    // Channels
    $stmt = $pdo->query("SELECT * FROM notification_channels ORDER BY id ASC");
    $channels = $stmt->fetchAll(PDO::FETCH_UNIQUE);

    // Templates
    $stmt = $pdo->query("SELECT * FROM notification_templates ORDER BY id ASC");
    $templates = $stmt->fetchAll();

    // Logs (Paginated & Filtered)
    $logSearch = trim($_GET['log_search'] ?? '');
    $logChannel = trim($_GET['log_channel'] ?? '');
    
    $whereConditions = [];
    $whereParams = [];
    
    if (!empty($logSearch)) {
        $whereConditions[] = "(u.username ILIKE :search OR u.email ILIKE :search OR n.title ILIKE :search OR n.message ILIKE :search)";
        $whereParams['search'] = '%' . $logSearch . '%';
    }
    
    if (!empty($logChannel)) {
        $whereConditions[] = "n.channels_sent ILIKE :channel";
        $whereParams['channel'] = '%' . $logChannel . '%';
    }
    
    $whereClause = "";
    if (!empty($whereConditions)) {
        $whereClause = " WHERE " . implode(" AND ", $whereConditions);
    }
    
    $limit = 10;
    $page = isset($_GET['page']) && $activeTab === 'logs' ? max(1, (int)$_GET['page']) : 1;
    $offset = ($page - 1) * $limit;
    $total_records = 0;
    $total_pages = 0;

    $count_sql = "SELECT COUNT(*) FROM notifications n JOIN users u ON n.user_id = u.id" . $whereClause;
    $stmt_count = $pdo->prepare($count_sql);
    $stmt_count->execute($whereParams);
    $total_records = (int)$stmt_count->fetchColumn() ?: 0;
    $total_pages = ceil($total_records / $limit);

    $stmt_logs = $pdo->prepare("
        SELECT n.*, u.username, u.email 
        FROM notifications n 
        JOIN users u ON n.user_id = u.id 
        $whereClause
        ORDER BY n.created_at DESC 
        LIMIT $limit OFFSET $offset
    ");
    $stmt_logs->execute($whereParams);
    $dispatch_logs = $stmt_logs->fetchAll();

    // Fetch users for manual trigger selection
    $stmt_users = $pdo->query("SELECT id, username, email FROM users ORDER BY username ASC");
    $users_list = $stmt_users->fetchAll();
} catch (PDOException $e) {
    $error = "Failed to load notification settings: " . $e->getMessage();
}

include __DIR__ . '/../../includes/header.php';
?>

<div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-3 mb-4">
    <div>
        <h1 class="h2 fw-bold text-dark mb-1">Notifications Control Center</h1>
        <p class="text-muted mb-0">Configure multichannel endpoints, design message templates, and track delivery reports.</p>
    </div>
</div>

<?php if (!empty($error)): ?>
    <div class="alert alert-danger alert-dismissible fade show shadow-sm border-0 mb-4" role="alert">
        <i class="bi bi-x-circle-fill me-2"></i>
        <?php echo htmlspecialchars($error); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<!-- Tabs Navigation -->
<div class="table-responsive mb-4">
    <ul class="nav nav-tabs flex-nowrap" id="notificationTabs" role="tablist" style="border-bottom: 2px solid #dee2e6;">

        <li class="nav-item" role="presentation">
            <a class="nav-link <?php echo $activeTab === 'templates' ? 'active fw-bold text-primary' : 'text-muted'; ?>" href="notifications?tab=templates">
                <i class="bi bi-envelope-paper-fill me-1"></i> Template Builder
            </a>
        </li>
        <li class="nav-item" role="presentation">
            <a class="nav-link <?php echo $activeTab === 'logs' ? 'active fw-bold text-primary' : 'text-muted'; ?>" href="notifications?tab=logs">
                <i class="bi bi-terminal-fill me-1"></i> Delivery Logs
            </a>
        </li>
    </ul>
</div>

<div class="row g-4">
    


    <!-- Tab 2: Template Builder -->
    <?php if ($activeTab === 'templates'): ?>
        <div class="col-12">
            <div class="row align-items-center mb-3 g-2">
                <div class="col-12 col-md-6">
                    <h5 class="fw-bold mb-0 text-dark">Notification Message Templates</h5>
                </div>
                <div class="col-12 col-md-6 d-flex gap-2 justify-content-md-end mt-2 mt-md-0">
                    <div class="input-group input-group-sm" style="max-width: 250px;">
                        <span class="input-group-text bg-white border-end-0 text-muted"><i class="bi bi-search"></i></span>
                        <input type="text" id="templateSearch" class="form-control border-start-0 ps-0" placeholder="Search templates...">
                    </div>
                    <button class="btn btn-primary btn-sm px-3 fw-bold shadow-sm" data-bs-toggle="modal" data-bs-target="#createTemplateModal">
                        <i class="bi bi-plus-circle me-1"></i> Add Custom Template
                    </button>
                </div>
            </div>
            
            <div class="row g-4">
                <?php foreach ($templates as $temp): 
                    $temp_chans = array_filter(array_map('trim', explode(',', $temp['channels_csv'])));
                    $is_core = in_array($temp['template_name'], ['event_registration', 'kyc_status', 'payout_status', 'event_reminder']);
                ?>
                    <div class="col-12 col-xl-6 template-card-container" data-name="<?php echo htmlspecialchars($temp['template_name']); ?>" data-subject="<?php echo htmlspecialchars($temp['subject'] ?? ''); ?>">
                        <div class="card border-0 shadow-sm h-100">
                            <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
                                <h6 class="mb-0 fw-bold text-dark">
                                    <i class="bi bi-envelope-paper me-2 text-primary"></i>
                                    <?php echo $is_core ? 'System Trigger' : 'Custom Template'; ?>: 
                                    <strong><?php echo htmlspecialchars($temp['template_name']); ?></strong>
                                </h6>
                                <div class="d-flex gap-1">
                                    <button type="button" class="btn btn-xs btn-outline-success py-1 px-2 font-monospace text-uppercase" style="font-size: 0.7rem;" data-bs-toggle="modal" data-bs-target="#sendNotificationModal" data-template-name="<?php echo htmlspecialchars($temp['template_name']); ?>">
                                        <i class="bi bi-send me-1"></i>Send
                                    </button>
                                    <?php if (!$is_core): ?>
                                        <a href="notifications?tab=templates&action=delete_template&id=<?php echo $temp['id']; ?>&csrf_token=<?php echo getCSRFToken(); ?>" class="btn btn-xs btn-outline-danger py-1 px-2 font-monospace text-uppercase" style="font-size: 0.7rem;" onclick="return confirm('Delete this custom template?');">
                                            <i class="bi bi-trash"></i> Delete
                                        </a>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="card-body p-4">
                                <form method="POST" action="notifications?tab=templates">
                                    <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                                    <input type="hidden" name="template_id" value="<?php echo $temp['id']; ?>">
                                    
                                    <div class="mb-3">
                                        <label class="form-label small fw-bold">Email/Push Subject</label>
                                        <input type="text" class="form-control form-control-sm" name="subject" required value="<?php echo htmlspecialchars($temp['subject'] ?? ''); ?>">
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label small fw-bold">Message Template Body</label>
                                        <textarea class="form-control form-control-sm" name="body" id="body-<?php echo $temp['id']; ?>" rows="4" required><?php echo htmlspecialchars($temp['body']); ?></textarea>
                                        <div class="form-text small text-secondary mt-1">
                                            Supported Placeholder Tokens (Drag & Drop or Click to Insert): 
                                            <span class="badge bg-secondary-subtle text-secondary-emphasis font-monospace token-badge" style="cursor: grab;" draggable="true" ondragstart="event.dataTransfer.setData('text/plain', '{{username}}')" onclick="insertPlaceholder('body-<?php echo $temp['id']; ?>', '{{username}}')">{{username}}</span>
                                            <span class="badge bg-secondary-subtle text-secondary-emphasis font-monospace token-badge" style="cursor: grab;" draggable="true" ondragstart="event.dataTransfer.setData('text/plain', '{{email}}')" onclick="insertPlaceholder('body-<?php echo $temp['id']; ?>', '{{email}}')">{{email}}</span>
                                            <?php if ($temp['template_name'] === 'event_registration' || $temp['template_name'] === 'event_reminder'): ?>
                                                <span class="badge bg-secondary-subtle text-secondary-emphasis font-monospace token-badge" style="cursor: grab;" draggable="true" ondragstart="event.dataTransfer.setData('text/plain', '{{event_title}}')" onclick="insertPlaceholder('body-<?php echo $temp['id']; ?>', '{{event_title}}')">{{event_title}}</span>
                                                <span class="badge bg-secondary-subtle text-secondary-emphasis font-monospace token-badge" style="cursor: grab;" draggable="true" ondragstart="event.dataTransfer.setData('text/plain', '{{location}}')" onclick="insertPlaceholder('body-<?php echo $temp['id']; ?>', '{{location}}')">{{location}}</span>
                                                <span class="badge bg-secondary-subtle text-secondary-emphasis font-monospace token-badge" style="cursor: grab;" draggable="true" ondragstart="event.dataTransfer.setData('text/plain', '{{start_date}}')" onclick="insertPlaceholder('body-<?php echo $temp['id']; ?>', '{{start_date}}')">{{start_date}}</span>
                                            <?php elseif ($temp['template_name'] === 'kyc_status'): ?>
                                                <span class="badge bg-secondary-subtle text-secondary-emphasis font-monospace token-badge" style="cursor: grab;" draggable="true" ondragstart="event.dataTransfer.setData('text/plain', '{{status}}')" onclick="insertPlaceholder('body-<?php echo $temp['id']; ?>', '{{status}}')">{{status}}</span>
                                            <?php elseif ($temp['template_name'] === 'payout_status'): ?>
                                                <span class="badge bg-secondary-subtle text-secondary-emphasis font-monospace token-badge" style="cursor: grab;" draggable="true" ondragstart="event.dataTransfer.setData('text/plain', '{{amount}}')" onclick="insertPlaceholder('body-<?php echo $temp['id']; ?>', '{{amount}}')">{{amount}}</span>
                                                <span class="badge bg-secondary-subtle text-secondary-emphasis font-monospace token-badge" style="cursor: grab;" draggable="true" ondragstart="event.dataTransfer.setData('text/plain', '{{status}}')" onclick="insertPlaceholder('body-<?php echo $temp['id']; ?>', '{{status}}')">{{status}}</span>
                                            <?php endif; ?>
                                        </div>
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label small fw-bold d-block">Active Dispatch Channels</label>
                                        <div class="d-flex flex-wrap gap-3">
                                            <?php foreach (['email' => 'SMTP', 'in_app' => 'In-App', 'sms' => 'SMS', 'whatsapp' => 'WhatsApp', 'telegram' => 'Telegram', 'push' => 'Push'] as $key => $lbl): ?>
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" name="channels[]" value="<?php echo $key; ?>" id="chan-<?php echo $temp['id']; ?>-<?php echo $key; ?>" <?php echo in_array($key, $temp_chans) ? 'checked' : ''; ?>>
                                                    <label class="form-check-label text-dark small" for="chan-<?php echo $temp['id']; ?>-<?php echo $key; ?>"><?php echo $lbl; ?></label>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>

                                    <button type="submit" name="save_template" class="btn btn-primary btn-sm"><i class="bi bi-save me-1"></i>Save Template Changes</button>
                                </form>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- Create Template Modal -->
        <div class="modal fade" id="createTemplateModal" tabindex="-1" aria-labelledby="createTemplateModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content border-0 shadow-lg">
                    <div class="modal-header border-0 pb-0">
                        <h5 class="modal-title fw-bold text-dark" id="createTemplateModalLabel"><i class="bi bi-plus-circle me-1 text-primary"></i> Create Message Template</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <form method="POST" action="notifications?tab=templates">
                        <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                        <div class="modal-body py-4">
                            <div class="mb-3">
                                <label for="template_name" class="form-label small fw-bold">Template Handle (Key) <span class="text-danger">*</span></label>
                                <input type="text" class="form-control form-control-sm font-monospace" id="template_name" name="template_name" required placeholder="e.g. registration_discount_notice">
                                <div class="form-text small text-muted">Use lowercase alphanumeric and underscores only.</div>
                            </div>
                            <div class="mb-3">
                                <label for="tpl_subject" class="form-label small fw-bold">Default Email/Push Subject</label>
                                <input type="text" class="form-control form-control-sm" id="tpl_subject" name="subject" placeholder="e.g. Special Offer!">
                            </div>
                            <div class="mb-3">
                                <label for="tpl_body" class="form-label small fw-bold">Message Template Body <span class="text-danger">*</span></label>
                                <textarea class="form-control form-control-sm" id="tpl_body" name="body" rows="4" required placeholder="Hello {{username}}, we have a special announcement..."></textarea>
                                <div class="form-text small text-secondary mt-1">
                                    Supported Placeholder Tokens (Drag & Drop or Click to Insert): 
                                    <span class="badge bg-secondary-subtle text-secondary-emphasis font-monospace token-badge" style="cursor: grab;" draggable="true" ondragstart="event.dataTransfer.setData('text/plain', '{{username}}')" onclick="insertPlaceholder('tpl_body', '{{username}}')">{{username}}</span>
                                    <span class="badge bg-secondary-subtle text-secondary-emphasis font-monospace token-badge" style="cursor: grab;" draggable="true" ondragstart="event.dataTransfer.setData('text/plain', '{{email}}')" onclick="insertPlaceholder('tpl_body', '{{email}}')">{{email}}</span>
                                    <span class="badge bg-secondary-subtle text-secondary-emphasis font-monospace token-badge" style="cursor: grab;" draggable="true" ondragstart="event.dataTransfer.setData('text/plain', '{{event_title}}')" onclick="insertPlaceholder('tpl_body', '{{event_title}}')">{{event_title}}</span>
                                    <span class="badge bg-secondary-subtle text-secondary-emphasis font-monospace token-badge" style="cursor: grab;" draggable="true" ondragstart="event.dataTransfer.setData('text/plain', '{{location}}')" onclick="insertPlaceholder('tpl_body', '{{location}}')">{{location}}</span>
                                    <span class="badge bg-secondary-subtle text-secondary-emphasis font-monospace token-badge" style="cursor: grab;" draggable="true" ondragstart="event.dataTransfer.setData('text/plain', '{{start_date}}')" onclick="insertPlaceholder('tpl_body', '{{start_date}}')">{{start_date}}</span>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label small fw-bold d-block">Channels to Dispatch</label>
                                <div class="d-flex flex-wrap gap-3">
                                    <?php foreach (['email' => 'SMTP', 'in_app' => 'In-App', 'sms' => 'SMS', 'whatsapp' => 'WhatsApp', 'telegram' => 'Telegram', 'push' => 'Push'] as $key => $lbl): ?>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" name="channels[]" value="<?php echo $key; ?>" id="newchan-<?php echo $key; ?>" checked>
                                            <label class="form-check-label text-dark small" for="newchan-<?php echo $key; ?>"><?php echo $lbl; ?></label>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer border-0 pt-0">
                            <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                            <button type="submit" name="create_template" class="btn btn-sm btn-primary fw-bold px-3">Create Template</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Send Notification Modal -->
        <div class="modal fade" id="sendNotificationModal" tabindex="-1" aria-labelledby="sendNotificationModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content border-0 shadow-lg">
                    <div class="modal-header border-0 pb-0">
                        <h5 class="modal-title fw-bold text-dark" id="sendNotificationModalLabel"><i class="bi bi-send me-1 text-success"></i> Dispatch Manual Notification</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <form method="POST" action="notifications?tab=templates">
                        <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                        <input type="hidden" name="template_name" id="modal_template_name">
                        <div class="modal-body py-4">
                            <p class="text-secondary small">You are manually triggering the template: <strong id="modal_template_display" class="text-dark"></strong></p>
                            
                            <div class="mb-3">
                                <label for="recipient" class="form-label small fw-bold">Select Target Recipient <span class="text-danger">*</span></label>
                                <select class="form-select form-select-sm" id="recipient" name="recipient" required>
                                    <option value="all">All Registered Users (BroadCast)</option>
                                    <?php foreach ($users_list as $usr): ?>
                                        <option value="<?php echo $usr['id']; ?>"><?php echo htmlspecialchars($usr['username']); ?> (<?php echo htmlspecialchars($usr['email']); ?>)</option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <h6 class="fw-bold mb-2 small text-secondary text-uppercase font-monospace" style="font-size: 0.7rem;">Inject Template Placeholder Tokens</h6>
                            <div class="row g-2 mb-3">
                                <div class="col-6">
                                    <label class="form-label small text-muted font-monospace" style="font-size: 0.65rem;">Token Key (e.g. promo_code)</label>
                                    <input type="text" class="form-control form-control-sm font-monospace" name="placeholder_key_1" placeholder="promo_code">
                                </div>
                                <div class="col-6">
                                    <label class="form-label small text-muted font-monospace" style="font-size: 0.65rem;">Token Value</label>
                                    <input type="text" class="form-control form-control-sm font-monospace" name="placeholder_val_1" placeholder="SAVE50">
                                </div>
                            </div>

                            <h6 class="fw-bold mb-2 small text-secondary text-uppercase font-monospace" style="font-size: 0.7rem;">Default Mocking Variables</h6>
                            <div class="row g-2 mb-2">
                                <div class="col-6">
                                    <label for="mock_title" class="form-label small text-muted" style="font-size: 0.7rem;">{{event_title}}</label>
                                    <input type="text" class="form-control form-control-sm" id="mock_title" name="event_title" value="Annual Tech Expo 2026">
                                </div>
                                <div class="col-6">
                                    <label for="mock_loc" class="form-label small text-muted" style="font-size: 0.7rem;">{{location}}</label>
                                    <input type="text" class="form-control form-control-sm" id="mock_loc" name="location" value="Grand Center Auditorium">
                                </div>
                            </div>
                            <div class="row g-2 mb-2">
                                <div class="col-6">
                                    <label for="mock_amt" class="form-label small text-muted" style="font-size: 0.7rem;">{{amount}}</label>
                                    <input type="text" class="form-control form-control-sm" id="mock_amt" name="amount" value="350.00">
                                </div>
                                <div class="col-6">
                                    <label for="mock_stat" class="form-label small text-muted" style="font-size: 0.7rem;">{{status}}</label>
                                    <input type="text" class="form-control form-control-sm" id="mock_stat" name="status" value="Approved">
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer border-0 pt-0">
                            <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                            <button type="submit" name="manual_dispatch" class="btn btn-sm btn-success text-white fw-bold px-3">Dispatch Now</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <script>
            document.addEventListener('DOMContentLoaded', function() {
                const sendModal = document.getElementById('sendNotificationModal');
                if (sendModal) {
                    sendModal.addEventListener('show.bs.modal', function(event) {
                        const button = event.relatedTarget;
                        const templateName = button.getAttribute('data-template-name');
                        const inputTemplateName = sendModal.querySelector('#modal_template_name');
                        const displayTemplateName = sendModal.querySelector('#modal_template_display');
                        if (inputTemplateName) inputTemplateName.value = templateName;
                        if (displayTemplateName) displayTemplateName.textContent = templateName;
                    });
                }
            });
        </script>
    <?php endif; ?>

    <!-- Tab 3: Delivery Logs -->
    <?php if ($activeTab === 'logs'): ?>
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-bottom py-3">
                    <form method="GET" action="notifications" class="row g-2 align-items-center">
                        <input type="hidden" name="tab" value="logs">
                        <div class="col-12 col-md-4">
                            <h5 class="mb-0 fw-bold text-dark"><i class="bi bi-terminal-fill me-2 text-primary"></i>Multichannel Delivery Logs</h5>
                        </div>
                        <div class="col-12 col-md-5 d-flex gap-2">
                            <div class="input-group input-group-sm">
                                <span class="input-group-text bg-white border-end-0 text-muted"><i class="bi bi-search"></i></span>
                                <input type="text" name="log_search" class="form-control border-start-0 ps-0" placeholder="Search logs (user, message...)" value="<?php echo htmlspecialchars($_GET['log_search'] ?? ''); ?>">
                            </div>
                            <select name="log_channel" class="form-select form-select-sm" style="max-width: 130px;" onchange="this.form.submit()">
                                <option value="">All Channels</option>
                                <?php foreach (['email' => 'SMTP', 'in_app' => 'In-App', 'sms' => 'SMS', 'whatsapp' => 'WhatsApp', 'telegram' => 'Telegram', 'push' => 'Push'] as $c_key => $c_lbl): ?>
                                    <option value="<?php echo $c_key; ?>" <?php echo ($_GET['log_channel'] ?? '') === $c_key ? 'selected' : ''; ?>><?php echo $c_lbl; ?></option>
                                <?php endforeach; ?>
                            </select>
                            <button type="submit" class="btn btn-primary btn-sm fw-bold">Filter</button>
                            <?php if (!empty($_GET['log_search']) || !empty($_GET['log_channel'])): ?>
                                <a href="notifications?tab=logs" class="btn btn-outline-secondary btn-sm fw-bold"><i class="bi bi-x-lg"></i></a>
                            <?php endif; ?>
                        </div>
                        <div class="col-12 col-md-3 text-md-end">
                            <a href="notifications?tab=logs&action=clear_logs&csrf_token=<?php echo getCSRFToken(); ?>" class="btn btn-danger btn-sm fw-bold shadow-sm" onclick="return confirm('WARNING: Are you sure you want to clear all delivery logs? This cannot be undone.');">
                                <i class="bi bi-trash-fill me-1"></i> Clear Logs
                            </a>
                        </div>
                    </form>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0" style="font-size: 0.9rem;">
                            <thead class="table-light text-muted uppercase font-monospace" style="font-size: 0.75rem;">
                                <tr>
                                    <th class="ps-4">Recipient</th>
                                    <th>Subject & Message Body</th>
                                    <th>Dispatched Channels</th>
                                    <th>Execution Date</th>
                                    <th class="text-end pe-4">Payload Inspector</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($dispatch_logs)): ?>
                                    <tr>
                                        <td colspan="5" class="text-center py-5 text-muted">
                                            <i class="bi bi-terminal fs-1 mb-2"></i>
                                            <p class="mb-0">No notification logs recorded.</p>
                                        </td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($dispatch_logs as $log): 
                                        $channels_arr = array_filter(array_map('trim', explode(',', $log['channels_sent'])));
                                        $logs_data = json_decode($log['delivery_logs'] ?? '{}', true) ?: [];
                                    ?>
                                        <tr>
                                            <!-- Recipient -->
                                            <td class="ps-4">
                                                <strong class="text-dark d-block"><?php echo htmlspecialchars($log['username']); ?></strong>
                                                <span class="text-muted small"><?php echo htmlspecialchars($log['email']); ?></span>
                                            </td>

                                            <!-- Subject / Message -->
                                            <td style="max-width: 300px;">
                                                <strong class="text-dark d-block mb-1 text-truncate"><?php echo htmlspecialchars($log['title']); ?></strong>
                                                <p class="text-secondary small mb-0 text-truncate-2"><?php echo htmlspecialchars($log['message']); ?></p>
                                            </td>

                                            <!-- Dispatched Channels -->
                                            <td>
                                                <div class="d-flex flex-wrap gap-1">
                                                    <?php foreach ($channels_arr as $c): ?>
                                                        <span class="badge bg-light text-dark border font-monospace text-uppercase" style="font-size: 0.65rem;">
                                                            <?php echo $c; ?>
                                                        </span>
                                                    <?php endforeach; ?>
                                                </div>
                                            </td>

                                            <!-- Date -->
                                            <td>
                                                <span class="text-muted small font-monospace"><?php echo date('Y-m-d H:i', strtotime($log['created_at'])); ?></span>
                                            </td>

                                            <!-- Inspector Action -->
                                            <td class="text-end pe-4">
                                                <button class="btn btn-outline-primary btn-sm py-1 px-2" type="button" data-bs-toggle="collapse" data-bs-target="#payload-<?php echo $log['id']; ?>" aria-expanded="false">
                                                    <i class="bi bi-code-slash me-1"></i> Inspect
                                                </button>
                                            </td>
                                        </tr>

                                        <!-- Hidden expandable details block for JSON inspection -->
                                        <tr class="collapse" id="payload-<?php echo $log['id']; ?>">
                                            <td colspan="5" class="bg-light p-4 border-bottom">
                                                <h6 class="fw-bold mb-2 font-monospace text-primary" style="font-size: 0.8rem;">Multichannel Gateway JSON Responses & Latencies</h6>
                                                <pre class="bg-dark text-success p-3 rounded font-monospace small mb-0" style="max-height: 250px; overflow-y: auto;"><?php 
                                                    echo htmlspecialchars(json_encode($logs_data, JSON_PRETTY_PRINT)); 
                                                ?></pre>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                </div>
                <?php if ($total_pages > 1): ?>
                    <div class="card-footer bg-light border-top py-3 d-flex flex-column flex-md-row justify-content-between align-items-center gap-3">
                        <div class="small text-secondary font-monospace">
                            Showing <?php echo $offset + 1; ?> to <?php echo min($offset + $limit, $total_records); ?> of <?php echo $total_records; ?> logs
                        </div>
                        <nav aria-label="Page navigation">
                            <ul class="pagination pagination-sm mb-0">
                                <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>"><i class="bi bi-chevron-left"></i></a>
                                </li>
                                <?php
                                $start = max(1, $page - 2);
                                $end = min($total_pages, $page + 2);
                                for ($i = $start; $i <= $end; $i++):
                                ?>
                                    <li class="page-item <?php echo $page === $i ? 'active' : ''; ?>">
                                        <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>"><?php echo $i; ?></a>
                                    </li>
                                <?php endfor; ?>
                                <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>"><i class="bi bi-chevron-right"></i></a>
                                </li>
                            </ul>
                        </nav>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    <?php endif; ?>

</div>

<script>
function insertPlaceholder(textareaId, placeholderText) {
    const textarea = document.getElementById(textareaId);
    if (!textarea) return;
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const text = textarea.value;
    const before = text.substring(0, start);
    const after  = text.substring(end, text.length);
    textarea.value = before + placeholderText + after;
    textarea.focus();
    textarea.selectionStart = textarea.selectionEnd = start + placeholderText.length;
}

document.addEventListener("DOMContentLoaded", function() {
    const textareas = document.querySelectorAll('textarea');
    textareas.forEach(textarea => {
        textarea.addEventListener('dragover', function(e) {
            e.preventDefault();
        });
        textarea.addEventListener('drop', function(e) {
            e.preventDefault();
            const data = e.dataTransfer.getData('text/plain');
            if (data && data.startsWith('{{') && data.endsWith('}}')) {
                const start = textarea.selectionStart;
                const end = textarea.selectionEnd;
                const text = textarea.value;
                const before = text.substring(0, start);
                const after  = text.substring(end, text.length);
                textarea.value = before + data + after;
                textarea.focus();
                textarea.selectionStart = textarea.selectionEnd = start + data.length;
            }
        });
        });
    });

    // Client-side Template live search
    const templateSearch = document.getElementById('templateSearch');
    if (templateSearch) {
        templateSearch.addEventListener('input', function(e) {
            const query = e.target.value.toLowerCase();
            document.querySelectorAll('.template-card-container').forEach(card => {
                const name = card.getAttribute('data-name').toLowerCase();
                const subject = card.getAttribute('data-subject').toLowerCase();
                if (name.includes(query) || subject.includes(query)) {
                    card.style.display = 'block';
                } else {
                    card.style.display = 'none';
                }
            });
        });
    }
});
</script>

<?php
include __DIR__ . '/../../includes/footer.php';
?>
