<?php
// Enable error reporting for debugging (remove in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);

include 'layouts/session.php';
include 'layouts/main.php';
include 'layouts/dbconn.php';

// Check if user is logged in and has admin access
if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] !== 1) {
    header('Location: login.php');
    exit();
}

try {
    // Fetch templates
    $sql = "SELECT * FROM notification_templates ORDER BY template_name";
    $result = $conn->query($sql);
    if (!$result) {
        throw new Exception("Failed to fetch templates: " . $conn->error);
    }
    $templates = $result->fetch_all(MYSQLI_ASSOC);

    // Fetch all roles for recipient selection
    $sql = "SELECT role_id, role_name FROM user_role ORDER BY role_name";
    $result = $conn->query($sql);
    if (!$result) {
        throw new Exception("Failed to fetch roles: " . $conn->error);
    }
    $roles = $result->fetch_all(MYSQLI_ASSOC);

    // Fetch existing notification settings
    $sql = "SELECT ns.*, nt.template_name, CASE 
                WHEN ns.recipient_type = 'USER' THEN u.full_name
                WHEN ns.recipient_type = 'ROLE' THEN r.role_name
                ELSE ns.recipient_value
            END as recipient_name
            FROM notification_settings ns
            JOIN notification_templates nt ON ns.template_id = nt.template_id
            LEFT JOIN users u ON ns.recipient_type = 'USER' AND ns.recipient_value = u.user_id
            LEFT JOIN user_role r ON ns.recipient_type = 'ROLE' AND ns.recipient_value = r.role_id
            ORDER BY nt.template_name";
    $result = $conn->query($sql);
    if (!$result) {
        throw new Exception("Failed to fetch notification settings: " . $conn->error);
    }
    $settings = $result->fetch_all(MYSQLI_ASSOC);

    // Fetch users for dropdown
    $sql = "SELECT user_id, full_name FROM users ORDER BY full_name";
    $result = $conn->query($sql);
    if (!$result) {
        throw new Exception("Failed to fetch users: " . $conn->error);
    }
    $users = $result->fetch_all(MYSQLI_ASSOC);

} catch (Exception $e) {
    // Log error and show user-friendly message
    error_log("Notification Settings Error: " . $e->getMessage());
    $error_message = "Unable to load notification settings. Please contact system administrator.";
    $templates = [];
    $roles = [];
    $settings = [];
    $users = [];
}

