<?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>
<?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;
  }
}
add_action('admin_post_content_nexus_form_submit', 'content_nexus_form_submit');

// <?php
// /*
// Plugin Name:  Content Nexus
// Description:  Generates blog posts from GPT-3 queries for a list of keywords
// Version:      1.0
// Author:       Konstantin Koss
// License:      GPLv2 or later
// License URI:  https://www.gnu.org/licenses/gpl-2.0.html
// Text Domain:  content-nexus
// Domain Path:  /languages
// */

// // If this file is called directly, abort.
// if ( !defined( 'WPINC' ) ) {
// 	die;
// }

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

// // Include plugin files
// require_once plugin_dir_path( __FILE__ ) . 'includes/class-content-nexus.php';

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

// // Initialize plugin
// function run_content_nexus() {
// 	$content_nexus = new ContentNexus();
// 	$content_nexus->run();
// }
// run_content_nexus();

// // Include the GPT-3 API
// require_once('gpt3-api.php');

// // Add a menu item for the plugin
// add_action('admin_menu', 'gpt3_blog_generator_menu');

// function gpt3_blog_generator_menu()
// {
//   add_menu_page(
//     'GPT-3 Blog Post Generator',
//     'GPT-3 Blog Post Generator',
//     'administrator',
//     'gpt3-blog-generator',
//     'gpt3_blog_generator_page',
//     'dashicons-admin-generic',
//     110
//   );
// };

// // Create the form for the plugin page
// function gpt3_blog_generator_page()
// {
//   echo '<h1>GPT-3 Blog Post Generator</h1>';
//   echo '<p>Upload a list of keywords to generate blog posts from GPT-3.</p>';
//   echo '<form method="post" enctype="multipart/form-data">';
//   echo '<input type="file" name="keywords" />';
//   echo '<input type="submit" value="Generate Blog Posts" />';
//   echo '</form>';

//   // Check if the file has been uploaded 
//   if (isset($_FILES['keywords'])) {
//     // Read the file 
//     $keywords = file($_FILES['keywords']['tmp_name']);
//     // Generate the posts 
//     foreach ($keywords as $keyword) {
//       // Query GPT-3 API 
//       $query = gpt3_query($keyword);

//       // Generate a random post date between now and one year from now 
//       $post_date = date('Y-m-d H:i:s', rand(time(), strtotime('+1 year')));

//       // Insert post into the WordPress database 
//       wp_insert_post(
//         array('post_title' => $keyword, 'post_content' => $query['data']['text'], 'post_date' => $post_date, 'post_status' => 'future')
//       );
//     }
//   }
// }
