<?php

/**
 * WP Jira Connector Login Test
 *
 * @since      1.0.0
 * @package    Lewe Jira Connector
 * @subpackage Lewe Jira Connector/admin/partials
 * @author     George Lewe <george@lewe.com>
 */

/**
 * Load WordPress if not already loaded
 */
try {
  if (!function_exists('wp_verify_nonce')) {
    // Find WordPress root - try multiple approaches
    $possible_roots = array(
      dirname(dirname(dirname(dirname(dirname(__FILE__))))), // /wp-content/plugins/plugin/admin/partials
      dirname(dirname(dirname(dirname(dirname(dirname(__FILE__)))))), // if in subdirectory
      $_SERVER['DOCUMENT_ROOT'] // fallback to document root
    );
    
    $wp_loaded = false;
    foreach ($possible_roots as $wp_root) {
      if (file_exists($wp_root . '/wp-load.php')) {
        require_once($wp_root . '/wp-load.php');
        $wp_loaded = true;
        break;
      }
    }
    
    if (!$wp_loaded) {
      throw new Exception('WordPress could not be loaded from any of the attempted paths');
    }
  }
} catch (Exception $e) {
  // If WordPress loading fails, output a basic error
  echo '<div style="color: red; border: 1px solid red; padding: 10px; margin: 10px;">';
  echo '<strong>WordPress Loading Error:</strong> ' . htmlspecialchars($e->getMessage());
  echo '</div>';
  exit;
}

// Start output buffering to catch any PHP errors
ob_start();

header("Cache-Control: no-cache");
header("Pragma: no-cache");

// Verify nonce for security
if (!isset($_REQUEST['_wpnonce']) || !wp_verify_nonce($_REQUEST['_wpnonce'], 'jira_login_test')) {
  wp_die(__('Security check failed', 'lewe-jira-connector'));
}

$reqServer = trim(sanitize_text_field($_REQUEST['server']));
$reqUser = trim(sanitize_text_field($_REQUEST['user']));
$reqPass = isset($_REQUEST['pass']) ? trim(sanitize_text_field($_REQUEST['pass'])) : '';
$reqToken = isset($_REQUEST['token']) ? trim(sanitize_text_field($_REQUEST['token'])) : '';

if (strlen($reqServer) and strlen($reqUser) and (strlen($reqPass) or strlen($reqToken))) {
  try {
    // Use absolute paths for includes - only need the Jira class
    $plugin_dir = dirname(dirname(dirname(__FILE__))); // Go up from /admin/partials/ to plugin root
    $jira_file = $plugin_dir . '/includes/class-lewe-jira-connector-jira.php';
    
    if (!file_exists($jira_file)) {
      throw new Exception("Jira class file not found: " . $jira_file);
    }
    
    include_once $jira_file;

    $jArray = array(
      'host' => $reqServer,
      'username' => $reqUser,
      'password' => $reqPass,
      'token' => $reqToken
    );
    
    if (!class_exists('Lewe_Jira_Connector_Jira')) {
      throw new Exception("Lewe_Jira_Connector_Jira class not found after include");
    }
    
    $J = new Lewe_Jira_Connector_Jira($jArray);

  if ($J->testConnection()) {
    $jiraUser = $J->getUser($reqUser);
    $jiraServerInfo = $J->getServerInfo();
?>
    <div class="jco-alert jco-alert-success">
      <p style="font-size:120%;"><strong><?php echo esc_html(__('Jira Login Test', 'lewe-jira-connector')); ?></strong></p>
      <p><?php echo esc_html(__('Connection and login to the JIRA server successful.', 'lewe-jira-connector')); ?></p>
      
      <?php if ($jiraServerInfo && is_object($jiraServerInfo)) { ?>
      <p><strong><?php echo esc_html(__('Jira Server Title', 'lewe-jira-connector')); ?>:</strong> <?php echo esc_html($jiraServerInfo->serverTitle ?? 'N/A'); ?><br>
        <strong><?php echo esc_html(__('Jira BaseURL', 'lewe-jira-connector')); ?>:</strong> <?php echo esc_html($jiraServerInfo->baseUrl ?? 'N/A'); ?><br>
        <strong><?php echo esc_html(__('Jira Version', 'lewe-jira-connector')); ?>:</strong> <?php echo esc_html($jiraServerInfo->version ?? 'N/A'); ?><br>
        <strong><?php echo esc_html(__('Jira Build', 'lewe-jira-connector')); ?>:</strong> <?php echo esc_html($jiraServerInfo->buildNumber ?? 'N/A'); ?><br><br>
      </p>
      <?php } else { ?>
      <p><em><?php echo esc_html(__('Server information could not be retrieved.', 'lewe-jira-connector')); ?></em><br><br></p>
      <?php } ?>
      
      <?php if ($jiraUser && is_object($jiraUser)) { ?>
      <p><strong><?php echo esc_html(__('Username', 'lewe-jira-connector')); ?>:</strong> <?php echo esc_html($jiraUser->name ?? 'N/A'); ?><br>
        <strong><?php echo esc_html(__('Display Name', 'lewe-jira-connector')); ?>:</strong> <?php echo esc_html($jiraUser->displayName ?? 'N/A'); ?><br>
        <strong><?php echo esc_html(__('E-mail', 'lewe-jira-connector')); ?>:</strong> <?php echo esc_html($jiraUser->emailAddress ?? 'N/A'); ?><br>
      </p>
      <?php } else { ?>
      <p><em><?php echo esc_html(__('User information could not be retrieved, but connection was successful.', 'lewe-jira-connector')); ?></em></p>
      <?php } ?>
    </div>
  <?php
  } else {
  ?>
    <div class='jco-alert jco-alert-danger'>
      <p style="font-size:120%;"><strong><?php echo esc_html(__('Jira Login Test', 'lewe-jira-connector')); ?></strong></p>
      <p><?php echo esc_html(__('The connection or authentication for this host failed. Please check the parameters and also whether a login captcha is required for this account', 'lewe-jira-connector')); ?>.</p>
    </div>
  <?php
  }
  
  } catch (Exception $e) {
  ?>
    <div class='jco-alert jco-alert-danger'>
      <p style="font-size:120%;"><strong><?php echo esc_html(__('Jira Login Test Error', 'lewe-jira-connector')); ?></strong></p>
      <p><?php echo esc_html(__('An error occurred: ', 'lewe-jira-connector')) . esc_html($e->getMessage()); ?>.</p>
    </div>
  <?php
  }
  
} else {
  ?>
  <div class='jco-alert jco-alert-warning'>
    <p style="font-size:120%;"><strong><?php echo esc_html(__('Jira Login Test', 'lewe-jira-connector')); ?></strong></p>
    <p><?php echo esc_html(__('The server, username, and authentication (password or token) parameters are incomplete', 'lewe-jira-connector')); ?>.</p>
  </div>
<?php
}
?>