?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Notification Settings')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Settings', 'title' => 'Notification Settings')); ?>

                    <?php if (isset($error_message)): ?>
                    <div class="row">
                        <div class="col-12">
                            <div class="alert alert-danger" role="alert">
                                <i class="ri-error-warning-line me-2"></i>
                                <?php echo $error_message; ?>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <!-- Templates Tab -->
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Notification Templates</h4>
                                    <div class="flex-shrink-0">
                                        <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addTemplateModal">
                                            <i class="ri-add-line align-middle me-1"></i> Add Template
                                        </button>
                                    </div>
                                </div>

                                <div class="card-body">
                                    <?php if (empty($templates)): ?>
                                    <div class="text-center py-4">
                                        <i class="ri-notification-2-line display-4 text-muted"></i>
                                        <h5 class="mt-3">No Templates Found</h5>
                                        <p class="text-muted">Create your first notification template to get started.</p>
                                    </div>
                                    <?php else: ?>
                                    <div class="table-responsive">
                                        <table class="table table-bordered">
                                            <thead>
                                                <tr>
                                                    <th>Template Name</th>
                                                    <th>Code</th>
                                                    <th>Days Before</th>
                                                    <th>Status</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($templates as $template): ?>
                                                <tr>
                                                    <td><?php echo htmlspecialchars($template['template_name']); ?></td>
                                                    <td><code><?php echo htmlspecialchars($template['template_code']); ?></code></td>
                                                    <td><?php echo $template['days_before']; ?></td>
                                                    <td>
                                                        <span class="badge bg-<?php echo $template['is_active'] ? 'success' : 'danger'; ?>">
                                                            <?php echo $template['is_active'] ? 'Active' : 'Inactive'; ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <div class="d-flex gap-2">
                                                            <button type="button" class="btn btn-info btn-sm edit-template" 
                                                                    data-id="<?php echo $template['template_id']; ?>"
                                                                    title="Edit Template">
                                                                <i class="ri-edit-2-line"></i>
                                                            </button>
                                                            <button type="button" class="btn btn-danger btn-sm delete-template"
                                                                    data-id="<?php echo $template['template_id']; ?>"
                                                                    title="Delete Template">
                                                                <i class="ri-delete-bin-line"></i>
                                                            </button>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Recipients Tab -->
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Notification Recipients</h4>
                                    <div class="flex-shrink-0">
                                        <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addRecipientModal"
                                                <?php echo empty($templates) ? 'disabled title="Create a template first"' : ''; ?>>
                                            <i class="ri-add-line align-middle me-1"></i> Add Recipient
                                        </button>
                                    </div>
                                </div>

                                <div class="card-body">
                                    <?php if (empty($settings)): ?>
                                    <div class="text-center py-4">
                                        <i class="ri-user-settings-line display-4 text-muted"></i>
                                        <h5 class="mt-3">No Recipients Configured</h5>
                                        <p class="text-muted">Add recipients to start sending notifications automatically.</p>
                                    </div>
                                    <?php else: ?>
                                    <div class="table-responsive">
                                        <table class="table table-bordered">
                                            <thead>
                                                <tr>
                                                    <th>Template</th>
                                                    <th>Recipient Type</th>
                                                    <th>Recipient</th>
                                                    <th>Email</th>
                                                    <th>SMS</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($settings as $setting): ?>
                                                <tr>
                                                    <td><?php echo htmlspecialchars($setting['template_name']); ?></td>
                                                    <td>
                                                        <span class="badge bg-primary">
                                                            <?php echo htmlspecialchars($setting['recipient_type']); ?>
                                                        </span>
                                                    </td>
                                                    <td><?php echo htmlspecialchars($setting['recipient_name'] ?? $setting['recipient_value']); ?></td>
                                                    <td>
                                                        <span class="badge bg-<?php echo $setting['notify_via_email'] ? 'success' : 'secondary'; ?>">
                                                            <?php echo $setting['notify_via_email'] ? 'Yes' : 'No'; ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <span class="badge bg-<?php echo $setting['notify_via_sms'] ? 'success' : 'secondary'; ?>">
                                                            <?php echo $setting['notify_via_sms'] ? 'Yes' : 'No'; ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <div class="d-flex gap-2">
                                                            <button type="button" class="btn btn-info btn-sm edit-recipient"
                                                                    data-id="<?php echo $setting['setting_id']; ?>"
                                                                    title="Edit Recipient">
                                                                <i class="ri-edit-2-line"></i>
                                                            </button>
                                                            <button type="button" class="btn btn-danger btn-sm delete-recipient"
                                                                    data-id="<?php echo $setting['setting_id']; ?>"
                                                                    title="Delete Recipient">
                                                                <i class="ri-delete-bin-line"></i>
                                                            </button>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Add Template Modal -->
    <div class="modal fade" id="addTemplateModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Add Notification Template</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="templateForm">
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Template Name <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" name="template_name" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Template Code <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" name="template_code" required>
                                    <small class="text-muted">Unique identifier for this template</small>
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Days Before</label>
                            <input type="number" class="form-control" name="days_before" value="0" min="0">
                            <small class="text-muted">Number of days before the event to send notification</small>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Email Subject Template <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="subject_template" required>
                            <small class="text-muted">Use {placeholders} for dynamic content</small>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Email Body Template <span class="text-danger">*</span></label>
                            <textarea class="form-control" name="body_template" rows="5" required></textarea>
                            <small class="text-muted">Use {placeholders} for dynamic content</small>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">SMS Template</label>
                            <textarea class="form-control" name="sms_template" rows="3" maxlength="160"></textarea>
                            <small class="text-muted">Use {placeholders} for dynamic content. Max 160 characters.</small>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Save Template</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Add Recipient Modal -->
    <div class="modal fade" id="addRecipientModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Add Notification Recipient</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="recipientForm">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Template <span class="text-danger">*</span></label>
                            <select class="form-select" name="template_id" required>
                                <option value="">Select Template</option>
                                <?php foreach ($templates as $template): ?>
                                    <option value="<?php echo $template['template_id']; ?>">
                                        <?php echo htmlspecialchars($template['template_name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Recipient Type <span class="text-danger">*</span></label>
                            <select class="form-select" name="recipient_type" required>
                                <option value="">Select Type</option>
                                <option value="USER">User</option>
                                <option value="ROLE">Role</option>
                                <option value="EMAIL">Email Address</option>
                                <option value="PHONE">Phone Number</option>
                            </select>
                        </div>
                        <div class="mb-3 recipient-value-container">
                            <!-- Dynamic input based on recipient type will be inserted here -->
                        </div>
                        <div class="mb-3">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" name="notify_via_email" checked>
                                <label class="form-check-label">Send Email Notifications</label>
                            </div>
                        </div>
                        <div class="mb-3">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" name="notify_via_sms">
                                <label class="form-check-label">Send SMS Notifications</label>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Save Recipient</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Debug information
            console.log('Notification Settings loaded');
            console.log('Templates count:', <?php echo count($templates); ?>);
            console.log('Settings count:', <?php echo count($settings); ?>);
            
            // Function to safely parse JSON response
            function safeParseJSON(response, url) {
                return response.text().then(text => {
                    console.log(`Response from ${url}:`, text);
                    
                    if (!text.trim().startsWith('{') && !text.trim().startsWith('[')) {
                        throw new Error(`Invalid JSON response from ${url}. Response: ${text.substring(0, 200)}...`);
                    }
                    
                    try {
                        return JSON.parse(text);
                    } catch (e) {
                        console.error(`JSON Parse Error from ${url}:`, e);
                        console.error('Raw response:', text);
                        throw new Error(`Failed to parse JSON response: ${e.message}`);
                    }
                });
            }

            // Handle recipient type change
            const recipientType = document.querySelector('select[name="recipient_type"]');
            const recipientContainer = document.querySelector('.recipient-value-container');
            
            recipientType?.addEventListener('change', function() {
                let html = '<label class="form-label">Recipient <span class="text-danger">*</span></label>';
                
                switch(this.value) {
                    case 'USER':
                        html += `<select class="form-select" name="recipient_value" required>
                                    <option value="">Select User</option>
                                    <?php foreach ($users as $user): ?>
                                        <option value="<?php echo $user['user_id']; ?>">
                                            <?php echo htmlspecialchars($user['full_name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>`;
                        break;
                        
                    case 'ROLE':
                        html += `<select class="form-select" name="recipient_value" required>
                                    <option value="">Select Role</option>
                                    <?php foreach ($roles as $role): ?>
                                        <option value="<?php echo $role['role_id']; ?>">
                                            <?php echo htmlspecialchars($role['role_name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>`;
                        break;
                        
                    case 'EMAIL':
                        html += '<input type="email" class="form-control" name="recipient_value" required placeholder="Enter email address">';
                        break;
                        
                    case 'PHONE':
                        html += '<input type="tel" class="form-control" name="recipient_value" required placeholder="Enter phone number">';
                        break;
                        
                    default:
                        html += '<input type="text" class="form-control" name="recipient_value" required placeholder="Enter recipient value">';
                }
                
                recipientContainer.innerHTML = html;
            });

            // Handle template form submission
            const templateForm = document.getElementById('templateForm');
            templateForm?.addEventListener('submit', function(e) {
                e.preventDefault();
                
                const formData = new FormData(this);
                const submitBtn = this.querySelector('button[type="submit"]');
                const originalText = submitBtn.textContent;
                
                submitBtn.textContent = 'Saving...';
                submitBtn.disabled = true;
                
                fetch('save_notification_template.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return safeParseJSON(response, 'save_notification_template.php');
                })
                .then(data => {
                    if (!data.success) {
                        throw new Error(data.error || 'Failed to save template');
                    }
                    
                    Swal.fire({
                        icon: 'success',
                        title: 'Success',
                        text: data.message || 'Template saved successfully!'
                    }).then(() => {
                        window.location.reload();
                    });
                })
                .catch(error => {
                    console.error('Save template error:', error);
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: error.message
                    });
                })
                .finally(() => {
                    submitBtn.textContent = originalText;
                    submitBtn.disabled = false;
                });
            });

            // Handle recipient form submission
            const recipientForm = document.getElementById('recipientForm');
            recipientForm?.addEventListener('submit', function(e) {
                e.preventDefault();
                
                const formData = new FormData(this);
                const submitBtn = this.querySelector('button[type="submit"]');
                const originalText = submitBtn.textContent;
                
                submitBtn.textContent = 'Saving...';
                submitBtn.disabled = true;
                
                fetch('save_notification_recipient.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return safeParseJSON(response, 'save_notification_recipient.php');
                })
                .then(data => {
                    if (!data.success) {
                        throw new Error(data.error || 'Failed to save recipient');
                    }
                    
                    Swal.fire({
                        icon: 'success',
                        title: 'Success',
                        text: data.message || 'Recipient saved successfully!'
                    }).then(() => {
                        window.location.reload();
                    });
                })
                .catch(error => {
                    console.error('Save recipient error:', error);
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: error.message
                    });
                })
                .finally(() => {
                    submitBtn.textContent = originalText;
                    submitBtn.disabled = false;
                });
            });

            // Handle template editing
            const editTemplateButtons = document.querySelectorAll('.edit-template');
            editTemplateButtons.forEach(button => {
                button.addEventListener('click', function() {
                    const templateId = this.dataset.id;
                    
                    fetch(`get_notification_template.php?id=${templateId}`)
                        .then(response => {
                            if (!response.ok) {
                                throw new Error(`HTTP error! status: ${response.status}`);
                            }
                            return safeParseJSON(response, 'get_notification_template.php');
                        })
                        .then(data => {
                            if (!data.success) {
                                throw new Error(data.error || 'Failed to load template');
                            }
                            
                            const template = data.template;
                            const modal = document.getElementById('addTemplateModal');
                            const form = modal.querySelector('form');
                            
                            // Clear any existing hidden inputs
                            const existingHidden = form.querySelector('input[name="template_id"]');
                            if (existingHidden) {
                                existingHidden.remove();
                            }
                            
                            // Populate form
                            form.querySelector('[name="template_name"]').value = template.template_name || '';
                            form.querySelector('[name="template_code"]').value = template.template_code || '';
                            form.querySelector('[name="days_before"]').value = template.days_before || 0;
                            form.querySelector('[name="subject_template"]').value = template.subject_template || '';
                            form.querySelector('[name="body_template"]').value = template.body_template || '';
                            form.querySelector('[name="sms_template"]').value = template.sms_template || '';
                            
                            // Add template ID for update
                            const idInput = document.createElement('input');
                            idInput.type = 'hidden';
                            idInput.name = 'template_id';
                            idInput.value = templateId;
                            form.appendChild(idInput);
                            
                            // Update modal title
                            modal.querySelector('.modal-title').textContent = 'Edit Notification Template';
                            
                            // Show modal
                            const bsModal = new bootstrap.Modal(modal);
                            bsModal.show();
                        })
                        .catch(error => {
                            console.error('Edit template error:', error);
                            Swal.fire({
                                icon: 'error',
                                title: 'Error',
                                text: error.message
                            });
                        });
                });
            });

            // Handle recipient editing
            const editRecipientButtons = document.querySelectorAll('.edit-recipient');
            editRecipientButtons.forEach(button => {
                button.addEventListener('click', function() {
                    const settingId = this.dataset.id;
                    
                    fetch(`get_notification_recipient.php?id=${settingId}`)
                        .then(response => {
                            if (!response.ok) {
                                throw new Error(`HTTP error! status: ${response.status}`);
                            }
                            return safeParseJSON(response, 'get_notification_recipient.php');
                        })
                        .then(data => {
                            if (!data.success) {
                                throw new Error(data.error || 'Failed to load recipient');
                            }
                            
                            const recipient = data.recipient;
                            const modal = document.getElementById('addRecipientModal');
                            const form = modal.querySelector('form');
                            
                            // Clear any existing hidden inputs
                            const existingHidden = form.querySelector('input[name="setting_id"]');
                            if (existingHidden) {
                                existingHidden.remove();
                            }
                            
                            // Populate form
                            form.querySelector('[name="template_id"]').value = recipient.template_id || '';
                            form.querySelector('[name="recipient_type"]').value = recipient.recipient_type || '';
                            form.querySelector('[name="recipient_type"]').dispatchEvent(new Event('change'));
                            
                            setTimeout(() => {
                                const recipientValueField = form.querySelector('[name="recipient_value"]');
                                if (recipientValueField) {
                                    recipientValueField.value = recipient.recipient_value || '';
                                }
                                form.querySelector('[name="notify_via_email"]').checked = recipient.notify_via_email == 1;
                                form.querySelector('[name="notify_via_sms"]').checked = recipient.notify_via_sms == 1;
                            }, 100);
                            
                            // Add setting ID for update
                            const idInput = document.createElement('input');
                            idInput.type = 'hidden';
                            idInput.name = 'setting_id';
                            idInput.value = settingId;
                            form.appendChild(idInput);
                            
                            // Update modal title
                            modal.querySelector('.modal-title').textContent = 'Edit Notification Recipient';
                            
                            // Show modal
                            const bsModal = new bootstrap.Modal(modal);
                            bsModal.show();
                        })
                        .catch(error => {
                            console.error('Edit recipient error:', error);
                            Swal.fire({
                                icon: 'error',
                                title: 'Error',
                                text: error.message
                            });
                        });
                });
            });

            // Handle template deletion
            const deleteTemplateButtons = document.querySelectorAll('.delete-template');
            deleteTemplateButtons.forEach(button => {
                button.addEventListener('click', function() {
                    const templateId = this.dataset.id;
                    
                    Swal.fire({
                        title: 'Confirm Deletion',
                        text: 'Are you sure you want to delete this template? This action cannot be undone.',
                        icon: 'warning',
                        showCancelButton: true,
                        confirmButtonColor: '#d33',
                        confirmButtonText: 'Yes, delete it!',
                        cancelButtonText: 'Cancel'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            Swal.fire({
                                title: 'Deleting...',
                                text: 'Please wait while we delete the template',
                                allowOutsideClick: false,
                                didOpen: () => {
                                    Swal.showLoading();
                                }
                            });
                            
                            fetch('delete_notification_template.php', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/x-www-form-urlencoded',
                                },
                                body: `template_id=${templateId}`
                            })
                            .then(response => {
                                if (!response.ok) {
                                    throw new Error(`HTTP error! status: ${response.status}`);
                                }
                                return safeParseJSON(response, 'delete_notification_template.php');
                            })
                            .then(data => {
                                if (!data.success) {
                                    throw new Error(data.error || 'Failed to delete template');
                                }
                                
                                Swal.fire({
                                    icon: 'success',
                                    title: 'Deleted!',
                                    text: data.message || 'Template has been deleted successfully.'
                                }).then(() => {
                                    window.location.reload();
                                });
                            })
                            .catch(error => {
                                console.error('Delete template error:', error);
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Error',
                                    text: error.message
                                });
                            });
                        }
                    });
                });
            });

            // Handle recipient deletion
            const deleteRecipientButtons = document.querySelectorAll('.delete-recipient');
            deleteRecipientButtons.forEach(button => {
                button.addEventListener('click', function() {
                    const settingId = this.dataset.id;
                    
                    Swal.fire({
                        title: 'Confirm Deletion',
                        text: 'Are you sure you want to delete this recipient? This action cannot be undone.',
                        icon: 'warning',
                        showCancelButton: true,
                        confirmButtonColor: '#d33',
                        confirmButtonText: 'Yes, delete it!',
                        cancelButtonText: 'Cancel'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            Swal.fire({
                                title: 'Deleting...',
                                text: 'Please wait while we delete the recipient',
                                allowOutsideClick: false,
                                didOpen: () => {
                                    Swal.showLoading();
                                }
                            });
                            
                            fetch('delete_notification_recipient.php', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/x-www-form-urlencoded',
                                },
                                body: `setting_id=${settingId}`
                            })
                            .then(response => {
                                if (!response.ok) {
                                    throw new Error(`HTTP error! status: ${response.status}`);
                                }
                                return safeParseJSON(response, 'delete_notification_recipient.php');
                            })
                            .then(data => {
                                if (!data.success) {
                                    throw new Error(data.error || 'Failed to delete recipient');
                                }
                                
                                Swal.fire({
                                    icon: 'success',
                                    title: 'Deleted!',
                                    text: data.message || 'Recipient has been deleted successfully.'
                                }).then(() => {
                                    window.location.reload();
                                });
                            })
                            .catch(error => {
                                console.error('Delete recipient error:', error);
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Error',
                                    text: error.message
                                });
                            });
                        }
                    });
                });
            });

            // Modal cleanup handlers
            document.getElementById('addTemplateModal')?.addEventListener('hidden.bs.modal', function() {
                const form = this.querySelector('form');
                form.reset();
                
                // Remove any hidden template_id input
                const hiddenInput = form.querySelector('input[name="template_id"]');
                if (hiddenInput) {
                    hiddenInput.remove();
                }
                
                // Reset modal title
                this.querySelector('.modal-title').textContent = 'Add Notification Template';
            });

            document.getElementById('addRecipientModal')?.addEventListener('hidden.bs.modal', function() {
                const form = this.querySelector('form');
                form.reset();
                
                // Remove any hidden setting_id input
                const hiddenInput = form.querySelector('input[name="setting_id"]');
                if (hiddenInput) {
                    hiddenInput.remove();
                }
                
                // Clear recipient value container
                const recipientContainer = form.querySelector('.recipient-value-container');
                if (recipientContainer) {
                    recipientContainer.innerHTML = '';
                }
                
                // Reset modal title
                this.querySelector('.modal-title').textContent = 'Add Notification Recipient';
            });
        });
    </script>
</body>
</html>