<?php
/*
Plugin Name: Slack Chat with AI Agents
Plugin URI: http://www.socialintents.com
Description: Use Slack to chat with your website visitors. Automate website support with AI Agents you can train on your own content and handoff to your team in Slack seamlessly. To get started, go to your Plugin Settings and register for a Free Trial or grab your API key from your account.
Version: 1.4.47
Author: Social Intents
Author URI: http://www.socialintents.com/
*/

$scsi_domain = plugins_url();
add_action('init', 'scsi_init');
add_action('admin_notices', 'scsi_notice');
add_filter('plugin_action_links', 'scsi_plugin_actions', 10, 2);
add_action('wp_footer', 'scsi_insert',4);
add_action('admin_footer', 'siRedirect');

define('SI_DASHBOARD_URL', "https://www.socialintents.com/webInbox.do");
define('SI_SMALL_LOGO',plugin_dir_url( __FILE__ ).'si-small.png');

function scsi_init() {
    if(function_exists('current_user_can') && current_user_can('manage_options')) {
        add_action('admin_menu', 'scsi_add_settings_page');
        add_action('admin_menu', 'scsi_create_menu');
    }
}

function scsi_insert() {
    if(strlen(get_option('scsi_widgetID')) == 32 ) {
        echo("\n\n<!-- www.socialintents.com -->\n<script type=\"text/javascript\">\n");
        echo("(function() {function socialintents(){\n");
        echo("    var siJsHost = ((\"https:\" === document.location.protocol) ? \"https://\" : \"http://\");\n");
        echo("    var s = document.createElement('script');s.type = 'text/javascript';s.async = true;s.src = siJsHost+'www.socialintents.com/api/chat/socialintents.1.4.js#" . esc_js(get_option('scsi_widgetID')) . "';\n");
        echo("    var x = document.getElementsByTagName('script')[0];x.parentNode.insertBefore(s, x);};\n");
        echo("if (window.attachEvent)window.attachEvent('onload', socialintents);else window.addEventListener('load', socialintents, false);})();\n");
        echo("</script>\n");
    }
}

function scsi_notice() {
    if(!get_option('scsi_widgetID')) {
        echo('<div class="error"><p><strong>'.sprintf(__('Your Slack Chat Plugin is disabled. Please go to the <a href="%s">plugin settings</a> to register.  ' ), admin_url('options-general.php?page=socialintents-slack-chat')).'</strong></p></div>');
    }
}

function scsi_plugin_actions($links, $file) {
    static $this_plugin;
    $scsi_domain = plugins_url();
    if(!$this_plugin) $this_plugin = plugin_basename(__FILE__);
    if($file == $this_plugin && function_exists('admin_url')) {
        $settings_link = '<a href="'.admin_url('options-general.php?page=socialintents-slack-chat').'">'.__('Settings', $scsi_domain).'</a>';
        array_unshift($links, $settings_link);
    }
    return($links);
}

