<!DOCTYPE html>
<html>
<head>
    <!-- TABLES CSS CODE -->
    <?php include"comman/code_css.php"; ?>
</head>

<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">
    <?php include"sidebar.php"; ?>
    
    <!-- Content Wrapper -->
    <div class="content-wrapper">
        <!-- Content Header -->
        <section class="content-header">
            <h1>
                WhatsApp Settings
                <small>Configure WhatsApp Integration</small>
            </h1>
            <ol class="breadcrumb">
                <li><a href="<?php echo $base_url; ?>dashboard"><i class="fa fa-dashboard"></i> Home</a></li>
                <li class="active">WhatsApp Settings</li>
            </ol>
        </section>

        <!-- Main content -->
        <section class="content">
            <div class="row">
                <!-- Alert Messages -->
                <?php include"comman/code_flashdata.php"; ?>
                
                <div class="col-md-12">
                    <!-- WhatsApp Configuration Box -->
                    <div class="box box-primary">
                        <div class="box-header with-border">
                            <h3 class="box-title">WhatsApp API Configuration</h3>
                        </div>
                        
                        <form id="whatsapp-settings-form" onkeypress="return event.keyCode != 13;">
                            <input type="hidden" name="<?php echo $this->security->get_csrf_token_name();?>" value="<?php echo $this->security->get_csrf_hash();?>">
                            <input type="hidden" id="base_url" value="<?php echo $base_url; ?>">
                            
                            <div class="box-body">
                                <div class="row">
                                    <!-- Enable/Disable WhatsApp -->
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label>WhatsApp Status</label>
                                            <select class="form-control" name="whatsapp_status" id="whatsapp_status">
                                                <option value="0" <?php echo ($whatsapp_status == 0) ? 'selected' : ''; ?>>Disabled</option>
                                                <option value="1" <?php echo ($whatsapp_status == 1) ? 'selected' : ''; ?>>Enabled</option>
                                            </select>
                                        </div>
                                    </div>
                                    
                                    <!-- Business Name -->
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label>Business Name <span class="text-danger">*</span></label>
                                            <input type="text" class="form-control" name="whatsapp_business_name" id="whatsapp_business_name" 
                                                   value="<?php echo $whatsapp_business_name; ?>" placeholder="Your Business Name">
                                            <span id="whatsapp_business_name_msg" style="display:none" class="text-danger"></span>
                                        </div>
                                    </div>
                                </div>

                                <div class="row">
                                    <!-- API URL -->
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label>WhatsApp API URL <span class="text-danger">*</span></label>
                                            <input type="url" class="form-control" name="whatsapp_api_url" id="whatsapp_api_url" 
                                                   value="<?php echo $whatsapp_api_url; ?>" placeholder="https://api.whatsapp.com/v1">
                                            <span id="whatsapp_api_url_msg" style="display:none" class="text-danger"></span>
                                        </div>
                                    </div>
                                    
                                    <!-- API Key -->
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label>API Key <span class="text-danger">*</span></label>
                                            <input type="text" class="form-control" name="whatsapp_api_key" id="whatsapp_api_key" 
                                                   value="<?php echo $whatsapp_api_key; ?>" placeholder="Your API Key">
                                            <span id="whatsapp_api_key_msg" style="display:none" class="text-danger"></span>
                                        </div>
                                    </div>
                                </div>

                                <div class="row">
                                    <!-- API Secret -->
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label>API Secret</label>
                                            <input type="password" class="form-control" name="whatsapp_api_secret" id="whatsapp_api_secret" 
                                                   value="<?php echo $whatsapp_api_secret; ?>" placeholder="Your API Secret">
                                        </div>
                                    </div>
                                    
                                    <!-- Instance ID -->
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label>Instance/Phone Number ID</label>
                                            <input type="text" class="form-control" name="whatsapp_instance_id" id="whatsapp_instance_id" 
                                                   value="<?php echo $whatsapp_instance_id; ?>" placeholder="Instance ID or Phone Number">
                                        </div>
                                    </div>
                                </div>

                                <div class="row">
                                    <!-- Webhook URL -->
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label>Webhook URL</label>
                                            <input type="url" class="form-control" name="whatsapp_webhook_url" id="whatsapp_webhook_url" 
                                                   value="<?php echo $whatsapp_webhook_url; ?>" placeholder="https://yourdomain.com/whatsapp/webhook">
                                            <small class="text-muted">URL to receive incoming messages</small>
                                        </div>
                                    </div>
                                    
                                    <!-- Webhook Token -->
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label>Webhook Verification Token</label>
                                            <input type="text" class="form-control" name="whatsapp_webhook_token" id="whatsapp_webhook_token" 
                                                   value="<?php echo $whatsapp_webhook_token; ?>" placeholder="Verification Token">
                                        </div>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label>Default Message</label>
                                            <textarea class="form-control" name="whatsapp_default_message" id="whatsapp_default_message" 
                                                      rows="3" placeholder="Default message for customers"><?php echo $whatsapp_default_message; ?></textarea>
                                        </div>
                                    </div>
                                </div>

                                <!-- Message Types -->
                                <div class="row">
                                    <div class="col-md-12">
                                        <h4>Automatic Message Settings</h4>
                                    </div>
                                    
                                    <div class="col-md-4">
                                        <div class="form-group">
                                            <label>
                                                <input type="checkbox" name="whatsapp_send_invoice" value="1" 
                                                       <?php echo ($whatsapp_send_invoice == 1) ? 'checked' : ''; ?>>
                                                Send Invoice Messages
                                            </label>
                                            <br><small class="text-muted">Automatically send invoice messages to customers</small>
                                        </div>
                                    </div>
                                    
                                    <div class="col-md-4">
                                        <div class="form-group">
                                            <label>
                                                <input type="checkbox" name="whatsapp_send_reminders" value="1" 
                                                       <?php echo ($whatsapp_send_reminders == 1) ? 'checked' : ''; ?>>
                                                Send Payment Reminders
                                            </label>
                                            <br><small class="text-muted">Send payment reminder messages</small>
                                        </div>
                                    </div>
                                    
                                    <div class="col-md-4">
                                        <div class="form-group">
                                            <label>
                                                <input type="checkbox" name="whatsapp_send_notifications" value="1" 
                                                       <?php echo ($whatsapp_send_notifications == 1) ? 'checked' : ''; ?>>
                                                Send General Notifications
                                            </label>
                                            <br><small class="text-muted">Send order confirmations and updates</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Box Footer -->
                            <div class="box-footer">
                                <div class="row">
                                    <div class="col-md-4">
                                        <button type="button" id="test_connection" class="btn btn-info">
                                            <i class="fa fa-plug"></i> Test Connection
                                        </button>
                                    </div>
                                    <div class="col-md-4">
                                        <button type="button" id="send_test_message" class="btn btn-warning">
                                            <i class="fa fa-whatsapp"></i> Send Test Message
                                        </button>
                                    </div>
                                    <div class="col-md-4 text-right">
                                        <button type="button" id="save_settings" class="btn btn-success">
                                            <i class="fa fa-save"></i> Save Settings
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </section>
    </div>

    <?php include"footer.php"; ?>
    <div class="control-sidebar-bg"></div>
