<?php
require_once '../config.php';
require_once '../config_api.php';
require_once '../app/classes/AdminAuth.php';
require_once '../app/classes/AdminNotificationManager.php';
require_once '../app/classes/NotificationManager.php';

$adminAuth = new AdminAuth($conn);
$adminAuth->requireAuth('admin_login.php');

$notificationManager = new AdminNotificationManager($conn);
$smsEmailManager = new NotificationManager($conn);
$adminId = $_SESSION['admin_id'];

// Handle form submissions
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'send_notification':
                $title = trim($_POST['title']);
                $messageText = trim($_POST['message']);
                $recipientType = $_POST['recipient_type'];
                $priority = $_POST['priority'];
                $expiresAt = !empty($_POST['expires_at']) ? $_POST['expires_at'] : null;
                $recipientIds = null;
                
                if ($recipientType === 'specific' && isset($_POST['recipient_ids'])) {
                    $recipientIds = $_POST['recipient_ids'];
                }
                
                $result = $notificationManager->sendNotification(
                    $title, 
                    $messageText, 
                    $adminId, 
                    $recipientType, 
                    $recipientIds, 
                    $priority, 
                    $expiresAt
                );
                
                if ($result['success']) {
                    $message = "Notification sent successfully to {$result['recipient_count']} recipients!";
                    $messageType = 'success';
                } else {
                    $message = $result['message'];
                    $messageType = 'error';
                }
                break;
                
            case 'delete_notification':
                $notificationId = intval($_POST['notification_id']);
                $result = $notificationManager->deleteNotification($notificationId);
                $message = $result['message'];
                $messageType = $result['success'] ? 'success' : 'error';
                break;
                
            case 'update_sms_config':
        $smsConfig = [
                    'enabled' => isset($_POST['sms_enabled']) ? 1 : 0,
                    'provider' => $_POST['sms_provider'] ?? '',
                    'api_url' => $_POST['sms_api_url'] ?? '',
                    'api_key' => $_POST['sms_api_key'] ?? '',
                    'sender_id' => $_POST['sms_sender_id'] ?? '',
                    'username' => $_POST['sms_username'] ?? '',
                    'password' => $_POST['sms_password'] ?? '',
                    'account_sid' => $_POST['sms_account_sid'] ?? '',
                    'auth_token' => $_POST['sms_auth_token'] ?? '',
                    'from_number' => $_POST['sms_from_number'] ?? ''
                ];
                
                $result = $smsEmailManager->updateConfiguration('sms', $smsConfig);
                if ($result) {
                    $message = 'SMS configuration updated successfully!';
                    $messageType = 'success';
                } else {
                    $message = 'Failed to update SMS configuration.';
                    $messageType = 'error';
                }
                break;
                
            case 'update_email_config':
        $emailConfig = [
                    'enabled' => isset($_POST['email_enabled']) ? 1 : 0,
                    'smtp_host' => $_POST['email_smtp_host'],
                    'smtp_port' => intval($_POST['email_smtp_port']),
                    'smtp_username' => $_POST['email_smtp_username'],
                    'smtp_password' => $_POST['email_smtp_password'],
                    'from_email' => $_POST['email_from_email'],
                    'from_name' => $_POST['email_from_name']
                ];
                
                $result = $smsEmailManager->updateConfiguration('email', $emailConfig);
                if ($result) {
                    $message = 'Email configuration updated successfully!';
                    $messageType = 'success';
                } else {
                    $message = 'Failed to update email configuration.';
                    $messageType = 'error';
                }
                break;
                
            case 'test_sms':
                $phoneNumber = $_POST['test_phone'];
                $testMessage = $_POST['test_sms_message'];
                $result = $smsEmailManager->testSMS($phoneNumber, $testMessage);
                if ($result) {
                    $message = 'Test SMS sent successfully!';
                    $messageType = 'success';
                } else {
                    $message = 'Failed to send test SMS. Check your configuration.';
                    $messageType = 'error';
                }
                break;
                
            case 'test_email':
                $email = $_POST['test_email'];
                $testSubject = $_POST['test_email_subject'];
                $testMessage = $_POST['test_email_message'];
                $result = $smsEmailManager->testEmail($email, $testSubject, $testMessage);
                if ($result) {
                    $message = 'Test email sent successfully!';
                    $messageType = 'success';
                } else {
                    $message = 'Failed to send test email. Check your configuration.';
                    $messageType = 'error';
                }
                break;
        }
    }
}

