{include file="sections/header.tpl"}

<!-- Test Notification Modal -->
<div class="modal fade" id="testNotificationModal" tabindex="-1" role="dialog" aria-labelledby="testNotificationModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="testNotificationModalLabel">Test Notification</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="testNotificationForm">
                    <div class="form-group">
                        <label for="testPhone">Phone Number</label>
                        <input type="text" class="form-control" id="testPhone" placeholder="Enter phone number for testing" required>
                    </div>
                    <div class="form-group">
                        <label for="testCustomerName">Customer Name</label>
                        <input type="text" class="form-control" id="testCustomerName" value="John Doe" placeholder="Customer name">
                    </div>
                    <div class="form-group">
                        <label for="testPackageName">Package Name</label>
                        <input type="text" class="form-control" id="testPackageName" value="Premium 10Mbps" placeholder="Package name">
                    </div>
                    <div class="form-group">
                        <label for="testPrice">Package Price</label>
                        <input type="text" class="form-control" id="testPrice" value="5000" placeholder="Package price">
                    </div>
                    <div class="form-group">
                        <label for="testNotificationType">Notification Type</label>
                        <select class="form-control" id="testNotificationType">
                            <option value="sms">SMS</option>
                            <option value="wa">WhatsApp</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Preview Message:</label>
                        <div id="messagePreview" class="alert alert-info" style="white-space: pre-wrap;"></div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="sendTestNotification()">Send Test</button>
            </div>
        </div>
    </div>
</div>

<script>
let currentTestType = '';
let currentPlanType = '';

function testNotification(type, planType) {
    currentTestType = type;
    currentPlanType = planType;
    
    // Update modal title
    document.getElementById('testNotificationModalLabel').textContent = 
        'Test ' + type.replace('_', ' ').toUpperCase() + ' - ' + planType.toUpperCase();
    
    // Show modal
    $('#testNotificationModal').modal('show');
    
    // Update preview
    updateMessagePreview();
}

function updateMessagePreview() {
    const customerName = document.getElementById('testCustomerName').value || 'John Doe';
    const packageName = document.getElementById('testPackageName').value || 'Premium 10Mbps';
    const price = document.getElementById('testPrice').value || '5000';
    
    // Get the template from the form
    let template = '';
    if (currentTestType === 'expired') {
        if (currentPlanType === 'hotspot') {
            template = document.getElementById('expired_hotspot').value;
        } else {
            template = document.getElementById('expired_pppoe').value;
        }
    } else if (currentTestType === 'reminder_7_day') {
        if (currentPlanType === 'hotspot') {
            template = document.getElementById('reminder_7_day_hotspot').value;
        } else {
            template = document.getElementById('reminder_7_day_pppoe').value;
        }
    }
    
    // Replace variables
    let preview = template
        .replace(/\[\[name\]\]/g, customerName)
        .replace(/\[\[username\]\]/g, 'testuser')
        .replace(/\[\[package\]\]/g, packageName)
        .replace(/\[\[plan\]\]/g, packageName)
        .replace(/\[\[price\]\]/g, price)
        .replace(/\[\[plan_type\]\]/g, currentPlanType.toUpperCase())
        .replace(/\[\[service_portal\]\]/g, 'https://portal.example.com')
        .replace(/\[\[support_contact\]\]/g, 'support@example.com')
        .replace(/\[\[expired_date\]\]/g, new Date().toLocaleDateString())
        .replace(/\[\[bills\]\]/g, '');
    
    document.getElementById('messagePreview').textContent = preview;
}