</div>

<!-- SOUND CODE -->
<?php include"comman/code_js_sound.php"; ?>
<!-- TABLES CODE -->
<?php include"comman/code_js.php"; ?>

<script type="text/javascript">
$(document).ready(function() {
    // Save Settings
    $('#save_settings').on("click", function(e) {
        e.preventDefault();
        var base_url = $("#base_url").val();
        var flag = true;

        function check_field(id) {
            if(!$("#"+id).val()) {
                $('#'+id+'_msg').fadeIn(200).show().html('Required Field').addClass('required');
                flag = false;
            } else {
                $('#'+id+'_msg').fadeOut(200).hide();
            }
        }

        // Validate required fields
        check_field("whatsapp_business_name");
        if($('#whatsapp_status').val() == '1') {
            check_field("whatsapp_api_url");
            check_field("whatsapp_api_key");
        }

        if(flag == false) {
            toastr["warning"]("Please fill all required fields!");
            return;
        }

        $(this).attr('disabled', true);
        $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');

        var formData = new FormData($('#whatsapp-settings-form')[0]);
        
        $.ajax({
            type: 'POST',
            url: base_url + 'whatsapp/update_settings',
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            success: function(result) {
                if(result == "success") {
                    toastr["success"]("WhatsApp settings saved successfully!");
                } else {
                    toastr["error"]("Failed to save settings. Please try again!");
                }
                $("#save_settings").attr('disabled', false);
                $(".overlay").remove();
            },
            error: function() {
                toastr["error"]("An error occurred. Please try again!");
                $("#save_settings").attr('disabled', false);
                $(".overlay").remove();
            }
        });
    });

    // Test Connection
    $('#test_connection').on("click", function(e) {
        e.preventDefault();
        var base_url = $("#base_url").val();
        
        if(!$('#whatsapp_api_url').val() || !$('#whatsapp_api_key').val()) {
            toastr["warning"]("Please enter API URL and Key first!");
            return;
        }

        $(this).attr('disabled', true);
        $(this).html('<i class="fa fa-spinner fa-spin"></i> Testing...');

        $.ajax({
            type: 'POST',
            url: base_url + 'whatsapp/test_connection',
            dataType: 'json',
            success: function(result) {
                if(result.status == "success") {
                    toastr["success"](result.message);
                } else {
                    toastr["error"](result.message);
                }
                $("#test_connection").attr('disabled', false);
                $("#test_connection").html('<i class="fa fa-plug"></i> Test Connection');
            },
            error: function() {
                toastr["error"]("Connection test failed!");
                $("#test_connection").attr('disabled', false);
                $("#test_connection").html('<i class="fa fa-plug"></i> Test Connection');
            }
        });
    });

    // Send Test Message
    $('#send_test_message').on("click", function(e) {
        e.preventDefault();
        var base_url = $("#base_url").val();
        
        if(!$('#whatsapp_api_url').val() || !$('#whatsapp_api_key').val() || !$('#whatsapp_instance_id').val()) {
            toastr["warning"]("Please enter API URL, Key and Instance ID first!");
            return;
        }

        if(!confirm("Send test message to +918883888012?")) {
            return;
        }

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

        $.ajax({
            type: 'POST',
            url: base_url + 'whatsapp/send_test_message',
            dataType: 'json',
            success: function(result) {
                if(result.status == "success") {
                    toastr["success"]("Test message sent successfully to +918883888012!");
                } else {
                    toastr["error"]("Failed to send test message: " + result.message);
                }
                $("#send_test_message").attr('disabled', false);
                $("#send_test_message").html('<i class="fa fa-whatsapp"></i> Send Test Message');
            },
            error: function() {
                toastr["error"]("Failed to send test message!");
                $("#send_test_message").attr('disabled', false);
                $("#send_test_message").html('<i class="fa fa-whatsapp"></i> Send Test Message');
            }
        });
    });

    // Toggle required fields based on status
    $('#whatsapp_status').change(function() {
        if($(this).val() == '1') {
            $('#whatsapp_api_url, #whatsapp_api_key').attr('required', true);
        } else {
            $('#whatsapp_api_url, #whatsapp_api_key').removeAttr('required');
        }
    });
});
</script>

<!-- Make sidebar menu highlighter/selector -->
<script>$(".whatsapp-settings-active-li").addClass("active");</script>
</body>
</html>
