<?php
if (!defined('ABSPATH')) exit;

/**
 * Assisted Doctor Support preference.
 *
 * Local Doctor diagnostics and manual JSON/HTML exports remain available
 * independently. This preference controls only the remote report handoff used
 * by the explicit “Open support request” administrator action.
 */
if (!function_exists('custausu_admin_doctor_assisted_support_preferences_option_name')) {
  function custausu_admin_doctor_assisted_support_preferences_option_name(): string {
    return 'custausu_doctor_assisted_support_preferences';
  }
}

if (!function_exists('custausu_admin_doctor_assisted_support_preferences')) {
  function custausu_admin_doctor_assisted_support_preferences(): array {
    $saved = get_option(
      custausu_admin_doctor_assisted_support_preferences_option_name(),
      []
    );

    $saved = is_array($saved) ? $saved : [];

    return [
      'enabled'       => !empty($saved['enabled']) ? 1 : 0,
      'consent_epoch' => max(1, absint($saved['consent_epoch'] ?? 1)),
    ];
  }
}

if (!function_exists('custausu_admin_doctor_assisted_support_enabled')) {
  function custausu_admin_doctor_assisted_support_enabled(): bool {
    $preferences = custausu_admin_doctor_assisted_support_preferences();

    return !empty($preferences['enabled']);
  }
}

if (!function_exists('custausu_admin_doctor_assisted_support_epoch')) {
  function custausu_admin_doctor_assisted_support_epoch(): int {
    $preferences = custausu_admin_doctor_assisted_support_preferences();

    return max(1, absint($preferences['consent_epoch'] ?? 1));
  }
}

if (!function_exists('custausu_admin_doctor_update_assisted_support_enabled')) {
  function custausu_admin_doctor_update_assisted_support_enabled(bool $enabled): bool {
    $preferences = custausu_admin_doctor_assisted_support_preferences();
    $was_enabled = !empty($preferences['enabled']);

    /*
     * Revoking consent increments the epoch. Existing handoffs therefore
     * remain invalid even if Assisted Doctor Support is enabled again later.
     */
    if ($was_enabled && !$enabled) {
      $preferences['consent_epoch'] = max(
        1,
        absint($preferences['consent_epoch'] ?? 1)
      ) + 1;
    }

    $preferences['enabled'] = $enabled ? 1 : 0;

    return (bool) update_option(
      custausu_admin_doctor_assisted_support_preferences_option_name(),
      $preferences,
      false
    );
  }
}

if (!function_exists('custausu_admin_doctor_handle_assisted_support_preference')) {
  /**
   * Persist the dedicated preference from the main CAS Settings form.
   */
  function custausu_admin_doctor_handle_assisted_support_preference(): void {
    if (!is_admin() || !current_user_can('manage_options')) {
      return;
    }

    global $pagenow;

    if ((string) $pagenow !== 'options.php') {
      return;
    }

    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce is sanitized and verified below.
    $option_page = isset($_POST['option_page'])
      ? sanitize_key((string) wp_unslash($_POST['option_page']))
      : '';

    if ($option_page !== 'custausu_settings_group') {
      return;
    }

    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Sanitized and verified immediately below.
    $nonce = isset($_POST['_wpnonce'])
      ? sanitize_text_field((string) wp_unslash($_POST['_wpnonce']))
      : '';

    if (!wp_verify_nonce($nonce, 'custausu_settings_group-options')) {
      return;
    }

    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified above; the nested scalar is unslashed and sanitized immediately.
    $raw_enabled = isset($_POST['custausu_global_settings']['custausu_doctor_assisted_support_enabled'])
      ? sanitize_text_field(
          wp_unslash(
            (string) $_POST['custausu_global_settings']['custausu_doctor_assisted_support_enabled']
          )
        )
      : '0';

    custausu_admin_doctor_update_assisted_support_enabled(
      $raw_enabled === '1'
    );
  }

  add_action(
    'admin_init',
    'custausu_admin_doctor_handle_assisted_support_preference',
    1
  );
}

if (!function_exists('custausu_admin_doctor_report_handoff_allowed_origins')) {
  function custausu_admin_doctor_report_handoff_allowed_origins(): array {
    return (array) apply_filters('custausu_doctor_report_handoff_allowed_origins', [
      'https://customauthsuite.com',
      'https://www.customauthsuite.com',
    ]);
  }
}

if (!function_exists('custausu_admin_doctor_report_handoff_key')) {
  function custausu_admin_doctor_report_handoff_key(string $token): string {
    return 'custausu_doctor_report_handoff_' . md5($token);
  }
}

if (!function_exists('custausu_admin_doctor_report_handoff_filename')) {
  function custausu_admin_doctor_report_handoff_filename(): string {
    return 'custom-auth-suite-doctor-report-' . gmdate('Ymd-His') . '.json';
  }
}