function sendTestNotification() {
    const phone = document.getElementById('testPhone').value;
    const customerName = document.getElementById('testCustomerName').value;
    const packageName = document.getElementById('testPackageName').value;
    const price = document.getElementById('testPrice').value;
    const notificationType = document.getElementById('testNotificationType').value;
    
    if (!phone) {
        alert('Please enter a phone number');
        return;
    }
    
    // Show loading
    const sendBtn = document.querySelector('#testNotificationModal .btn-primary');
    const originalText = sendBtn.textContent;
    sendBtn.textContent = 'Sending...';
    sendBtn.disabled = true;
    
    // Send test notification
    fetch('{$_url}settings/test-notification', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams({
            phone: phone,
            customer_name: customerName,
            package_name: packageName,
            price: price,
            notification_type: notificationType,
            test_type: currentTestType,
            plan_type: currentPlanType
        })
    })
    .then(response => response.text())
    .then(data => {
        alert('Test notification sent!\nResult: ' + data);
        $('#testNotificationModal').modal('hide');
    })
    .catch(error => {
        alert('Error sending test notification: ' + error);
    })
    .finally(() => {
        sendBtn.textContent = originalText;
        sendBtn.disabled = false;
    });
}

// Update preview when form fields change
document.addEventListener('DOMContentLoaded', function() {
    const formFields = ['testCustomerName', 'testPackageName', 'testPrice'];
    formFields.forEach(fieldId => {
        const field = document.getElementById(fieldId);
        if (field) {
            field.addEventListener('input', updateMessagePreview);
        }
    });
});

