<script type="text/javascript">
$(document).ready(function(){
    // Save template form
    $('.template-form').submit(function(e){
        e.preventDefault();
        var form = $(this);
        var templateId = form.data('id');
        var btn = form.find('button[type="submit"]');
        var originalText = btn.html();

        btn.html('<i class="fas fa-spinner fa-spin"></i> Saving...').prop('disabled', true);

        var formData = {
            updte: 1,
            template_id: form.find('input[name="template_id"]').val(),
            template_key: form.find('input[name="template_key"]').val(),
            template_message: form.find('textarea[name="template_message"]').val(),
            is_active: form.find('input[name="is_active"]').is(':checked') ? 1 : 0
        };

        $.ajax({
            url: "save_whatsapp_template.php",
            type: "POST",
            data: formData,
            success: function(response) {
                var result = JSON.parse(response);
                if(result.error == 0) {
                    swal({title: "Success", text: result.error_msg, icon: "success", buttons: false, timer: 2000});
                    // Update badge
                    var badge = $('#template_' + templateId + ' .badge');
                    if(formData.is_active == 1) {
                        badge.removeClass('badge-secondary').addClass('badge-success').text('Active');
                    } else {
                        badge.removeClass('badge-success').addClass('badge-secondary').text('Inactive');
                    }
                } else {
                    swal({title: "Error", text: result.error_msg, icon: "error", buttons: false, timer: 2000});
                }
                btn.html(originalText).prop('disabled', false);
            },
            error: function() {
                swal({title: "Error", text: "Something went wrong!", icon: "error", buttons: false, timer: 2000});
                btn.html(originalText).prop('disabled', false);
            }
        });
    });

    // Test template button
    var currentTemplateId = null;
    $('.test-template-btn').click(function(){
        currentTemplateId = $(this).data('id');
        var message = $('#template_' + currentTemplateId + ' textarea[name="template_message"]').val();

        // Replace variables with sample data for preview
        var previewMsg = message
            .replace(/{site_name}/g, '<?= $res_site[0]['site_name']; ?>')
            .replace(/{username}/g, 'TESTUSER')
            .replace(/{password}/g, '********')
            .replace(/{name}/g, 'Test User')
            .replace(/{mobile}/g, '9876543210')
            .replace(/{email}/g, 'test@example.com')
            .replace(/{amount}/g, '100')
            .replace(/{number}/g, '9876543210')
            .replace(/{txn_id}/g, 'TXN123456')
            .replace(/{operator}/g, 'Airtel')
            .replace(/{balance}/g, '5000')
            .replace(/{otp}/g, '123456')
            .replace(/{login_url}/g, '<?= $res_site[0]['site_url']; ?>')
            .replace(/{reason}/g, 'Invalid details')
            .replace(/{date}/g, new Date().toLocaleDateString())
            .replace(/{time}/g, new Date().toLocaleTimeString())
            .replace(/\\n/g, '\n');

        $('#test_message').val(previewMsg);
        $('#testTemplateModal').modal('show');
    });

    // Send test message
    $('#send_test_btn').click(function(){
        var mobile = $('#test_mobile').val();
        var message = $('#test_message').val();

        if(!mobile || mobile.length < 10) {
            swal({title: "Error", text: "Please enter a valid mobile number", icon: "error", buttons: false, timer: 2000});
            return;
        }

        var btn = $(this);
        btn.html('<i class="fas fa-spinner fa-spin"></i> Sending...').prop('disabled', true);

        $.ajax({
            url: "sendWhatsapp.php",
            type: "POST",
            data: {
                updte: 1,
                mobile: mobile,
                message: message
            },
            success: function(response) {
                var result = JSON.parse(response);
                if(result.error == 0) {
                    swal({title: "Success", text: "Test message sent successfully!", icon: "success", buttons: false, timer: 2000});
                    $('#testTemplateModal').modal('hide');
                } else {
                    swal({title: "Error", text: result.error_msg, icon: "error", buttons: false, timer: 2000});
                }
                btn.html('<i class="fab fa-whatsapp"></i> Send Test').prop('disabled', false);
            },
            error: function() {
                swal({title: "Error", text: "Something went wrong!", icon: "error", buttons: false, timer: 2000});
                btn.html('<i class="fab fa-whatsapp"></i> Send Test').prop('disabled', false);
            }
        });
    });
});
</script>
