<?php

use _121Digital\Connect\Admin\Services\NoticeService;

add_action('admin_menu', function () {
    add_submenu_page(
        'options-general.php',
        '121 Site Connector',
        '121 Site Connector',
        'manage_options',
        'site-connector',
        'sc_site_connector_page'
    );
});

function sc_check_for_updates()
{
    if (!current_user_can('update_plugins')) {
        return ['success' => false, 'message' => 'You do not have permission to update plugins.'];
    }

    // Force update check
    delete_site_transient('update_plugins');
    wp_update_plugins();

    $plugin_file = '121-site-connector/121-site-connector.php'; // adjust this to your actual plugin path
    $update_plugins = get_site_transient('update_plugins');

    if (isset($update_plugins->response[$plugin_file])) {
        $new_version = $update_plugins->response[$plugin_file]->new_version;
        $details_url = self_admin_url('update.php?action=upgrade-plugin&plugin=' . urlencode($plugin_file) . '&_wpnonce=' . wp_create_nonce('upgrade-plugin_' . $plugin_file));

        return [
          'success' => false,
          'message' => "A new version ($new_version) of Site Connector is available.",
          'update_url' => $details_url
        ];
    }

    return ['success' => true, 'message' => 'You are using the latest version of the Site Connector plugin.'];
}

