function mc_mm_setup()
{
    $mm_helpers = new MailchimpMailmunchHelpers();
    $mc_mm_data = unserialize(get_option("mc_mm_data"));
    $mc_mm_data["site_url"] = home_url();
    $mc_mm_data["site_name"] = get_bloginfo();
    update_option("mc_mm_data", serialize($mc_mm_data));
    // This is a POST request. Let's save data first.
    if ($_POST) {
        $post_data = isset($_POST["mc_mm_data"]) ? $_POST["mc_mm_data"] : array();
        $post_action = $_POST["action"];
        if ($post_action == "save_settings") {
            $mc_mm_data = array_merge(unserialize(get_option('mc_mm_data')), $post_data);
            update_option("mc_mm_data", serialize($mc_mm_data));
        } else {
            if ($post_action == "sign_in") {
                $mm = new MailchimpMailmunchApi($_POST["email"], $_POST["password"], "http://" . MAILCHIMP_MAILMUNCH_URL);
                if ($mm->validPassword()) {
                    update_option("mc_mm_user_email", $_POST["email"]);
                    update_option("mc_mm_user_password", base64_encode($_POST["password"]));
                    delete_option("mc_mm_guest_user");
                }
            } else {
                if ($post_action == "sign_up") {
                    if (empty($_POST["email"]) || empty($_POST["password"])) {
                        $invalid_email_password = true;
                    } else {
                        $account_info = $mm_helpers->getEmailPassword();
                        $mc_mm_email = $account_info['email'];
                        $mc_mm_password = $account_info['password'];
                        $mm = new MailchimpMailmunchApi($mc_mm_email, $mc_mm_password, "http://" . MAILCHIMP_MAILMUNCH_URL);
                        if ($mm->isNewUser($_POST['email'])) {
                            $update_result = $mm->updateGuest($_POST['email'], $_POST['password']);
                            $result = json_decode($update_result['body']);
                            update_option("mc_mm_user_email", $result->email);
                            update_option("mc_mm_user_password", base64_encode($_POST['password']));
                            if (!$result->guest_user) {
                                delete_option("mc_mm_guest_user");
                            }
                            $mc_mm_email = $result->email;
                            $mc_mm_password = $_POST['password'];
                            // We have update the guest with real email address, let's create a site now
                            $mm = new MailchimpMailmunchApi($mc_mm_email, $mc_mm_password, "http://" . MAILCHIMP_MAILMUNCH_URL);
                            $update_result = $mm->updateSite($mc_mm_data["site_name"], $mc_mm_data["site_url"]);
                            $result = json_decode($update_result['body']);
                            $mc_mm_data = unserialize(get_option("mc_mm_data"));
                            $mc_mm_data["site_url"] = $result->domain;
                            $mc_mm_data["site_name"] = $result->name;
                            update_option("mc_mm_data", serialize($mc_mm_data));
                        } else {
                            $user_exists = true;
                        }
                    }
                } else {
                    if ($post_action == "unlink_account") {
                        $mc_mm_data = array();
                        $mc_mm_data["site_url"] = home_url();
                        $mc_mm_data["site_name"] = get_bloginfo();
                        update_option("mc_mm_data", serialize($mc_mm_data));
                        delete_option("mc_mm_user_email");
                        delete_option("mc_mm_user_password");
                    } else {
                        if ($post_action == "delete_widget") {
                            if ($_POST["site_id"] && $_POST["widget_id"]) {
                                $account_info = $mm_helpers->getEmailPassword();
                                $mc_mm_email = $account_info['email'];
                                $mc_mm_password = $account_info['password'];
                                $mm = new MailchimpMailmunchApi($account_info['email'], $account_info["password"], "http://" . MAILCHIMP_MAILMUNCH_URL);
                                $request = $mm->deleteWidget($_POST["site_id"], $_POST["widget_id"]);
                            }
                        } else {
                            if ($post_action == "create_site") {
                                $site_url = empty($_POST["site_url"]) ? get_bloginfo() : $_POST["site_url"];
                                $site_name = empty($_POST["site_name"]) ? home_url() : $_POST["site_name"];
                                $account_info = $mm_helpers->getEmailPassword();
                                $mm = new MailchimpMailmunchApi($account_info['email'], $account_info["password"], "http://" . MAILCHIMP_MAILMUNCH_URL);
                                $request = $mm->createSite($site_name, $site_url);
                                $site = json_decode($request['body']);
                                if (!empty($site->id)) {
                                    $mc_mm_data = unserialize(get_option("mc_mm_data"));
                                    $mc_mm_data["site_id"] = $site->id;
                                    $mc_mm_data["script_src"] = $site->javascript_url;
                                    update_option("mc_mm_data", serialize($mc_mm_data));
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    // If the user does not exists, create a GUEST user
    if (get_option("mc_mm_user_email") == "") {
        $mc_mm_email = "guest_" . uniqid() . "@mailmunch.co";
        $mc_mm_password = uniqid();
        $mm = new MailchimpMailmunchApi($mc_mm_email, $mc_mm_password, "http://" . MAILCHIMP_MAILMUNCH_URL);
        $mm->createGuestUser();
        update_option("mc_mm_user_email", $mc_mm_email);
        update_option("mc_mm_user_password", base64_encode($mc_mm_password));
        update_option("mc_mm_guest_user", true);
    }
    // If we already have the user's email stored, let's create the API instance
    // If we don't have it yet, make sure NOT to phone home any user data
    if (get_option("mc_mm_user_email") != "") {
        $account_info = $mm_helpers->getEmailPassword();
        $mc_mm_email = $account_info['email'];
        $mc_mm_password = $account_info['password'];
        $mm = new MailchimpMailmunchApi($mc_mm_email, $mc_mm_password, "http://" . MAILCHIMP_MAILMUNCH_URL);
        $pass_check = $mm->validPassword();
        if (is_wp_error($pass_check)) {
            echo $pass_check->get_error_message();
            return;
        }
        if (!$pass_check) {
            // Invalid user, create a GUEST user
            $mc_mm_email = "guest_" . uniqid() . "@mailmunch.co";
            $mc_mm_password = uniqid();
            $mm = new MailchimpMailmunchApi($mc_mm_email, $mc_mm_password, "http://" . MAILCHIMP_MAILMUNCH_URL);
            $mm->createGuestUser();
            update_option("mc_mm_user_email", $mc_mm_email);
            update_option("mc_mm_user_password", base64_encode($mc_mm_password));
            update_option("mc_mm_guest_user", true);
        }
    }
    $mc_mm_guest_user = get_option("mc_mm_guest_user");
    if ($mc_mm_guest_user) {
        // This is a Guest USER. Do not collect any user data.
        $sites = $mm_helpers->createAndGetGuestSites($mm);
    } else {
        $sites = $mm_helpers->createAndGetSites($mm);
    }
    if (isset($mc_mm_data["site_id"])) {
        // If there's a site already chosen, we need to get and save it's script_src in WordPress
        $site = $mm_helpers->getSite($sites, $mc_mm_data["site_id"]);
        if ($site) {
            $mc_mm_data = array_merge(unserialize(get_option('mc_mm_data')), array("script_src" => $site->javascript_url));
            update_option("mc_mm_data", serialize($mc_mm_data));
        } else {
            // The chosen site does not exist in the mailmunch account any more, remove it locally
            $site_not_found = true;
            $mc_mm_data = unserialize(get_option('mc_mm_data'));
            unset($mc_mm_data["site_id"]);
            unset($mc_mm_data["script_src"]);
            update_option("mc_mm_data", serialize($mc_mm_data));
        }
    }
    if (!isset($mc_mm_data["site_id"])) {
        // If there's NO chosen site yet
        if (sizeof($sites) == 1 && ($sites[0]->name == get_bloginfo() || $sites[0]->name == "WordPress")) {
            // If this mailmunch account only has 1 site and its name matches this WordPress blogs
            $site = $sites[0];
            if ($site) {
                $mc_mm_data = array_merge(unserialize(get_option('mc_mm_data')), array("site_id" => $site->id, "script_src" => $site->javascript_url));
                update_option("mc_mm_data", serialize($mc_mm_data));
            }
        } else {
            if (sizeof($sites) > 0) {
                // If this mailmunch account has one or more sites, let the user choose one
                ?>
  <div class="container">
    <div class="page-header">
      <h1>Choose Your Site</h1>
    </div>

    <p>Choose the site that you would like to link with your WordPress.</p>

    <div id="choose-site-form">
      <form action="" method="POST">
        <div class="form-group">
          <input type="hidden" name="action" value="save_settings" />

          <select name="mc_mm_data[site_id]">
            <?php 
                foreach ($sites as $site) {
                    ?>
            <option value="<?php 
                    echo $site->id;
                    ?>
"><?php 
                    echo $site->name;
                    ?>
</option>
            <?php 
                }
                ?>
          </select>
        </div>

        <div class="form-group">
          <input type="submit" value="Save Settings" class="button-primary" />
        </div>
      </form>

      <p>
        Don't see this site above? <a href="" onclick="document.getElementById('create-site-form').style.display = 'block'; document.getElementById('choose-site-form').style.display = 'none'; return false;">Create New Site</a>
      </p>
    </div>

    <div id="create-site-form" style="display: none;">
      <form action="" method="POST">
        <input type="hidden" name="action" value="create_site" />

        <div class="form-group">
          <label>Site Name</label>
          <input type="text" name="site_name" value="<?php 
                echo get_bloginfo();
                ?>
" />
        </div>

        <div class="form-group">
          <label>Site URL</label>
          <input type="text" name="site_url" value="<?php 
                echo home_url();
                ?>
" />
        </div>

        <div class="form-group">
          <input type="submit" value="Create Site" class="button-primary" />
        </div>
      </form>

      <p>
        Already have a site in your MailMunch account? <a href="" onclick="document.getElementById('create-site-form').style.display = 'none'; document.getElementById('choose-site-form').style.display = 'block'; return false;">Choose Site</a>
      </p>
    </div>
  </div>
<?php 
                return;
            }
        }
    }
    $request = $mm->getWidgetsHtml($mc_mm_data["site_id"]);
    $widgets = $request['body'];
    $widgets = str_replace("{{EMAIL}}", $mc_mm_email, $widgets);
    $widgets = str_replace("{{PASSWORD}}", $mc_mm_password, $widgets);
    echo $widgets;
    if ($mc_mm_guest_user) {
        $current_user = wp_get_current_user();
        ?>

<div id="signup-signin-box-overlay" onclick="hideSignupBox();" style="display: none;"></div>

<div id="signup-signin-box" style="display:none;">
  <a id="signup-signin-close" onclick="hideSignupBox();">
    <img src="<?php 
        echo plugins_url('img/close.png', __FILE__);
        ?>
" />
  </a>

  <div id="sign-up-form" class="<?php 
        if (!$_POST || $_POST["action"] != "sign_in" && $_POST["action"] != "unlink_account") {
            ?>
 active<?php 
        }
        ?>
">
    <div class="form-container">
      <h2 class="modal-header">Sign Up</h2>
      <p>To activate your MailChimp forms, we will now create your account on MailMunch (<a onclick="showWhyAccount();" id="why-account-btn">Why?</a>).</p>

      <div id="why-account" class="alert alert-warning" style="display: none;">
        <h4>Why do I need a MailMunch account?</h4>

        <p>
          MailMunch is a not just a WordPress plugin but a standalone service. An account is required to identify your WordPress and serve your MailChimp forms.
        </p>
      </div>

      <?php 
        if (isset($user_exists)) {
            ?>
      <div id="invalid-alert" class="alert alert-danger signup-alert" role="alert">Account with this email already exists. Please sign in using your password.</div>
      <?php 
        } else {
            if (isset($invalid_email_password)) {
                ?>
      <div id="invalid-alert" class="alert alert-danger signup-alert" role="alert">Invalid email or password. Please enter a valid email and password below.</div>
      <?php 
            }
        }
        ?>

      <form action="" method="POST">
        <input type="hidden" name="action" value="sign_up" />

        <div class="form-group">
          <label>Wordpress Name</label>
          <input type="text" placeholder="Site Name" name="site_name" value="<?php 
        echo $mc_mm_data["site_name"];
        ?>
" class="form-control">
        </div>

        <div class="form-group">
          <label>Wordpress URL</label>
          <input type="text" placeholder="Site URL" name="site_url" value="<?php 
        echo $mc_mm_data["site_url"];
        ?>
" class="form-control">
        </div>

        <div class="form-group">
          <label>Email Address</label>
          <input type="email" placeholder="Email Address" name="email" value="<?php 
        echo $current_user->user_email;
        ?>
" class="form-control">
        </div>

        <div class="form-group">
          <label>Password</label>
          <input type="password" placeholder="Password" name="password" class="form-control" />
        </div>

        <div class="form-group">
          <input type="submit" value="Sign Up &raquo;" class="btn btn-success btn-lg" />
        </div>
      </form>
    </div>

    <p>Already have an account? <a id="show-sign-in" onclick="showSignInForm();">Sign In</a></p>
  </div>

  <div id="sign-in-form" class="<?php 
        if ($_POST && ($_POST["action"] == "sign_in" || $_POST["action"] == "unlink_account")) {
            ?>
 active<?php 
        }
        ?>
">
    <h2 class="modal-header">Sign In</h2>
    <p>Sign in using your email and password below.</p>

    <?php 
        if ($_POST && $_POST["action"] == "sign_in") {
            ?>
    <div id="invalid-alert" class="alert alert-danger signin-alert" role="alert">Invalid Email or Password. Please try again.</div>
    <?php 
        }
        ?>

    <div class="form-container">
      <form action="" method="POST">
        <input type="hidden" name="action" value="sign_in" />

        <div class="form-group">
          <label>Email Address</label>
          <input type="email" placeholder="Email Address" name="email" class="form-control" value="<?php 
        if (isset($_POST["email"])) {
            echo $_POST["email"];
        }
        ?>
" />
        </div>
        <div class="form-group">
          <label>Password</label>
          <input type="password" placeholder="Password" name="password" class="form-control" />
        </div>

        <div class="form-group">
          <input type="submit" value="Sign In &raquo;" class="btn btn-success btn-lg" />
        </div>
      </form>
    </div>

    <p>Forgot your password? <a href="http://<?php 
        echo MAILCHIMP_MAILMUNCH_URL;
        ?>
/users/password/new" target="_blank">Click here</a> to retrieve it.</p>
    <p>Don't have an account? <a id="show-sign-up" onclick="showSignUpForm();">Sign Up</a></p>
  </div>
</div>

<?php 
        if ($_POST) {
            ?>
<script>
jQuery(window).load(function() {
  <?php 
            if ($_POST && ($_POST["action"] == "sign_in" || $_POST["action"] == "unlink_account")) {
                ?>
  showSignInForm();
  <?php 
            } else {
                ?>
  showSignUpForm();
  <?php 
            }
            ?>
});
</script>
<?php 
        }
    }
}
    /**
     * Back-end widget form.
     *
     * @see WP_Widget::form()
     *
     * @param array $instance Previously saved values from database.
     */
    public function form($instance)
    {
        if (isset($instance['title'])) {
            $title = $instance['title'];
        } else {
            $title = __('Optin Form', 'text_domain');
        }
        if (isset($instance['form_id'])) {
            $form_id = $instance['form_id'];
        }
        $mc_mm_data = unserialize(get_option("mc_mm_data"));
        $mc_mm_user_email = get_option("mc_mm_user_email");
        $mc_mm_user_password = get_option("mc_mm_user_password");
        if (!empty($mc_mm_user_email) && !empty($mc_mm_user_password) && !empty($mc_mm_data["site_id"])) {
            $mc_mm_site_id = $mc_mm_data["site_id"];
            $mm = new MailchimpMailmunchApi($mc_mm_user_email, $mc_mm_user_password, "http://" . MAILCHIMP_MAILMUNCH_URL);
            $result = $mm->widgets($mc_mm_site_id, "Sidebar");
            if (!is_wp_error($result)) {
                $widgets = json_decode($result['body']);
            }
        } else {
            ?>
            <p>No MailMunch account found. <a href="<?php 
            echo admin_url('admin.php?page=' . MAILCHIMP_MAILMUNCH_SLUG);
            ?>
">Go Here First</a></p>
        <?php 
            return;
        }
        ?>
        <script type="text/javascript">
        window.onmessage = function (e) {
          if (e.data === 'refresh') {
            top.location.reload();
          }
        };
        </script>
        <?php 
        if (sizeof($widgets) > 0) {
            ?>
        <p>
            <label for="<?php 
            echo $this->get_field_id('title');
            ?>
"><?php 
            _e('Title:');
            ?>
</label> 
            <input class="widefat" id="<?php 
            echo $this->get_field_id('title');
            ?>
" name="<?php 
            echo $this->get_field_name('title');
            ?>
" type="text" value="<?php 
            echo esc_attr($title);
            ?>
">
        </p>

        <p>
            <label for="<?php 
            echo $this->get_field_id('form_id');
            ?>
"><?php 
            _e('Optin Form:');
            ?>
</label>
            <select class="widefat" id="<?php 
            echo $this->get_field_id('form_id');
            ?>
" name="<?php 
            echo $this->get_field_name('form_id');
            ?>
">
                <option value="">None</option>
                <?php 
            foreach ($widgets as $widget) {
                echo "<option value='" . $widget->id . "'";
                if ($form_id == $widget->id) {
                    echo " selected";
                }
                echo ">" . $widget->name . "</option>";
            }
            ?>
            </select>
        </p>

        <p><a href="//<?php 
            echo MAILCHIMP_MAILMUNCH_URL;
            ?>
/sso?email=<?php 
            echo urlencode($mc_mm_user_email);
            ?>
&password=<?php 
            echo urlencode($mc_mm_user_password);
            ?>
&next_url=<?php 
            echo urlencode("/sites/" . $mc_mm_data["site_id"] . "/widgets/new?wp_layout=1&widget_type=Sidebar");
            ?>
" target="_blank">Create New Sidebar Form</a></p>
        <?php 
        } else {
            ?>
        <p>No sidebar forms found. <a href="//<?php 
            echo MAILCHIMP_MAILMUNCH_URL;
            ?>
/sso?email=<?php 
            echo urlencode($mc_mm_user_email);
            ?>
&password=<?php 
            echo urlencode($mc_mm_user_password);
            ?>
&next_url=<?php 
            echo urlencode("/sites/" . $mc_mm_data["site_id"] . "/widgets/new?wp_layout=1&widget_type=Sidebar");
            ?>
" target="_blank">Create Your First One</a></p>
        <?php 
        }
    }