function testCronJob() {
    const resultDiv = document.getElementById('cronTestResult');
    resultDiv.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Testing cron job...';
    
    fetch('{$_url}settings/test-cron', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        }
    })
    .then(response => response.text())
    .then(data => {
        resultDiv.innerHTML = '<div class="alert alert-info"><pre>' + data + '</pre></div>';
    })
    .catch(error => {
        resultDiv.innerHTML = '<div class="alert alert-danger">Error: ' + error + '</div>';
    });
}
</script>
            <div class="container-fluid">
                <form class="form-horizontal" method="post" role="form" action="{$_url}settings/notifications-post">
                    <div class="row">
                        <div class="col-xxl-6 col-xxl-12">
                            <div class="col-md-12">
                                <div class="card">
                                    <div class="card-header"
                                        style="display: grid; align-content: center; justify-content: center;">
                                        <div class="panel panel-primary panel-hovered panel-stacked mb30">
                                            <div class="card-header">
                                                <h5 class="card-title">{Lang::T('Messages Settings')}</h5>
                                                <div class="btn-group pull-right">
                                                    <button class="btn btn-primary" title="save" type="submit"><span
                                                            class="flaticon-381-save"
                                                            aria-hidden="true"></span></button>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="card-body">
                                            <div class="card-header" style="background-color: #f8f9fa; margin: 0 0 20px 0;">
                                                <h6 class="card-title" style="margin: 0; color: #495057; font-weight: bold;">
                                                    <i class="fa fa-exclamation-triangle"></i> {Lang::T('Expiration & Reminder Messages')}
                                                </h6>
                                                <div class="btn-group pull-right">
                                                    <button type="button" class="btn btn-info btn-sm" onclick="testNotification('expired', 'hotspot')">
                                                        <i class="fa fa-wifi"></i> Test Hotspot Expiry
                                                    </button>
                                                    <button type="button" class="btn btn-success btn-sm" onclick="testNotification('expired', 'pppoe')">
                                                        <i class="fa fa-ethernet"></i> Test PPPoE Expiry
                                                    </button>
                                                    <button type="button" class="btn btn-warning btn-sm" onclick="testNotification('reminder_7_day', 'hotspot')">
                                                        <i class="fa fa-clock-o"></i> Test 7-Day Reminder
                                                    </button>
                                                </div>
                                            </div>
                                            <!-- Plan Type Specific Templates -->
                                            <div class="form-group">
                                                <label class="control-label">{Lang::T('Expired Notification Messages')}</label>
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <label class="control-label text-primary"><i class="fa fa-wifi"></i> {Lang::T('Hotspot Users')}</label>
                                                        <textarea style="overflow: hidden;" class="form-control"
                                                            id="expired_hotspot" oninput="autoExpand(this)" name="expired[hotspot]"
                                                            placeholder="Hello [[name]], your Hotspot internet package [[package]] has been expired. Please visit our portal at [[service_portal]] to renew your connection."
                                                            rows="6">{if $_json['expired']['hotspot']!=''}{Lang::htmlspecialchars($_json['expired']['hotspot'])}{else}Hello [[name]], your Hotspot internet package [[package]] has been expired. Please visit our portal at [[service_portal]] to renew your connection.{/if}</textarea>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <label class="control-label text-success"><i class="fa fa-ethernet"></i> {Lang::T('PPPoE Users')}</label>
                                                        <textarea style="overflow: hidden;" class="form-control"
                                                            id="expired_pppoe" oninput="autoExpand(this)" name="expired[pppoe]"
                                                            placeholder="Hello [[name]], your PPPoE internet package [[package]] has been expired. Please contact our support team at [[support_contact]] for renewal assistance."
                                                            rows="6">{if $_json['expired']['pppoe']!=''}{Lang::htmlspecialchars($_json['expired']['pppoe'])}{else}Hello [[name]], your PPPoE internet package [[package]] has been expired. Please contact our support team at [[support_contact]] for renewal assistance.{/if}</textarea>
                                                    </div>
                                                </div>
                                                <script>
                                                    function autoExpand(element) {
                                                        element.style.height = 'auto';
                                                        element.style.height = (element.scrollHeight) + 'px';
                                                    }
                                                </script>
                                                <p class="help-block">
                                                    <b>[[name]]</b> Customer Name | <b>[[username]]</b> Customer username | <b>[[package]]</b> Package name | <b>[[price]]</b> Package price | <b>[[plan_type]]</b> Service type (Hotspot/PPPoE) | <b>[[service_portal]]</b> Hotspot portal URL | <b>[[support_contact]]</b> Support contact | <b>[[expired_date]]</b> Expiration date | <b>[[bills]]</b> Additional bills
                                                </p>
                                            </div>
                                            <div class="form-group">
                                                <label class="control-label">{Lang::T('Reminder 7 Days Messages')}</label>
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <label class="control-label text-primary"><i class="fa fa-wifi"></i> {Lang::T('Hotspot Users')}</label>
                                                        <textarea class="form-control" id="reminder_7_day_hotspot"
                                                            name="reminder_7_day[hotspot]"
                                                            rows="4">{if $_json['reminder_7_day']['hotspot']!=''}{Lang::htmlspecialchars($_json['reminder_7_day']['hotspot'])}{else}Hello *[[name]]*, your Hotspot package *[[package]]* will expire in 7 days. Visit [[service_portal]] to renew and avoid service interruption.{/if}</textarea>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <label class="control-label text-success"><i class="fa fa-ethernet"></i> {Lang::T('PPPoE Users')}</label>
                                                        <textarea class="form-control" id="reminder_7_day_pppoe"
                                                            name="reminder_7_day[pppoe]"
                                                            rows="4">{if $_json['reminder_7_day']['pppoe']!=''}{Lang::htmlspecialchars($_json['reminder_7_day']['pppoe'])}{else}Hello *[[name]]*, your PPPoE package *[[package]]* will expire in 7 days. Contact [[support_contact]] to renew your connection.{/if}</textarea>
                                                    </div>
                                                </div>
                                                <p class="help-block">
                                                    <b>[[name]]</b> Customer Name | <b>[[username]]</b> Customer username | <b>[[package]]</b> Package name | <b>[[price]]</b> Package price | <b>[[expired_date]]</b> Expiration date | <b>[[service_portal]]</b> Hotspot portal URL | <b>[[support_contact]]</b> Support contact | <b>[[bills]]</b> Additional bills
                                                </p>
                                            </div>
                                            <div class="form-group">
                                                <label class="control-label">{Lang::T('Reminder 3 Days Messages')}</label>
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <label class="control-label text-primary"><i class="fa fa-wifi"></i> {Lang::T('Hotspot Users')}</label>
                                                        <textarea class="form-control" id="reminder_3_day_hotspot"
                                                            name="reminder_3_day[hotspot]"
                                                            rows="3">{if $_json['reminder_3_day']['hotspot']!=''}{Lang::htmlspecialchars($_json['reminder_3_day']['hotspot'])}{else}Hello *[[name]]*, your Hotspot package *[[package]]* will expire in 3 days. Renew now at [[service_portal]] to maintain uninterrupted service.{/if}</textarea>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <label class="control-label text-success"><i class="fa fa-ethernet"></i> {Lang::T('PPPoE Users')}</label>
                                                        <textarea class="form-control" id="reminder_3_day_pppoe"
                                                            name="reminder_3_day[pppoe]"
                                                            rows="3">{if $_json['reminder_3_day']['pppoe']!=''}{Lang::htmlspecialchars($_json['reminder_3_day']['pppoe'])}{else}Hello *[[name]]*, your PPPoE package *[[package]]* will expire in 3 days. Contact [[support_contact]] immediately to renew.{/if}</textarea>
                                                    </div>
                                                </div>
                                                <p class="help-block">
                                                    <b>[[name]]</b> Customer Name | <b>[[username]]</b> Customer username | <b>[[package]]</b> Package name | <b>[[price]]</b> Package price | <b>[[expired_date]]</b> Expiration date | <b>[[service_portal]]</b> Hotspot portal URL | <b>[[support_contact]]</b> Support contact | <b>[[bills]]</b> Additional bills
                                                </p>
                                            </div>
                                            <div class="form-group">
                                                <label class="control-label">{Lang::T('Reminder 1 Day Messages')}</label>
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <label class="control-label text-primary"><i class="fa fa-wifi"></i> {Lang::T('Hotspot Users')}</label>
                                                        <textarea class="form-control" id="reminder_1_day_hotspot"
                                                            name="reminder_1_day[hotspot]"
                                                            rows="3">{if $_json['reminder_1_day']['hotspot']!=''}{Lang::htmlspecialchars($_json['reminder_1_day']['hotspot'])}{else}Hello *[[name]]*, your Hotspot package *[[package]]* will expire tomorrow. Please renew at [[service_portal]] to avoid service disruption.{/if}</textarea>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <label class="control-label text-success"><i class="fa fa-ethernet"></i> {Lang::T('PPPoE Users')}</label>
                                                        <textarea class="form-control" id="reminder_1_day_pppoe"
                                                            name="reminder_1_day[pppoe]"
                                                            rows="3">{if $_json['reminder_1_day']['pppoe']!=''}{Lang::htmlspecialchars($_json['reminder_1_day']['pppoe'])}{else}Hello *[[name]]*, your PPPoE package *[[package]]* will expire tomorrow. Contact [[support_contact]] urgently to renew.{/if}</textarea>
                                                    </div>
                                                </div>
                                                <p class="help-block">
                                                    <b>[[name]]</b> Customer Name | <b>[[username]]</b> Customer username | <b>[[package]]</b> Package name | <b>[[price]]</b> Package price | <b>[[expired_date]]</b> Expiration date | <b>[[service_portal]]</b> Hotspot portal URL | <b>[[support_contact]]</b> Support contact | <b>[[bills]]</b> Additional bills
                                                </p>
                                            </div>
                                            <hr>
                                            
                                            <!-- Debug Information Section -->
                                            <div class="card-header" style="background-color: #fff3cd; margin: 20px 0 10px 0; border-left: 4px solid #ffc107;">
                                                <h6 class="card-title" style="margin: 0; color: #856404; font-weight: bold;">
                                                    <i class="fa fa-bug"></i> Debug Information
                                                </h6>
                                            </div>
                                            <div class="alert alert-warning">
                                                <h6><i class="fa fa-info-circle"></i> Troubleshooting Expiry Messages</h6>
                                                <p>If expiry messages are not working, check the following:</p>
                                                <ul>
                                                    <li><strong>Cron Job:</strong> Ensure cron jobs are running: <code>php system/cron.php</code></li>
                                                    <li><strong>Notification Settings:</strong> Check that "Expired Notification" is enabled in App Settings</li>
                                                    <li><strong>SMS/WhatsApp Configuration:</strong> Verify SMS/WhatsApp settings are properly configured</li>
                                                    <li><strong>Phone Numbers:</strong> Ensure customers have valid phone numbers in their profiles</li>
                                                    <li><strong>Plan Type Detection:</strong> Check that plans have correct 'type' field (Hotspot/PPPOE)</li>
                                                </ul>
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <strong>Current Notification Settings:</strong><br>
                                                        <small class="text-muted">
                                                            Expired: {$_c['user_notification_expired']|default:'Not Set'}<br>
                                                            Reminder: {$_c['user_notification_reminder']|default:'Not Set'}<br>
                                                            SMS URL: {$_c['sms_url']|default:'Not Set'}<br>
                                                            WhatsApp URL: {$_c['wa_url']|default:'Not Set'}
                                                        </small>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <strong>Test Cron Job:</strong><br>
                                                        <button type="button" class="btn btn-warning btn-sm" onclick="testCronJob()">
                                                            <i class="fa fa-play"></i> Test Cron Job
                                                        </button>
                                                        <div id="cronTestResult" class="mt-2"></div>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div class="card-header" style="background-color: #f8f9fa; margin: 20px 0 10px 0;">
                                                <h6 class="card-title" style="margin: 0; color: #495057; font-weight: bold;">
                                                    <i class="fa fa-credit-card"></i> {Lang::T('Payment & Invoice Messages')}
                                                </h6>
                                            </div>
                                            <div class="form-group">
                                                <label class="control-label">{Lang::T('Invoice Notification
                                                    Payment')}</label>
                                                <div class="">
                                                    <textarea class="form-control" id="invoice_paid" name="invoice_paid"
                                                        placeholder="Hello [[name]], your internet package [[package]] has been expired"
                                                        rows="20">{Lang::htmlspecialchars($_json['invoice_paid'])}</textarea>
                                                </div>
                                                <p class="help-block">
                                                    <b>[[company_name]]</b> Your Company Name at Settings.
                                                    <b>[[address]]</b> Your Company Address at Settings.
                                                    <b>[[phone]]</b> Your Company Phone at Settings.
                                                    <b>[[invoice]]</b> invoice number.
                                                    <b>[[date]]</b> Date invoice created.
                                                    <b>[[payment_gateway]]</b> Payment gateway user paid from.
                                                    <b>[[payment_channel]]</b> Payment channel user paid from.
                                                    <b>[[type]]</b> is Hotspot/PPPOE.
                                                    <b>[[plan_name]]</b> Internet Package.
                                                    <b>[[plan_price]]</b> Internet Package Prices.
                                                    <b>[[name]]</b> Receiver name.
                                                    <b>[[user_name]]</b> Username internet.
                                                    <b>[[user_password]]</b> User password.
                                                    <b>[[expired_date]]</b> Expired datetime.
                                                    <b>[[footer]]</b> Invoice Footer.
                                                    <b>[[note]]</b> For Notes by admin.
                                                </p>
                                            </div>
                                            <div class="form-group">
                                                <label class="control-label">{Lang::T('Balance Notification
                                                    Payment')}</label>
                                                <div class="">
                                                    <textarea class="form-control" id="invoice_balance"
                                                        name="invoice_balance"
                                                        placeholder="Hello [[name]], your internet package [[package]] has been expired"
                                                        rows="20">{Lang::htmlspecialchars($_json['invoice_balance'])}</textarea>
                                                </div>
                                                <p class="help-block">
                                                    <b>[[company_name]]</b> Your Company Name at Settings.
                                                    <b>[[address]]</b> Your Company Address at Settings.
                                                    <b>[[phone]]</b> Your Company Phone at Settings.
                                                    <b>[[invoice]]</b> invoice number.
                                                    <b>[[date]]</b> Date invoice created.
                                                    <b>[[payment_gateway]]</b> Payment gateway user paid from.
                                                    <b>[[payment_channel]]</b> Payment channel user paid from.
                                                    <b>[[type]]</b> is Hotspot/PPPOE.
                                                    <b>[[plan_name]]</b> Internet Package.
                                                    <b>[[plan_price]]</b> Internet Package Prices.
                                                    <b>[[name]]</b> Receiver name.
                                                    <b>[[user_name]]</b> Username internet.
                                                    <b>[[user_password]]</b> User password.
                                                    <b>[[trx_date]]</b> Transaction datetime.
                                                    <b>[[balance_before]]</b> Balance Before.
                                                    <b>[[balance]]</b> Balance After.
                                                    <b>[[footer]]</b> Invoice Footer.
                                                </p>
                                            </div>
                                            {if $_c['enable_balance'] == 'yes'}
                                            <div class="panel-body">
                                                <div class="form-group">
                                                    <label class="control-label">{Lang::T('Send Balance')}</label>
                                                    <div class="">
                                                        <textarea class="form-control" id="balance_send"
                                                            name="balance_send"
                                                            rows="3">{if $_json['balance_send']}{Lang::htmlspecialchars($_json['balance_send'])}{else}{Lang::htmlspecialchars($_default['balance_send'])}{/if}</textarea>
                                                    </div>
                                                    <p class="help-block">
                                                        <b>[[name]]</b> Receiver name.
                                                        <b>[[balance]]</b> how much balance have been send.
                                                        <b>[[current_balance]]</b> Current Balance.
                                                    </p>
                                                </div>
                                            </div>
                                            <div class="panel-body">
                                                <div class="form-group">
                                                    <label class="control-label">{Lang::T('Received Balance')}</label>
                                                    <div class="">
                                                        <textarea class="form-control" id="balance_received"
                                                            name="balance_received"
                                                            rows="3">{if $_json['balance_received']}{Lang::htmlspecialchars($_json['balance_received'])}{else}{Lang::htmlspecialchars($_default['balance_received'])}{/if}</textarea>
                                                    </div>
                                                    <p class="help-block">
                                                        <b>[[name]]</b> Sender name.
                                                        <b>[[balance]]</b> how much balance have been received.
                                                        <b>[[current_balance]]</b> Current Balance.
                                                    </p>
                                                </div>
                                            </div>
                                            {/if}
                                            <hr>
                                            <div class="card-header" style="background-color: #f8f9fa; margin: 20px 0 10px 0;">
                                                <h6 class="card-title" style="margin: 0; color: #495057; font-weight: bold;">
                                                    <i class="fa fa-user-plus"></i> {Lang::T('Registration Messages')}
                                                </h6>
                                            </div>
                                            <div class="form-group">
                                                <label class="control-label">{Lang::T('User Registration
                                                    Message')}</label>
                                                <div class="">
                                                    <textarea class="form-control" id="user_registration"
                                                        name="user_registration"
                                                        placeholder="Welcome to [[company_name]]! Your account has been created successfully."
                                                        rows="8">{if $_json['user_registration']}{Lang::htmlspecialchars($_json['user_registration'])}{else}{Lang::htmlspecialchars($_default['user_registration'])}{/if}</textarea>
                                                </div>
                                                <p class="help-block">
                                                    <b>[[company_name]]</b> Your Company Name from Settings.
                                                    <b>[[name]]</b> Customer's full name.
                                                    <b>[[user_name]]</b> Customer's username.
                                                    <b>[[username]]</b> Customer's username (alternative).
                                                    <b>[[password]]</b> Customer's password.
                                                    <b>[[service_type]]</b> Service type (Hotspot/PPPOE).
                                                    <b>[[footer]]</b> Company footer message.
                                                </p>
                                            </div>
                                            <hr>
                                            <div class="form-group">
                                                <button class="btn btn-success btn-block" type="submit">{Lang::T('Save
                                                    Changes')}</button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                </form>
            </div>
{include file="sections/footer.tpl"}