function sc_site_connector_page()
{
    if (!current_user_can('manage_options')) {
        return;
    }

    $is_registered = get_option('sc_site_registered');
    $has_registration_data = sc_has_registration_data();

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (isset($_POST['sc_connect_confirm']) && !$is_registered) {
            $result = sc_handle_registration();
        } elseif (isset($_POST['sc_disconnect_confirm'])) {
            $result = sc_handle_disconnect();
        } elseif (isset($_POST['sc_verify_confirm'])) {
            $result = sc_verify_registration();
        } elseif (isset($_POST['sc_check_updates_confirm']) && check_admin_referer('sc_check_updates_action', 'sc_check_updates_nonce')) {
            $result = sc_check_for_updates();
        } elseif (isset($_POST['sc_update_matomo_tracking_code'])) {
            $tracking_code = sanitize_textarea_field($_POST['sc_matomo_tracking_code']);
            sc_matomo_set_tracking_code($tracking_code);
            $result = [
              'success' => true,
              'message' => 'Matomo tracking code updated successfully.',
            ];
        }

        if (isset($result)) {
            if ($result['success']) {
                NoticeService::addSuccess($result['message'], true, 'sc-action-result');
            } else {
                NoticeService::addError($result['message'], true, 'sc-action-result');
            }
        }
    }

    ?>
  <div class="wrap">
    <?php require_once SC_PLUGIN_PATH . 'partials/StatusToolbar.php'; ?>
    <br>
    <h1><b>Site Connector</b></h1>

    <?php if (!$is_registered): ?>
      <?php if (!$has_registration_data): ?>
        <form method="post">
          <input type="hidden" name="sc_connect_confirm" value="1">
          <p>This will register your site with the backend. This can only be done once.</p>
          <?php submit_button('Register Site'); ?>
        </form>
      <?php else: ?>
        <h2>Site Registration Error</h2>
        <p>This site's connection to 121 Digital needs to be re-verified. Use the tool below to do this manually.</p>
        <div class="notice notice-error connect-121-notice">
          <br>
          <b>Last reported error:</b><br>
          <?php echo esc_html(get_option('sc_last_backend_error')); ?>
          <br><hr>
          <b>Suggested fix:</b><br>
          Await the WordPress CRON job to run again, or invoke validation manually using the 'Verify Connection &amp; Keys' tool.
          <br><br>
          <form method="POST">
            <input type="hidden" name="sc_verify_confirm" value="1">
            <?php wp_nonce_field('sc_disconnect_site_action', 'sc_disconnect_nonce'); ?>
            <input type="submit" class="button button-danger" value="Verify Connection">
          </form>
          <br>
        </div>
        <hr>
        <?php
            $last_run = get_option('sc_last_cron_execution');
          if ($last_run) {
              $last_run_timestamp = strtotime($last_run);
              $time_diff = time() - $last_run_timestamp;

              if ($time_diff < 600) {
                  echo '<p><strong><span class="dashicons dashicons-yes" style="color:green;"></span> The cron was last run ' . esc_html($last_run) . '</strong></p>';
              } else {
                  echo '<p><strong><span style="color:orange;">⚠️</span> Warning: Cron has not run recently. Last run: ' . esc_html($last_run) . '</strong></p>';
              }
          } else {
              echo '<p><strong><span style="color:red;">❌</span> The cron has not run yet. <i>It might be a good idea to check the cron config.</i></strong></p>';
          }
          ?>
        <hr>
        <h2>Verify Connection &amp; Keys</h2>
        <form method="POST">
          <input type="hidden" name="sc_verify_confirm" value="1">
          <?php wp_nonce_field('sc_disconnect_site_action', 'sc_disconnect_nonce'); ?>
          <input type="submit" class="button button-danger" value="Verify Connection">
        </form>
        <form method="POST">
          <?php wp_nonce_field('sc_disconnect_site_action', 'sc_disconnect_nonce'); ?>
          <input type="submit" name="sc_disconnect_confirm" class="button button-danger" 
                value="Disconnect Site" onclick="return confirm('Are you sure you want to disconnect this site?');">
        </form>
      <?php endif; ?>
    <?php else: ?>
      <p><strong>✅ This site is registered as site ID <?php echo esc_html(get_option('sc_site_id')); ?>.</strong></p>
      <small>Last backend request: <?php echo esc_html(get_option('sc_last_communication')); ?></small>

      <hr>
      <?php
          $last_run = get_option('sc_last_cron_execution');
        if ($last_run) {
            $last_run_timestamp = strtotime($last_run);
            $time_diff = time() - $last_run_timestamp;

            if ($time_diff < 600) {
                echo '<p><strong><span class="dashicons dashicons-yes" style="color:green;"></span> The cron was last run ' . esc_html($last_run) . '</strong></p>';
            } else {
                echo '<p><strong><span style="color:orange;">⚠️</span> Warning: Cron has not run recently. Last run: ' . esc_html($last_run) . '</strong></p>';
            }
        } else {
            echo '<p><strong><span style="color:red;">❌</span> The cron has not run yet. <i>It might be a good idea to check the cron config.</i></strong></p>';
        }
        ?>

      <hr>
      <h2>Check for Updates</h2>
      <p>Use this tool to manually check with the backend for any available plugin updates or configuration changes.</p>
      <form method="POST">
        <?php wp_nonce_field('sc_check_updates_action', 'sc_check_updates_nonce'); ?>
        <input type="submit" name="sc_check_updates_confirm" class="button button-secondary" value="Check for Updates">
      </form>

      <hr>
      <h2>Verify Connection &amp; Keys</h2>
      <form method="POST">
        <input type="hidden" name="sc_verify_confirm" value="1">
        <?php wp_nonce_field('sc_disconnect_site_action', 'sc_disconnect_nonce'); ?>
        <input type="submit" class="button button-danger" value="Verify Connection">
      </form>

      <hr>
      <h2>Disconnect Site</h2>
      <form method="POST">
        <?php wp_nonce_field('sc_disconnect_site_action', 'sc_disconnect_nonce'); ?>
        <input type="submit" name="sc_disconnect_confirm" class="button button-danger" 
              value="Disconnect Site" onclick="return confirm('Are you sure you want to disconnect this site?');">
      </form>

      <hr>
      <h2>Matomo Tracking Code</h2>
      <?php if (sc_matomo_has_tracking_code()): ?>
        <?php if (sc_matomo_can_render_tracking_code()): ?>
          <p><strong>Matomo tracking code is set and valid.</strong></p>
        <?php else: ?>
            <?php if (!sc_matomo_tracking_code_empty()): ?>
            <div class="notice notice-error connect-121-notice">
              <p><b>Security Notice:</b> The defined matomo tracking code is potentially unsafe and has been disabled.</p>
            </div>
          <?php endif; ?>
        <?php endif; ?>
      <?php endif; ?>

      <form method="POST">
        <textarea disabled name="sc_matomo_tracking_code" rows="15" cols="100"><?php echo esc_html(sc_matomo_get_tracking_code()); ?></textarea>
        <br>
        <!-- <input type="submit" name="sc_update_matomo_tracking_code" class="button" 
              value="Update Tracking Code"> -->
      </form>
    <?php endif; ?>
  </div>
  <?php
}
