<?php

/*
 * Plugin Name: Content Nexus
 * Description: A plugin to transform a list of keywords into an array and sends it to an endpoint.
 * Version: 1.0
 * Author: Konstantin K
 * License: GPL2
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: content-nexus
 */

// If this file is called directly, abort.
if (!defined('WPINC')) {
  echo 'Hi there!  I\'m just a plugin, not much I can do when called directly.';
  die;
}

// Define plugin constants
define('CONTENT_NEXUS_VERSION', '1.0');

// Make sure we have the necessary functions
if (!function_exists('register_activation_hook')) {
  require_once(ABSPATH . 'wp-admin/includes/plugin.php');
}

// // Register hooks
// register_activation_hook( __FILE__, array( 'ContentNexus', 'activate' ) );
// register_deactivation_hook( __FILE__, array( 'ContentNexus', 'deactivate' ) );

class ContentNexus
{

  public function __construct()
  {
    add_action('admin_menu', array($this, 'add_admin_menu'));
  }

  public function add_admin_menu()
  {
    add_menu_page(
      'Content Nexus',
      'Content Nexus',
      'manage_options',
      'content-nexus',
      array($this, 'admin_menu_page_callback'),
      'dashicons-admin-generic',
      81
    );
  }

  public function admin_menu_page_callback()
  {
?>
    <h1>Content Nexus</h1>
    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
      <input type="hidden" name="action" value="content_nexus_form_submit">
      <textarea name="keywords" placeholder="Enter keywords, one per line" rows="10" cols="50"></textarea><br>
      <input type="text" name="target" placeholder="Target audience description"><br>
      <input type="number" name="category" placeholder="Category Number" value="1"><br>
      <?php if ($_SERVER['HTTP_HOST'] == 'localhost:8888') {
      ?>
        <input type="text" name="host" placeholder="Host">
      <?php
      } else {
      ?>
        <input type="hidden" name="host" placeholder="Host" value="<?php echo $_SERVER['HTTP_HOST'] ?>">
      <?php
      } ?><br>
      <input type="text" name="secret" placeholder="Secret"><br>
      <input type="submit" value="Submit">
    </form>
    <h2>Other Actions</h2>
    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
      <input type="hidden" name="action" value="content_nexus_get_post">
      <?php if ($_SERVER['HTTP_HOST'] == 'localhost:8888') {
      ?>
        <input type="text" name="host" placeholder="Host">
      <?php
      } else {
      ?>
        <input type="hidden" name="host" placeholder="Host" value="<?php echo $_SERVER['HTTP_HOST'] ?>">
      <?php
      } ?>
      <input type="submit" value="Get Instant Content!">
    </form>
<?php
  }
}

new ContentNexus();

function content_nexus_form_submit()
{
  if (isset($_POST['keywords'])) {
    $keywords = explode("\n", $_POST['keywords']);
    $keywords = array_map('trim', $keywords);
    $keywords = array_filter($keywords);
    $keyword_chunks = array_chunk($keywords, 5000);
    $chunks_number = count($keyword_chunks);
    foreach ($keyword_chunks as $index => $keyword_chunk) {
      echo "<p>Submitting… " . ($index + 1) . "/$chunks_number</p>";
      $data = array(
        'keywords' => $keyword_chunk,
        'target' => $_POST['target'],
        'baseUrl' => $_POST['host'],
        'category' => $_POST['category'],
        'secret' => $_POST['secret'],
      );
      $response = wp_remote_post('https://d5ouaqolbrs4r4nttcibwzzt4m0zgpbu.lambda-url.us-east-1.on.aws/', array(
        'method' => 'POST',
        'timeout' => 9999,
        'redirection' => 5,
        'httpversion' => '1.0',
        'blocking' => true,
        'headers' => array(
          'Content-Type' => 'application/json; charset=utf-8'
        ),
        'body' => json_encode($data),
        'data_format' => 'body',
        'cookies' => array()
      ));

      $formatted = print_r($response["body"]);
      echo "<pre>$formatted</pre>";
    }

    // // add the admin notice
    // $admin_notice = $response;

    // // redirect the user to the appropriate page
    // wp_safe_redirect("/wp-admin/admin.php?page=content-nexus&msg=$admin_notice");
    exit;
  }
}

function content_nexus_get_post()
{
  if (isset($_POST['host'])) {
    $host = $_POST['host'];
    $response = wp_remote_get("https://sowao5jsbaqyqd4kl6kcpuuk5i0rlyub.lambda-url.us-east-1.on.aws/?baseUrl=$host", array(
      'method' => 'GET',
      'timeout' => 9999,
      'redirection' => 5,
      'httpversion' => '1.0',
      'blocking' => true,
      'cookies' => array()
    ));

    $formatted = print_r($response["body"]);
    echo "<pre>$formatted</pre>";
  }
  exit;
};

add_action('admin_post_content_nexus_form_submit', 'content_nexus_form_submit');
add_action('admin_post_content_nexus_get_post', 'content_nexus_get_post');