// Get notifications and stats
$notifications = $notificationManager->getAllNotifications(50, 0);
$stats = $notificationManager->getNotificationStats();
$agents = $notificationManager->getAgents();

// Get SMS and Email configurations
$smsConfig = [];
$emailConfig = [];

$smsResult = mysqli_query($conn, "SELECT * FROM notification_config WHERE type = 'sms'");
if ($smsResult && mysqli_num_rows($smsResult) > 0) {
    $smsConfig = mysqli_fetch_assoc($smsResult);
    $smsConfig = json_decode($smsConfig['config_data'], true) ?: [];
}

$emailResult = mysqli_query($conn, "SELECT * FROM notification_config WHERE type = 'email'");
if ($emailResult && mysqli_num_rows($emailResult) > 0) {
    $emailConfig = mysqli_fetch_assoc($emailResult);
    $emailConfig = json_decode($emailConfig['config_data'], true) ?: [];
}

// Set default values if not configured
$smsConfig = array_merge([
    'enabled' => false,
    'provider' => 'generic',
    'api_url' => '',
    'api_key' => '',
    'sender_id' => '',
    'username' => '',
    'password' => '',
    'account_sid' => '',
    'auth_token' => '',
    'from_number' => ''
], $smsConfig);

$emailConfig = array_merge([
    'enabled' => false,
    'smtp_host' => '',
    'smtp_port' => 587,
    'smtp_username' => '',
    'smtp_password' => '',
    'from_email' => '',
    'from_name' => 'D-Bundles Stores'
], $emailConfig);
?>