function scsi_add_settings_page() {
    function scsi_settings_page() {
        global $scsi_domain;
        $widget_id = esc_attr(get_option('scsi_widgetID'));
        ?>
<div class="wrap">
    <h2><?php _e('Slack Chat by Social Intents', $scsi_domain) ?></h2>

    <div class="metabox-holder meta-box-sortables ui-sortable pointer">

    <div class="postbox" style="float:left;width:35em;margin-right:20px;">
        <h3 class="hndle"><span id="scsi_noAccountSpan"><?php _e('Slack Chat by Social Intents', $scsi_domain) ?></span></h3>
        <div id="scsi_register" class="inside" style="padding: -30px 10px">
            <p style="text-align:center">
                <?php wp_nonce_field('update-options'); ?>
                <a href="https://www.socialintents.com/" title="Chat from Slack">
                    <img src="<?php echo esc_url(plugins_url('socialintents.png', __FILE__)); ?>" height="94" />
                </a>
            </p>
            <p><?php printf(__('Join 55,000+ companies using our platform improve customer service and sell more. Visit %1$sSocial Intents%2$s.', $scsi_domain), '<a href="https://www.socialintents.com" target="_blank">', '', '</a>'); ?></p>
            <div style='text-align:center'>
                <a href='https://www.socialintents.com/signup.do?wptype=wpchat' class="button button-primary" target="_blank">Register For Free Now!</a>
            </div>
        </div>
        <div id="scsi_registerComplete" class="inside" style="padding: -20px 10px;display:none;">
            <p>View previous chats, train your AI and respond to chats right from Slack.</p>
            <p><a href='https://help.socialintents.com' target="_blank">Getting Started</a></p>
            <p>
                <a href='https://www.socialintents.com/webInbox.do' class="button button-primary" target="_blank">Inbox</a>
                <a href='https://www.socialintents.com/webWidget.do?id=<?php echo urlencode($widget_id); ?>' class="button button-primary" target="_blank">Settings</a>
                <a href='https://www.socialintents.com/preview.do?wid=<?php echo urlencode($widget_id); ?>' class="button button-primary" target="_blank">Preview</a>
            </p><br>
            <div style="text-align:center">
                <a id="changeWidget" class="" target="_blank">Enter Different App Key</a>
            </div>
        </div>
    </div>

    <div id="addAppKey" class="postbox" style="float:left;width:35em;margin-right:20px">
        <h3 class="hndle"><span><?php _e('Already Registered?  Enter your API Key', $scsi_domain) ?></span></h3>
        <div class="inside" style="padding: 0 10px">
            <form id="saveSettings" method="post" action="options.php">
                <?php wp_nonce_field('update-options'); ?>
                <p><label for="scsi_widgetID">Enter your App Key below to activate your plugin.</label><br />
                    <input type="text" name="scsi_widgetID" id="scsi_widgetID" placeholder="Your API Key" value="<?php echo esc_attr($widget_id); ?>" style="width:100%" />
                </p>
                <p class="submit" style="padding:0">
                    <input type="hidden" name="action" value="update" />
                    <input type="hidden" name="page_options" value="scsi_widgetID" />
                    <input type="submit" name="scsi_submit" id="scsi_submit" value="<?php _e('Save Settings', $scsi_domain) ?>" class="button-primary" />
                    <a href='https://www.socialintents.com/webApps.do' class="button button-primary" target="_blank">Find My API Key</a>
                </p>
                <br><img src="<?php echo esc_url(plugins_url('app-key.png', __FILE__)); ?>" width="250" />
            </form>
        </div>
    </div>

    </div>
</div>
<script>
jQuery(document).ready(function($) {
    var scsi_wid = $('#scsi_widgetID').val();
    if (scsi_wid !== '') {
        $("#scsi_register").hide();
        $("#addAppKey").hide();
        $("#scsi_registerComplete").show();
        $("#scsi_noAccountSpan").html("Slack Chat Settings");
    }
    $(document).on("click", "#changeWidget", function () {
        $("#addAppKey").show();
    });

    $(document).on("click", "#scsi_inputSaveSettings", function () {
        var scsi_wid = encodeURIComponent($('#scsi_widgetID').val());
        var scsi_tt  = encodeURIComponent($('#scsi_tab_text').val() || '');
        var scsi_ht  = encodeURIComponent($('#scsi_header_text').val() || '');
        var scsi_to  = encodeURIComponent($('#scsi_tab_offline_text').val() || '');
        var scsi_tc  = encodeURIComponent($('#scsi_tab_color').val() || '');
        var scsi_top = encodeURIComponent($('#scsi_time_on_page').val() || '');

        var url = 'https://www.socialintents.com/json/jsonSaveChatSettings.jsp?' +
                  'tc=' + scsi_tc + '&tt=' + scsi_tt + '&ht=' + scsi_ht +
                  '&wid=' + scsi_wid + '&to=' + scsi_to + '&top=' + scsi_top + '&callback=?';

        sessionStorage.removeItem("settings");

        $.ajax({
            type: 'GET',
            url: url,
            async: false,
            jsonpCallback: 'jsonCallBack',
            contentType: "application/json",
            dataType: 'jsonp',
            success: function(json) {
                $('#scsi_widgetID').val(json.key);
                sessionStorage.removeItem("settings");
                sessionStorage.removeItem("socialintents_vs_chat");
                sessionStorage.setItem("hasSeenPopup", "false");
                $("#saveDetailSettings").submit();
            },
            error: function(e) {
                console.error("Settings save failed:", e);
            }
        });
    });
});
</script>
<?php
    }
    $scsi_domain = plugins_url();
    add_submenu_page('options-general.php', __('Slack Chat', $scsi_domain), __('Slack Chat', $scsi_domain), 'manage_options', 'socialintents-slack-chat', 'scsi_settings_page');
}

function addSilcLink() {
    $dir = plugin_dir_path(__FILE__);
    include $dir . 'options.php';
}

function scsi_create_menu() {
    add_menu_page('Slack Chat', 'Slack Chat', 'administrator', 'scsi_dashboard', 'addSilcLink', plugins_url('socialintents-slack-chat/si-small.png'));
}

function siRedirect() {
    $redirectUrl = "https://www.socialintents.com/webInbox.do";
    echo "<script> jQuery('a[href=\"admin.php?page=scsi_dashboard\"]').attr('href', '" . esc_url($redirectUrl) . "').attr('target', '_blank') </script>";
}
?>