if (!function_exists('custausu_admin_doctor_create_report_handoff')) {
  function custausu_admin_doctor_create_report_handoff(): array {
    if (
      !custausu_admin_doctor_assisted_support_enabled()
      || !current_user_can('manage_options')
      || !function_exists('custausu_support_report_generate')
    ) {
      return [];
    }

    $report = custausu_support_report_generate();

    if (!is_array($report)) {
      return [];
    }

    $json = wp_json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

    if (!is_string($json) || $json === '') {
      return [];
    }

    $token = wp_generate_password(40, false, false);
    $ttl   = (int) apply_filters('custausu_doctor_report_handoff_ttl', 30 * MINUTE_IN_SECONDS);

    if ($ttl < 60) {
      $ttl = 60;
    }

    if ($ttl > HOUR_IN_SECONDS) {
      $ttl = HOUR_IN_SECONDS;
    }

    $payload = [
      'json'          => $json,
      'filename'      => custausu_admin_doctor_report_handoff_filename(),
      'created_at'    => time(),
      'expires_at'    => time() + $ttl,
      'consent_epoch' => custausu_admin_doctor_assisted_support_epoch(),
    ];

    set_transient(custausu_admin_doctor_report_handoff_key($token), $payload, $ttl);

    $url = add_query_arg([
      'token' => rawurlencode($token),
    ], rest_url('custom-auth-suite/v1/doctor-report-handoff'));

    return [
      'url'      => $url,
      'filename' => $payload['filename'],
      'ttl'      => $ttl,
    ];
  }
}

if (!function_exists('custausu_admin_doctor_report_handoff_send_cors')) {
  function custausu_admin_doctor_report_handoff_send_cors(): void {
    $origin = isset($_SERVER['HTTP_ORIGIN'])
      ? esc_url_raw((string) wp_unslash($_SERVER['HTTP_ORIGIN']))
      : '';

    if ($origin === '') {
      return;
    }

    $allowed = custausu_admin_doctor_report_handoff_allowed_origins();

    if (in_array($origin, $allowed, true)) {
      header('Access-Control-Allow-Origin: ' . $origin);
      header('Vary: Origin');
      header('Access-Control-Allow-Methods: GET, OPTIONS');
      header('Access-Control-Allow-Headers: Content-Type, X-Requested-With');

      if (!empty($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_PRIVATE_NETWORK'])) {
        header('Access-Control-Allow-Private-Network: true');
      }
    }
  }
}

if (!function_exists('custausu_admin_doctor_rest_report_handoff')) {
  function custausu_admin_doctor_rest_report_handoff(WP_REST_Request $request) {
    if (!custausu_admin_doctor_assisted_support_enabled()) {
      return new WP_Error(
        'cas_doctor_report_handoff_disabled',
        'Assisted Doctor Support is disabled.',
        ['status' => 403]
      );
    }

    custausu_admin_doctor_report_handoff_send_cors();

    $request_method = isset($_SERVER['REQUEST_METHOD'])
      ? strtoupper(sanitize_key((string) wp_unslash($_SERVER['REQUEST_METHOD'])))
      : '';

    if ($request_method === 'OPTIONS') {
      return new WP_REST_Response(null, 204);
    }

    $token = trim((string) $request->get_param('token'));

    if ($token === '' || strlen($token) < 20) {
      return new WP_Error('cas_doctor_report_handoff_invalid', 'Invalid report handoff token.', ['status' => 403]);
    }

    $payload = get_transient(custausu_admin_doctor_report_handoff_key($token));

    if (!is_array($payload) || empty($payload['json'])) {
      return new WP_Error('cas_doctor_report_handoff_expired', 'Report handoff token expired.', ['status' => 410]);
    }

    $payload_epoch = max(0, absint($payload['consent_epoch'] ?? 0));

    if (
      $payload_epoch < 1
      || $payload_epoch !== custausu_admin_doctor_assisted_support_epoch()
    ) {
      return new WP_Error(
        'cas_doctor_report_handoff_revoked',
        'Report handoff consent has been revoked.',
        ['status' => 403]
      );
    }

    if ((bool) apply_filters('custausu_doctor_report_handoff_single_use', false)) {
    }

    $filename = sanitize_file_name((string) ($payload['filename'] ?? custausu_admin_doctor_report_handoff_filename()));
    $data = json_decode((string) $payload['json'], true);

    if (!is_array($data)) {
      return new WP_Error('cas_doctor_report_handoff_invalid_json', 'Invalid report payload.', ['status' => 500]);
    }

    return new WP_REST_Response($data, 200, [
      'Content-Type'                => 'application/json; charset=UTF-8',
      'Content-Disposition'         => 'attachment; filename="' . $filename . '"',
      'X-CAS-Doctor-Report-Name'    => $filename,
      'X-CAS-Doctor-Report-Handoff' => '1',
      'Cache-Control'               => 'no-store, no-cache, must-revalidate, max-age=0',
    ]);
  }
}

if (!function_exists('custausu_admin_doctor_register_report_handoff_route')) {
  function custausu_admin_doctor_register_report_handoff_route(): void {
    register_rest_route('custom-auth-suite/v1', '/doctor-report-handoff', [
      'methods'             => ['GET', 'OPTIONS'],
      'permission_callback' => '__return_true',
      'callback'            => 'custausu_admin_doctor_rest_report_handoff',
    ]);
  }

  add_action('rest_api_init', 'custausu_admin_doctor_register_report_handoff_route');
}