<!-- Notification Management Page Content -->
<style>
    .notification-card {
        transition: all 0.3s ease;
    }
    .notification-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(0,0,0,0.1);
    }
    .priority-urgent { border-left: 4px solid #ef4444; }
    .priority-high { border-left: 4px solid #f97316; }
    .priority-normal { border-left: 4px solid #3b82f6; }
    .priority-low { border-left: 4px solid #6b7280; }
</style>
    
    <div class="container mx-auto px-4 py-8">
        <!-- Header -->
        <div class="flex justify-between items-center mb-8">
        <div>
                <h1 class="text-3xl font-bold text-gray-900">Notification Management</h1>
                <p class="text-gray-600 mt-2">Send messages to agents and super agents</p>
        </div>
            <button onclick="openSendModal()" class="bg-blue-600 text-white px-6 py-3 rounded-lg hover:bg-blue-700 transition-colors">
                <i class="fas fa-plus mr-2"></i>Send Notification
            </button>
        </div>

        <!-- Tab Navigation -->
        <div class="mb-8">
            <div class="border-b border-gray-200">
                <nav class="-mb-px flex space-x-8">
                    <button onclick="showTab('in-app')" class="tab-btn active py-2 px-1 border-b-2 border-blue-500 font-medium text-sm text-blue-600" id="in-app-tab">
                        <i class="fas fa-bell mr-2"></i>In-App Notifications
                    </button>
                    <button onclick="showTab('sms')" class="tab-btn py-2 px-1 border-b-2 border-transparent font-medium text-sm text-gray-500 hover:text-gray-700 hover:border-gray-300" id="sms-tab">
                        <i class="fas fa-sms mr-2"></i>SMS Configuration
                    </button>
                    <button onclick="showTab('email')" class="tab-btn py-2 px-1 border-b-2 border-transparent font-medium text-sm text-gray-500 hover:text-gray-700 hover:border-gray-300" id="email-tab">
                        <i class="fas fa-envelope mr-2"></i>Email Configuration
                    </button>
                </nav>
    </div>
</div>

        <!-- Message Display -->
        <?php if ($message): ?>
        <div class="mb-6 p-4 rounded-lg <?php echo $messageType === 'success' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>">
            <i class="fas <?php echo $messageType === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'; ?> mr-2"></i>
            <?php echo htmlspecialchars($message); ?>
</div>
<?php endif; ?>

        <!-- Tab Content -->
        <!-- In-App Notifications Tab -->
        <div id="in-app-content" class="tab-content">

        <!-- Statistics Cards -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
            <div class="bg-white p-6 rounded-lg shadow-sm">
        <div class="flex items-center">
                    <div class="p-3 bg-blue-100 rounded-lg">
                        <i class="fas fa-bell text-blue-600 text-xl"></i>
                    </div>
                    <div class="ml-4">
                        <p class="text-sm text-gray-600">Total Notifications</p>
                        <p class="text-2xl font-bold text-gray-900"><?php echo $stats['total_notifications']; ?></p>
        </div>
    </div>
            </div>
            
            <div class="bg-white p-6 rounded-lg shadow-sm">
                <div class="flex items-center">
                    <div class="p-3 bg-red-100 rounded-lg">
                        <i class="fas fa-exclamation-circle text-red-600 text-xl"></i>
                    </div>
                    <div class="ml-4">
                        <p class="text-sm text-gray-600">Unread</p>
                        <p class="text-2xl font-bold text-gray-900"><?php echo $stats['unread_notifications']; ?></p>
            </div>
        </div>
            </div>
            
            <div class="bg-white p-6 rounded-lg shadow-sm">
                <div class="flex items-center">
                    <div class="p-3 bg-orange-100 rounded-lg">
                        <i class="fas fa-exclamation-triangle text-orange-600 text-xl"></i>
            </div>
                    <div class="ml-4">
                        <p class="text-sm text-gray-600">High Priority</p>
                        <p class="text-2xl font-bold text-gray-900"><?php echo $stats['by_priority']['high'] ?? 0; ?></p>
                </div>
                </div>
            </div>
            
            <div class="bg-white p-6 rounded-lg shadow-sm">
                <div class="flex items-center">
                    <div class="p-3 bg-red-100 rounded-lg">
                        <i class="fas fa-fire text-red-600 text-xl"></i>
                    </div>
                    <div class="ml-4">
                        <p class="text-sm text-gray-600">Urgent</p>
                        <p class="text-2xl font-bold text-gray-900"><?php echo $stats['by_priority']['urgent'] ?? 0; ?></p>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Notifications List -->
        <div class="bg-white rounded-lg shadow-sm">
            <div class="p-6 border-b border-gray-200">
                <h2 class="text-xl font-semibold text-gray-900">Recent Notifications</h2>
                </div>
                
            <div class="divide-y divide-gray-200">
                <?php if (empty($notifications)): ?>
                <div class="p-8 text-center text-gray-500">
                    <i class="fas fa-bell-slash text-4xl mb-4"></i>
                    <p>No notifications sent yet.</p>
                </div>
                <?php else: ?>
                    <?php foreach ($notifications as $notification): ?>
                    <div class="p-6 notification-card priority-<?php echo $notification['priority']; ?>">
                        <div class="flex justify-between items-start">
                            <div class="flex-1">
                                <div class="flex items-center mb-2">
                                    <h3 class="text-lg font-semibold text-gray-900 mr-3"><?php echo htmlspecialchars($notification['title']); ?></h3>
                                    <span class="px-2 py-1 text-xs font-medium rounded-full
                                        <?php 
                                        switch($notification['priority']) {
                                            case 'urgent': echo 'bg-red-100 text-red-800'; break;
                                            case 'high': echo 'bg-orange-100 text-orange-800'; break;
                                            case 'normal': echo 'bg-blue-100 text-blue-800'; break;
                                            case 'low': echo 'bg-gray-100 text-gray-800'; break;
                                        }
                                        ?>">
                                        <?php echo ucfirst($notification['priority']); ?>
                                    </span>
                                </div>
                                
                                <p class="text-gray-700 mb-3"><?php echo nl2br(htmlspecialchars($notification['message'])); ?></p>
                                
                                <div class="flex items-center text-sm text-gray-500 space-x-4">
                                    <span><i class="fas fa-users mr-1"></i><?php echo ucfirst(str_replace('_', ' ', $notification['recipient_type'])); ?></span>
                                    <span><i class="fas fa-eye mr-1"></i><?php echo $notification['read_count']; ?>/<?php echo $notification['total_recipients']; ?> read</span>
                                    <span><i class="fas fa-clock mr-1"></i><?php echo date('M j, Y g:i A', strtotime($notification['created_at'])); ?></span>
                                    <?php if ($notification['expires_at']): ?>
                                    <span><i class="fas fa-calendar-times mr-1"></i>Expires: <?php echo date('M j, Y g:i A', strtotime($notification['expires_at'])); ?></span>
                                    <?php endif; ?>
            </div>
        </div>
        
                            <div class="ml-4">
                                <form method="POST" class="inline" onsubmit="return confirm('Are you sure you want to delete this notification?')">
                                    <input type="hidden" name="action" value="delete_notification">
                                    <input type="hidden" name="notification_id" value="<?php echo $notification['id']; ?>">
                                    <button type="submit" class="text-red-600 hover:text-red-800 transition-colors">
                                        <i class="fas fa-trash"></i>
            </button>
    </form>
</div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
        <!-- SMS Configuration Tab -->
        <div id="sms-content" class="tab-content hidden">
            <div class="bg-white rounded-lg shadow-sm p-6">
                <h2 class="text-xl font-semibold text-gray-900 mb-6">
                    <i class="fas fa-sms mr-2"></i>SMS Configuration
        </h2>
                
                <!-- SMS Configuration Instructions -->
                <div class="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6">
                    <div class="flex items-start">
                        <div class="flex-shrink-0">
                            <i class="fas fa-info-circle text-blue-600 text-lg"></i>
                        </div>
                        <div class="ml-3">
                            <h3 class="text-sm font-medium text-blue-800">SMS Configuration Guide</h3>
                            <div class="mt-2 text-sm text-blue-700">
                                <p class="mb-2">Configure SMS notifications to send messages to agents and super agents. Choose your SMS provider and enter the required credentials:</p>
                                <ul class="list-disc list-inside space-y-1">
                                    <li><strong>Generic API:</strong> Use any SMS API that accepts HTTP requests</li>
                                    <li><strong>SMS Online Ghana:</strong> Local SMS service provider for Ghana (recommended)</li>
                                </ul>
                            </div>
                        </div>
        </div>
    </div>
    
                <form method="POST" class="space-y-6">
        <input type="hidden" name="action" value="update_sms_config">
        
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
                            <label class="flex items-center">
                                <input type="checkbox" name="sms_enabled" <?php echo $smsConfig['enabled'] ? 'checked' : ''; ?> class="mr-2">
                                <span class="text-sm font-medium text-gray-700">Enable SMS Notifications</span>
                            </label>
                            <p class="text-xs text-gray-500 mt-1">Turn on SMS notifications for agents and super agents</p>
            </div>
            
            <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">SMS Provider *</label>
                            <select name="sms_provider" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent" required>
                                <option value="">Select SMS Provider</option>
                                <option value="generic" <?php echo $smsConfig['provider'] === 'generic' ? 'selected' : ''; ?>>Generic API</option>
                                <option value="smsonlinegh" <?php echo $smsConfig['provider'] === 'smsonlinegh' ? 'selected' : ''; ?>>SMS Online Ghana</option>
                            </select>
                            <p class="text-xs text-gray-500 mt-1">Choose your SMS service provider</p>
            </div>
        </div>
        
                    <!-- Generic API Configuration -->
                    <div id="generic-config" class="space-y-4">
                        <h4 class="text-lg font-medium text-gray-900 border-b border-gray-200 pb-2">Generic API Configuration</h4>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">API URL *</label>
                                <input type="url" name="sms_api_url" value="<?php echo htmlspecialchars($smsConfig['api_url']); ?>" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="https://api.example.com/sms/send">
                                <p class="text-xs text-gray-500 mt-1">The endpoint URL for sending SMS messages</p>
            </div>
            
            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">API Key *</label>
                                <input type="text" name="sms_api_key" value="<?php echo htmlspecialchars($smsConfig['api_key']); ?>" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="Your API key">
                                <p class="text-xs text-gray-500 mt-1">Authentication key for your SMS API</p>
            </div>
        </div>
        
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Sender ID</label>
                                <input type="text" name="sms_sender_id" value="<?php echo htmlspecialchars($smsConfig['sender_id']); ?>" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="YourCompany">
                                <p class="text-xs text-gray-500 mt-1">Name or ID that appears as sender (max 11 characters)</p>
                </div>
                
                <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Username</label>
                                <input type="text" name="sms_username" value="<?php echo htmlspecialchars($smsConfig['username']); ?>" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="Your username">
                                <p class="text-xs text-gray-500 mt-1">Username for API authentication (if required)</p>
                </div>
            </div>
            
            <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Password</label>
                            <input type="password" name="sms_password" value="<?php echo htmlspecialchars($smsConfig['password']); ?>" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="Your password">
                            <p class="text-xs text-gray-500 mt-1">Password for API authentication (if required)</p>
                        </div>
                    </div>
                    
                    
                    <!-- SMS Online Ghana Configuration -->
                    <div id="smsonlinegh-config" class="space-y-4 hidden">
                        <h4 class="text-lg font-medium text-gray-900 border-b border-gray-200 pb-2">SMS Online Ghana Configuration</h4>
                        <div class="bg-green-50 border border-green-200 rounded-lg p-3 mb-4">
                            <div class="flex">
                                <i class="fas fa-info-circle text-green-600 mt-0.5 mr-2"></i>
                                <div class="text-sm text-green-800">
                                    <p class="mb-2">Configure SMS Online Ghana service for sending SMS notifications</p>
                                    <p class="text-xs"><strong>Important:</strong> The sender name must be registered in your SMS Online Ghana account under SMS Messaging menu option.</p>
                                </div>
            </div>
        </div>
        
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">API Key *</label>
                                <input type="text" name="sms_api_key" value="<?php echo htmlspecialchars($smsConfig['api_key']); ?>" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="Your API key">
                                <p class="text-xs text-gray-500 mt-1">Your SMS Online Ghana API key</p>
                </div>
                
                <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Sender ID *</label>
                                <input type="text" name="sms_sender_id" value="<?php echo htmlspecialchars($smsConfig['sender_id']); ?>" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="Cloudtech">
                                <p class="text-xs text-gray-500 mt-1">Your sender ID (e.g., Cloudtech)</p>
                            </div>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Phone Number</label>
                            <input type="text" name="sms_phone_number" value="<?php echo htmlspecialchars($smsConfig['phone_number'] ?? ''); ?>" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="0247965501">
                            <p class="text-xs text-gray-500 mt-1">Your registered phone number (optional)</p>
            </div>
        </div>
        
        <div class="flex justify-end space-x-3">
                        <button type="submit" class="bg-blue-600 text-white px-6 py-2 rounded-lg hover:bg-blue-700 transition-colors">
                            <i class="fas fa-save mr-2"></i>Save SMS Configuration
            </button>
        </div>
    </form>
                
                <!-- Test SMS Section -->
                <div class="mt-8 pt-6 border-t border-gray-200">
                    <h3 class="text-lg font-semibold text-gray-900 mb-4">Test SMS Configuration</h3>
                    <div class="bg-gray-50 border border-gray-200 rounded-lg p-4 mb-4">
                        <div class="flex">
                            <i class="fas fa-info-circle text-blue-600 mt-0.5 mr-2"></i>
                            <p class="text-sm text-gray-700">Test your SMS configuration by sending a test message to verify everything is working correctly.</p>
                        </div>
                    </div>
                    <form method="POST" class="space-y-4">
                        <input type="hidden" name="action" value="test_sms">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Phone Number *</label>
                                <input type="text" name="test_phone" placeholder="0558119187" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent" required>
                                <p class="text-xs text-gray-500 mt-1">Enter phone number with country code (e.g., +233558119187)</p>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Test Message *</label>
                                <input type="text" name="test_sms_message" value="Test SMS from D-Bundles Stores" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent" required>
                                <p class="text-xs text-gray-500 mt-1">Message to send for testing (max 160 characters)</p>
                            </div>
                        </div>
                        <button type="submit" class="bg-green-600 text-white px-6 py-2 rounded-lg hover:bg-green-700 transition-colors">
                            <i class="fas fa-paper-plane mr-2"></i>Send Test SMS
                        </button>
                    </form>
                </div>
            </div>
</div>

        <!-- Email Configuration Tab -->
        <div id="email-content" class="tab-content hidden">
            <div class="bg-white rounded-lg shadow-sm p-6">
                <h2 class="text-xl font-semibold text-gray-900 mb-6">
                    <i class="fas fa-envelope mr-2"></i>Email Configuration
        </h2>
                
                <!-- Email Configuration Instructions -->
                <div class="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6">
                    <div class="flex items-start">
                        <div class="flex-shrink-0">
                            <i class="fas fa-info-circle text-blue-600 text-lg"></i>
                        </div>
                        <div class="ml-3">
                            <h3 class="text-sm font-medium text-blue-800">Email Configuration Guide</h3>
                            <div class="mt-2 text-sm text-blue-700">
                                <p class="mb-2">Configure SMTP settings to send email notifications to agents and super agents. Common SMTP providers:</p>
                                <ul class="list-disc list-inside space-y-1">
                                    <li><strong>Gmail:</strong> smtp.gmail.com, Port 587 (TLS) or 465 (SSL)</li>
                                    <li><strong>Outlook/Hotmail:</strong> smtp-mail.outlook.com, Port 587</li>
                                    <li><strong>Yahoo:</strong> smtp.mail.yahoo.com, Port 587 or 465</li>
                                    <li><strong>Custom SMTP:</strong> Use your hosting provider's SMTP settings</li>
                                </ul>
                            </div>
                        </div>
        </div>
    </div>
    
                <form method="POST" class="space-y-6">
        <input type="hidden" name="action" value="update_email_config">
        
                    <div>
                        <label class="flex items-center">
                            <input type="checkbox" name="email_enabled" <?php echo $emailConfig['enabled'] ? 'checked' : ''; ?> class="mr-2">
                            <span class="text-sm font-medium text-gray-700">Enable Email Notifications</span>
                        </label>
                        <p class="text-xs text-gray-500 mt-1">Turn on email notifications for agents and super agents</p>
                    </div>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">SMTP Host *</label>
                            <input type="text" name="email_smtp_host" value="<?php echo htmlspecialchars($emailConfig['smtp_host']); ?>" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="smtp.gmail.com" required>
                            <p class="text-xs text-gray-500 mt-1">SMTP server hostname (e.g., smtp.gmail.com)</p>
            </div>
            
            <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">SMTP Port *</label>
                            <input type="number" name="email_smtp_port" value="<?php echo htmlspecialchars($emailConfig['smtp_port']); ?>" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="587" required>
                            <p class="text-xs text-gray-500 mt-1">SMTP port (587 for TLS, 465 for SSL, 25 for non-encrypted)</p>
            </div>
        </div>
        
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">SMTP Username *</label>
                            <input type="text" name="email_smtp_username" value="<?php echo htmlspecialchars($emailConfig['smtp_username']); ?>" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="your-email@gmail.com" required>
                            <p class="text-xs text-gray-500 mt-1">Your email address or SMTP username</p>
            </div>
            
            <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">SMTP Password *</label>
                            <input type="password" name="email_smtp_password" value="<?php echo htmlspecialchars($emailConfig['smtp_password']); ?>" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="Your email password or app password" required>
                            <p class="text-xs text-gray-500 mt-1">Email password or app-specific password (for Gmail, use App Password)</p>
            </div>
        </div>
        
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">From Email *</label>
                            <input type="email" name="email_from_email" value="<?php echo htmlspecialchars($emailConfig['from_email']); ?>" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="noreply@yourcompany.com" required>
                            <p class="text-xs text-gray-500 mt-1">Email address that will appear as sender</p>
            </div>
            
            <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">From Name *</label>
                            <input type="text" name="email_from_name" value="<?php echo htmlspecialchars($emailConfig['from_name']); ?>" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="D-Bundles Stores" required>
                            <p class="text-xs text-gray-500 mt-1">Display name that will appear as sender</p>
            </div>
        </div>
        
        <div class="flex justify-end space-x-3">
                        <button type="submit" class="bg-blue-600 text-white px-6 py-2 rounded-lg hover:bg-blue-700 transition-colors">
                            <i class="fas fa-save mr-2"></i>Save Email Configuration
            </button>
        </div>
    </form>
                
                <!-- Test Email Section -->
                <div class="mt-8 pt-6 border-t border-gray-200">
                    <h3 class="text-lg font-semibold text-gray-900 mb-4">Test Email Configuration</h3>
                    <div class="bg-gray-50 border border-gray-200 rounded-lg p-4 mb-4">
                        <div class="flex">
                            <i class="fas fa-info-circle text-blue-600 mt-0.5 mr-2"></i>
                            <p class="text-sm text-gray-700">Test your email configuration by sending a test message to verify SMTP settings are working correctly.</p>
                        </div>
                    </div>
                    <form method="POST" class="space-y-4">
                        <input type="hidden" name="action" value="test_email">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Email Address *</label>
                                <input type="email" name="test_email" placeholder="test@example.com" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent" required>
                                <p class="text-xs text-gray-500 mt-1">Email address to send the test message to</p>
</div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Subject *</label>
                                <input type="text" name="test_email_subject" value="Test Email from D-Bundles Stores" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent" required>
                                <p class="text-xs text-gray-500 mt-1">Subject line for the test email</p>
    </div>
</div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Message *</label>
                            <textarea name="test_email_message" rows="4" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent" required>This is a test email from D-Bundles Stores notification system. If you receive this email, your SMTP configuration is working correctly!</textarea>
                            <p class="text-xs text-gray-500 mt-1">Message content for the test email</p>
                    </div>
                        <button type="submit" class="bg-green-600 text-white px-6 py-2 rounded-lg hover:bg-green-700 transition-colors">
                            <i class="fas fa-paper-plane mr-2"></i>Send Test Email
                        </button>
                </form>
            </div>
        </div>
    </div>
</div>

    <!-- Send Notification Modal -->
    <div id="sendModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50">
    <div class="flex items-center justify-center min-h-screen p-4">
            <div class="bg-white rounded-lg max-w-2xl w-full max-h-[90vh] overflow-y-auto">
                <div class="p-6 border-b border-gray-200">
                    <div class="flex justify-between items-center">
                        <h3 class="text-xl font-semibold text-gray-900">Send Notification</h3>
                        <button onclick="closeSendModal()" class="text-gray-400 hover:text-gray-600">
                            <i class="fas fa-times text-xl"></i>
                        </button>
            </div>
        </div>
        
                <form method="POST" class="p-6">
                    <input type="hidden" name="action" value="send_notification">
                    
                    <div class="space-y-6">
            <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Title *</label>
                            <input type="text" name="title" required class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="Enter notification title">
            </div>
            
            <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Message *</label>
                            <textarea name="message" required rows="4" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="Enter your message"></textarea>
        </div>
        
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Recipients *</label>
                                <select name="recipient_type" id="recipient_type" required onchange="toggleRecipientSelection()" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                    <option value="">Select recipients</option>
                                    <option value="all">All Agents</option>
                                    <option value="agents">Agents Only</option>
                                    <option value="specific">Specific Users</option>
                                </select>
            </div>
            
            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Priority</label>
                                <select name="priority" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                    <option value="normal">Normal</option>
                                    <option value="low">Low</option>
                                    <option value="high">High</option>
                                    <option value="urgent">Urgent</option>
                                </select>
            </div>
        </div>
        
                        <div id="specific_recipients" class="hidden">
                            <label class="block text-sm font-medium text-gray-700 mb-2">Select Specific Users</label>
                            <div class="max-h-40 overflow-y-auto border border-gray-300 rounded-lg p-3">
                                <?php foreach ($agents as $agent): ?>
                                <label class="flex items-center mb-2">
                                    <input type="checkbox" name="recipient_ids[]" value="<?php echo $agent['id']; ?>" class="mr-2">
                                    <span class="text-sm">
                                        <?php echo htmlspecialchars($agent['username']); ?> 
                                        <span class="text-gray-500">(<?php echo ucfirst($agent['role']); ?>)</span>
                            </span>
                                </label>
                <?php endforeach; ?>
    </div>
</div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Expiration Date (Optional)</label>
                            <input type="datetime-local" name="expires_at" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                            <p class="text-xs text-gray-500 mt-1">Leave empty for no expiration</p>
    </div>
                    </div>

                    <div class="flex justify-end space-x-3 mt-6">
                        <button type="button" onclick="closeSendModal()" class="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors">
                            Cancel
                        </button>
                        <button type="submit" class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
                            <i class="fas fa-paper-plane mr-2"></i>Send Notification
                        </button>
                    </div>
                </form>
        </div>
    </div>
</div>

<script>
        function showTab(tabName) {
            // Hide all tab contents
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.add('hidden');
            });
            
            // Remove active class from all tabs
            document.querySelectorAll('.tab-btn').forEach(btn => {
                btn.classList.remove('border-blue-500', 'text-blue-600');
                btn.classList.add('border-transparent', 'text-gray-500');
            });
            
            // Show selected tab content
            document.getElementById(tabName + '-content').classList.remove('hidden');
            
            // Add active class to selected tab
            const activeTab = document.getElementById(tabName + '-tab');
            activeTab.classList.add('border-blue-500', 'text-blue-600');
            activeTab.classList.remove('border-transparent', 'text-gray-500');
        }
        
        function openSendModal() {
            document.getElementById('sendModal').classList.remove('hidden');
        }
        
        function closeSendModal() {
            document.getElementById('sendModal').classList.add('hidden');
            document.querySelector('form').reset();
            document.getElementById('specific_recipients').classList.add('hidden');
        }
        
        function toggleRecipientSelection() {
            const recipientType = document.getElementById('recipient_type').value;
            const specificDiv = document.getElementById('specific_recipients');
            
            if (recipientType === 'specific') {
                specificDiv.classList.remove('hidden');
    } else {
                specificDiv.classList.add('hidden');
                // Uncheck all specific recipient checkboxes
                document.querySelectorAll('input[name="recipient_ids[]"]').forEach(checkbox => {
                    checkbox.checked = false;
                });
            }
        }
        
        function toggleSMSProviderConfig() {
            const provider = document.querySelector('select[name="sms_provider"]').value;
            const genericConfig = document.getElementById('generic-config');
            const smsonlineghConfig = document.getElementById('smsonlinegh-config');
            
            // Hide all config sections
            genericConfig.classList.add('hidden');
            smsonlineghConfig.classList.add('hidden');
            
            // Show the appropriate config section
            switch(provider) {
                case 'generic':
                    genericConfig.classList.remove('hidden');
                    break;
                case 'smsonlinegh':
                    smsonlineghConfig.classList.remove('hidden');
                    break;
            }
        }
        
        // Initialize SMS provider config on page load
document.addEventListener('DOMContentLoaded', function() {
            toggleSMSProviderConfig();
            
            // Add event listener to SMS provider select
            const smsProviderSelect = document.querySelector('select[name="sms_provider"]');
            if (smsProviderSelect) {
                smsProviderSelect.addEventListener('change', toggleSMSProviderConfig);
            }
        });
        
        // Close modal when clicking outside
        document.getElementById('sendModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeSendModal();
            }
        });
        
        // Auto-hide success/error messages
        setTimeout(() => {
            const messages = document.querySelectorAll('.mb-6.p-4.rounded-lg');
            messages.forEach(message => {
                message.style.opacity = '0';
                setTimeout(() => message.remove(), 300);
            });
        }, 5000);
</script>
