<?php

/**
 * Jira Host meta box
 *
 * @link       https://www.lewe.com
 * @since      1.0.0
 *
 * @package    Lewe Jira Connector
 * @subpackage Lewe Jira Connector/admin/partials
 */

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

if (!function_exists('display_jira_host_meta_box')) {
  function display_jira_host_meta_box($jira_host) {
    /**
     * Load classes and initialize variables.
     */
    $P = new Lewe_Jira_Connector_Plugin();

    /**
     * Retrieve current values
     */
    $jira_host_description = sanitize_text_field(get_post_meta($jira_host->ID, 'jira_host_description', true));
    $jira_host_url = sanitize_text_field(get_post_meta($jira_host->ID, 'jira_host_url', true));
    $jira_host_username = sanitize_text_field(get_post_meta($jira_host->ID, 'jira_host_username', true));
    $jira_host_password = sanitize_text_field(get_post_meta($jira_host->ID, 'jira_host_password', true));
    $jira_host_token = sanitize_text_field(get_post_meta($jira_host->ID, 'jira_host_token', true));

?>

    <table class="form-table" style="margin-left:16px;">
      <tbody>
        <tr>
          <th scope="row"><label for="jira_host_description"><?php echo esc_html(__('Description', 'lewe-jira-connector')); ?></label></th>
          <td>
            <input type="text" id="jira_host_description" name="jira_host_description" value="<?php echo esc_html($jira_host_description); ?>" />
            <p class="description"><?php echo esc_html(__('Enter a description for this Jira host.', 'lewe-jira-connector')); ?></p>
          </td>
        </tr>

        <tr>
          <th scope="row"><label for="jira_host_url"><?php echo esc_html(__('URL', 'lewe-jira-connector')); ?></label></th>
          <td>
            <input type="text" id="jira_host_url" name="jira_host_url" value="<?php echo esc_html($jira_host_url); ?>" />
            <p class="description"><?php echo esc_html(__('Enter the base URL for this Jira host (do not add a trailing slash).', 'lewe-jira-connector')); ?></p>
          </td>
        </tr>

        <tr>
          <th scope="row"><label for="jira_host_username"><?php echo esc_html(__('Username', 'lewe-jira-connector')); ?></label></th>
          <td>
            <input type="text" id="jira_host_username" name="jira_host_username" value="<?php echo esc_html($jira_host_username); ?>" />
            <p class="description"><?php echo esc_html(__('Enter the username for this Jira host.', 'lewe-jira-connector')); ?></p>
          </td>
        </tr>

        <tr>
          <th scope="row"><label for="jira_host_password"><?php echo esc_html(__('Password', 'lewe-jira-connector')); ?></label></th>
          <td>
            <input type="password" id="jira_host_password" name="jira_host_password" value="<?php echo esc_html($jira_host_password); ?>" />
            <p class="description"><?php echo esc_html(__('Enter the password (Jira Server, Jira Data Center) or the', 'lewe-jira-connector')); ?>
              <a href="https://support.atlassian.com/atlassian-account/docs/manage-api-tokens-for-your-atlassian-account/" target="_blank"><?php echo esc_html(__('API token', 'lewe-jira-connector')); ?></a>
              <?php echo esc_html(__('(Jira Cloud) for the username you specified.', 'lewe-jira-connector')); ?>
            </p>
          </td>
        </tr>

        <tr>
          <th scope="row"><label for="jira_host_token"><?php echo esc_html(__('Personal Access Token (PAT)', 'lewe-jira-connector')); ?></label></th>
          <td>
            <input type="password" id="jira_host_token" name="jira_host_token" value="<?php echo esc_html($jira_host_token); ?>" />
            <p class="description"><?php echo esc_html(__('If this host requires a personal access token (PAT) instead of basic authentication for API calls, enter yours here. Leave this field empty for basic authentication with your username and password. Read more about ', 'lewe-jira-connector')); ?>
              <a href="https://confluence.atlassian.com/enterprise/using-personal-access-tokens-1026032365.html" target="_blank"><?php echo esc_html(__('Personal Access Tokens', 'lewe-jira-connector')); ?></a>.
            </p>
          </td>
        </tr>

        <tr>
          <th scope="row"><?php echo esc_html(__('Test Connection', 'lewe-jira-connector')); ?></th>
          <td>
            <button type="button" id="test-jira-connection" class="button button-secondary">
              <?php echo esc_html(__('Test Jira Connection', 'lewe-jira-connector')); ?>
            </button>
            <p class="description"><?php echo esc_html(__('Click to test the connection to your Jira host using the URL, username, and password/token entered above.', 'lewe-jira-connector')); ?></p>
            <div id="jira-test-result" style="margin-top: 10px;"></div>
          </td>
        </tr>

      </tbody>
    </table>

    <script type="text/javascript">
    jQuery(document).ready(function($) {
      // Add some basic styling
      $('#jira-test-result').css({
        'max-width': '600px',
        'font-family': 'inherit'
      });
      
      $('#test-jira-connection').on('click', function() {
        var button = $(this);
        var resultDiv = $('#jira-test-result');
        
        // Get field values
        var server = $('#jira_host_url').val().trim();
        var username = $('#jira_host_username').val().trim();
        var password = $('#jira_host_password').val().trim();
        var token = $('#jira_host_token').val().trim();
        
        // Validate required fields (need server, username, and either password or token)
        if (!server || !username || (!password && !token)) {
          resultDiv.html('<div class="notice notice-error"><p><?php echo esc_js(__('Please fill in URL, Username, and either Password or Personal Access Token before testing.', 'lewe-jira-connector')); ?></p></div>');
          return;
        }
        
        // Update button state
        button.prop('disabled', true).text('<?php echo esc_js(__('Testing...', 'lewe-jira-connector')); ?>');
        resultDiv.html('<div class="notice notice-info"><p><?php echo esc_js(__('Testing connection...', 'lewe-jira-connector')); ?></p></div>');
        
        // Prepare data for AJAX request
        var testData = {
          server: server,
          user: username,
          pass: password,
          token: token,
          _wpnonce: '<?php echo wp_create_nonce('jira_login_test'); ?>'
        };
        
        // Make AJAX request to test login file
        $.ajax({
          url: '<?php echo esc_js(plugin_dir_url(__FILE__) . 'lewe-jira-connector-admin-test-jira-login.php'); ?>',
          type: 'POST',
          data: testData,
          timeout: 30000, // 30 second timeout
          success: function(response) {
            resultDiv.html(response);
          },
          error: function(xhr, status, error) {
            var errorMsg = '<?php echo esc_js(__('Connection test failed. Error: ', 'lewe-jira-connector')); ?>';
            if (status === 'timeout') {
              errorMsg += '<?php echo esc_js(__('Request timeout. Please check your Jira server URL.', 'lewe-jira-connector')); ?>';
            } else {
              errorMsg += error;
            }
            resultDiv.html('<div class="notice notice-error"><p>' + errorMsg + '</p></div>');
          },
          complete: function() {
            // Reset button state
            button.prop('disabled', false).text('<?php echo esc_js(__('Test Jira Connection', 'lewe-jira-connector')); ?>');
          }
        });
      });
    });
    </script>

<?php
  }
}
