<?php
/*
Plugin Name: Fomo for WooCommerce
Plugin URI: https://fomo.com
Description: Fomo displays recent orders on your WooCommerce storefront
Version: 2.0.12
Author: fomo
Author URI: https://fomo.com
*/

if (!defined('ABSPATH')) exit; // Exit if accessed directly

if (in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {

    $fomofwc_domain = 'https://fomo.com';

    global $fomofwc_version;
    $fomofwc_version = '2.0.12';

    function fomofwc_enqueue_script()
    {
      if(fomofwc_set_and_get_app_client_id()){
        global $fomofwc_domain;
        wp_enqueue_script('fomo', $fomofwc_domain . '/api/v1/' . fomofwc_set_and_get_app_client_id() . '/load.js', false);
      }
    }

    add_action('wp_enqueue_scripts', 'fomofwc_enqueue_script');

    function fomofwc_set_and_get_app_client_id()
    {
        $key = get_option('fomofwc_fomo_client_id');
        if ($key == null || $key === false || $key === "") {
          return false;
        }
        return $key;
    }

    function fomofwc_menu()
    {
        add_options_page('Fomo', 'Fomo', 'manage_options', 'fomo', 'fomofwc_plugin_options');
    }
    add_action('admin_menu', 'fomofwc_menu');

    function fomofwc_auth_params(){
      return '?client_id=' . get_option('fomofwc_fomo_client_id') . '&consumer_key=' . get_option('fomofwc_consumer_key') . '&consumer_secret=' . get_option('fomofwc_consumer_secret');
    }

    function fomofwc_uninstall()
    {
        global $fomofwc_domain;
        $args = array( 'headers' => array( 'Content-Type' => 'application/json' ), 'body' => fomofwc_params(), 'timeout' => 30 );
        $url = $fomofwc_domain . '/api/partners/woo_commerce/uninstall';
        fomofwc_remote_post($url, $args);

        delete_option( 'fomofwc_consumer_key' );
        delete_option( 'fomofwc_consumer_secret' );
        delete_option( 'fomofwc_fomo_client_id');
    }
    register_deactivation_hook(__FILE__, 'fomofwc_uninstall');

    function fomofwc_add_action_links($links)
    {
        $added_links = array(
            '<a href="' . admin_url('options-general.php?page=fomo') . '">' . __('Settings') . '</a>',
        );
        return array_merge($links, $added_links);
    }
    add_filter('plugin_action_links_' . plugin_basename(__FILE__), 'fomofwc_add_action_links');

    function fomofwc_params(){
      $payload = [
          'url' => home_url(),
          'email' => get_option('admin_email'),
          'store_name' => get_option('blogname'),
          'client_id' => get_option('fomofwc_fomo_client_id'),
          'consumer_key' => get_option('fomofwc_consumer_key'),
          'consumer_secret' => get_option('fomofwc_consumer_secret'),
          'fomo_installed' => get_option('fomofwc_fomo_installed')
      ];
      return json_encode($payload);
    }

    function fomofwc_build_auth_url()
    {
      global $fomofwc_domain;
      return $fomofwc_domain . '/api/partners/woo_commerce/connect' . fomofwc_auth_params();
    }

    function fomofwc_build(){
      global $fomofwc_domain;
      $args = array( 'headers' => array( 'Content-Type' => 'application/json' ), 'body' => fomofwc_params(), 'timeout' => 30 );
      $response = fomofwc_remote_post($fomofwc_domain .'/api/partners/woo_commerce/auth', $args);
      
      if ($response['errors']) {
          print_r($response); exit;
      }
      
      
      if ($response['client_id']){
        ?>
        <div class="updated"><p>Updated your settings with Fomo.</p></div>
        <?php
        update_option( 'fomofwc_fomo_client_id', $response['client_id'] );
        update_option( 'fomofwc_fomo_installed', true );
      } else {
        ?>
        <div class="error"><p>Something went wrong. Please try again, if the error continues email: hello@fomo.com for support.</p></div>
        <?php
      }
    }

    function fomofwc_check(){
      global $fomofwc_domain;
      $args = array( 'headers' => array( 'Content-Type' => 'application/json' ), 'body' => fomofwc_params(), 'timeout' => 30 );
      $response = fomofwc_remote_post($fomofwc_domain .'/api/partners/woo_commerce/check', $args);
      if ($response['message'] == 'error'){
        return true;
      } else {
        return false;
      }
    }

    function fomofwc_user_check(){
      global $fomofwc_domain;
      if (fomofwc_set_and_get_app_client_id()){
        return false; // don't check fomo's server - only check if fomo not installed
      }

      $args = array( 'headers' => array( 'Content-Type' => 'application/json' ), 'body' => fomofwc_params(), 'timeout' => 30 );
      $response = fomofwc_remote_post($fomofwc_domain .'/api/partners/woo_commerce/user_check', $args);
      
      if ($response['message'] == 'found'){
        return true;
      } else {
        return false;
      }
    }

    function fomofwc_remote_post($url, $args)
    {
        $response = wp_remote_post($url, $args);

        if (is_wp_error($response)) {
            if ($response->get_error_message() == 'cURL error 35: SSL connect error') {
                try {
                    return json_decode(file_get_contents($url), true);
                } catch (Exception $e) {
                    echo '<p class="warning">';
                    _e('Error accrued while contacting our server!');
                    echo '<br />';
                    _e('Error data: ');
                    echo $e->getMessage();
                    echo '</p>';
                }
            } else {
                echo '<p class="warning">';
                _e('Error accrued while contacting our server!');
                echo '<br />';
                _e('Error data: ');
                echo $response->get_error_data();
                echo '<br />';
                _e('Error message: ');
                echo $response->get_error_message();
                echo '<br />';
                _e('Error code: ');
                echo $response->get_error_code();
                echo "</p>";
            }
            // error, CURL not installed, firewall blocked or Fomo server down
        } else {
            if ($response != null && isset($response['body'])) {
                return json_decode($response['body'], true);
            }
        }
    }
    function fomofwc_plugin_options()
    {
        if (!current_user_can('manage_options')) {
            wp_die(__('You do not have sufficient permissions to access this page.'));
        }

        $fomofwc_user_check_found = fomofwc_user_check();

        if( $_POST['updated'] === 'true' ){ fomofwc_handle_form(); }
        ?>
        <h3 style='margin-bottom: 30px;'>
          <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 1000 268.2" height="40px" width="150px" enable-background="new 0 0 1000 268.2" xml:space="preserve">
              <g>
                <path fill="#EBA06D" d="M234.8,26.5L209.5,1.2c-1.6-1.6-4.2-1.6-5.8-0.1c-10.2,9.7-20.5,15.5-51,15.5v0H55.1
                  c-2.3,0-4.2,1.9-4.2,4.2V118c0,2.3-1.9,4.2-4.2,4.2H4.2c-2.3,0-4.2,1.9-4.2,4.2v38c0,2.3,1.9,4.2,4.2,4.2h42.6
                  c2.3,0,4.2,1.9,4.2,4.2v83.7c0,2.3,1.9,4.2,4.2,4.2h38c2.3,0,4.2-1.9,4.2-4.2v-83.7c0-2.3,1.9-4.2,4.2-4.2h71.2
                  c2.3,0,4.2-1.9,4.2-4.2v-38c0-2.3-1.9-4.2-4.2-4.2h-71.2c-2.3,0-4.2-1.9-4.2-4.2V67.1c0-2.3,1.9-4.2,4.2-4.2h61.7
                  c32.1,0,50.8-11.3,71.5-30.5C236.4,30.9,236.4,28.1,234.8,26.5z"></path>
                <path fill="#EBA06D" d="M888.5,8.3L888.5,8.3c0,0-0.1,0-0.1,0c0,0-0.1,0-0.1,0v0c-19.5,0-36.4,3.8-50.6,10.7
                  c-8.1-5.6-18.9-10.7-31.6-10.7c-32.5,0-63,15.4-81,53.9V16.9c0-4.8-3.9-8.7-8.7-8.7h-14.7c-32.5,0-60.9,18.5-74.9,54.2V11
                  c0-1.5-1.2-2.7-2.7-2.7h-20.6c-32.7,0-62.5,20.3-75.2,54.9V11.4c0-1.8-1.5-3.2-3.3-3.1h0.1l-20.9,0c-31.5,0-71.3,16.8-86.9,63.3
                  c-16.7-38-49.6-63.2-98.7-63.2v0c0,0-0.1,0-0.1,0c0,0-0.1,0-0.1,0v0c-76.2,0-111.5,57.8-111.5,129.9c0,83.5,35.8,129.9,111.5,129.9
                  v0c0,0,0.1,0,0.1,0c0,0,0.1,0,0.1,0v0c73.9,0,111.5-46.4,111.5-129.9c0-53.3,30.6-78.5,49.9-79.6c0.8,0,1.4,0.5,1.4,1.3v196.5
                  c0,2.3,1.9,4.2,4.2,4.2h38.3c2.3,0,4.2-1.9,4.2-4.2v-53.2C528.3,84.1,569.5,62,578.4,59c0.8-0.3,1.7,0.4,1.7,1.2l0,196.1
                  c0,2.3,1.9,4.2,4.2,4.2h38.3c2.3,0,4.2-1.9,4.2-4.2v-53.2c0-119.9,39.7-141.6,49.9-144.2c0.8-0.2,1.6,0.4,1.6,1.3v196.1
                  c0,2.3,1.9,4.2,4.2,4.2h38.3c2.3,0,4.2-1.9,4.2-4.2v-53.2c0-120.4,39.5-144.6,57.6-144.6c4.1,0,8,1.1,11.5,2.7
                  c-11.7,21.5-17.4,48.1-17.4,77c0,83.5,35.8,129.9,111.5,129.9v0c0,0,0.1,0,0.1,0c0,0,0.1,0,0.1,0v0c73.9,0,111.5-46.4,111.5-129.9
                  C1000,66.1,962.7,8.3,888.5,8.3z M318.6,221.5c-44.5-0.1-61.7-37.4-61.7-83.2S273.7,55,318.6,55c44.9,0.1,61.7,37.4,61.7,83.2
                  S363.2,221.4,318.6,221.5z M888.4,221.5c-44.5-0.1-61.7-37.4-61.7-83.2S843.5,55,888.4,55c44.9,0.1,61.7,37.4,61.7,83.2
                  S932.9,221.4,888.4,221.5z"></path>
              </g>
            </svg>
            <span style='margin-left:6px; display: block;'>For WooCommerce</span>
          </h3>

          <?php if(!get_option('fomofwc_fomo_client_id')): ?>
            <div class='fomo-warning'>If you already have a Fomo account, don't use this plugin. This plugin is only for new users to easily create a Fomo account.</div>
          <?php endif; ?>

          <p>After you connect to Fomo. You can select one of our <a href='https://fomo.com/pricing' target='_blank'>subscription plans</a>. Your subscription plan will be managed on fomo.com</p>

          <div class='fomo-col fomo-col-200'>

            <h3>Access Fomo admin<h3>

            <?php if (fomofwc_set_and_get_app_client_id()): ?>

                <a target="_blank" href="<?php echo fomofwc_build_auth_url(); ?>" class="fomo-btn">Go to Fomo</a>

                <?php if (fomofwc_check()) :?>
                  <p>There might be an error with your connection to Fomo. Please email hello@fomo.com for support.</p>
                <?php endif; ?>

            <?php else: ?>
                <p><em>Add Consumer Key and Secret then hit 'Connect to Fomo'</em></p>
            <?php endif; ?>

            <hr>

            <p><a href="https://help.fomo.com/integration-guides" target="_blank">Support Docs</a></p>
          </div>


          <div class='fomo-col'>
          <h3>Settings</h3>

          <?php if ($fomofwc_user_check_found){ echo '<b>Account found: We checked our database and your email or website is already connected, please log in at fomo.com and delete this plugin.</b>'; } ?>
          <form method="POST">
            <input type="hidden" name="updated" value="true" />
            <?php wp_nonce_field( 'fomofwc_update', 'fomofwc_form' ); ?>
            <table class="form-table <?php if ($fomofwc_user_check_found){ echo 'fomo-disabled'; } ?> ">
              <tbody>
                    <?php if(get_option('fomofwc_fomo_client_id')): ?>
                      <tr>
                      <th><label for="fomofwc_fomo_client_id">Fomo Client Id</label></th>
                      <td><input readonly name="fomofwc_fomo_client_id" id="fomofwc_fomo_client_id" type="text" value="<?php echo get_option('fomofwc_fomo_client_id'); ?>" class="regular-text" /></td>
                    <?php endif; ?>

                    <tr>
                    <th><label for="fomofwc_consumer_key">Consumer Key</label></th>
                    <td><input name="fomofwc_consumer_key" id="fomofwc_consumer_key" type="text" value="<?php echo get_option('fomofwc_consumer_key'); ?>" class="regular-text" <?php if(get_option('fomofwc_consumer_key')) { echo "readonly"; } ?> /></td>
                  </tr>
                    <tr>
                    <th><label for="fomofwc_consumer_secret">Consumer Secret</label></th>
                    <td><input name="fomofwc_consumer_secret" id="fomofwc_consumer_secret" type="text" value="<?php echo get_option('fomofwc_consumer_secret'); ?>" class="regular-text" <?php if(get_option('fomofwc_consumer_secret')) { echo "readonly"; } ?> /></td>
                  </tr>
              </tbody>
            </table>
            <?php if(!get_option('fomofwc_fomo_client_id')): ?>
            <a target='_blank' href="https://help.fomo.com/article/357-where-do-i-find-my-woocommerce-api-key">Where do I get this?</a>
            <p class="submit <?php if ($fomofwc_user_check_found){ echo 'fomo-hidden'; } ?>">
                <input type="submit" name="submit" id="submit" class="fomo-btn" value="Connect to Fomo">
            </p>
            <?php endif; ?>
        </form>
        </div>



        <?php
      }

        function fomofwc_handle_form() {
          $fomofwc_consumer_key = sanitize_text_field( $_POST['fomofwc_consumer_key'] );
          $fomofwc_consumer_secret = sanitize_text_field( $_POST['fomofwc_consumer_secret'] );

            if( ! isset( $_POST['fomofwc_form'] ) || ! wp_verify_nonce( $_POST['fomofwc_form'], 'fomofwc_update' ) ){ ?>
               <div class="error">
                   <p>Sorry, there was an error. Please try again.</p>
               </div> <?php
               exit;
            } else {

              update_option( 'fomofwc_consumer_key', $fomofwc_consumer_key );
              update_option( 'fomofwc_consumer_secret', $fomofwc_consumer_secret );

              if( !$fomofwc_consumer_key || !$fomofwc_consumer_secret ){ ?>
                <div class="error">
                    <p>Ensure customer key and consumer secret are set. Please try again.</p>
                </div> <?php
              } else {
                fomofwc_build();
              }
            }
        }

} else {
    function fomofwc_admin_notice_woocommerce_not_installed()
    {
        $class = 'notice notice-error';
        $message = __('<strong>Fomo for WooCommerce</strong> plugin requires to have <a href="https://wordpress.org/plugins/woocommerce/" target="_blank">WooCommerce</a> plugin installed.', 'woocommerce-plugin-fomo');

        printf('<div class="%1$s"><p>%2$s</p></div>', $class, $message);
    }

    add_action('admin_notices', 'fomofwc_admin_notice_woocommerce_not_installed');
}

function admin_enqueue_styles() {
  wp_enqueue_style( 'fomo-admin-style', plugin_dir_url( __FILE__ ) . 'css/plugin-fomo-admin.css' );
}
add_action( 'admin_init', 'admin_enqueue_styles' );
