<?php
/**
 * MindWebConcierge Subscription & Trial Handlers
 *
 * @package MindWebConcierge
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

require_once __DIR__ . '/mindweco_config.php';

/**
 * Returns the plugin configuration array from constants defined in config.php.
 *
 * @return array
 */
function mindweco_stripe_load_config() {
  return array(
    'rag_url'      => defined( 'MINDWECO_RAG_URL' ) ? MINDWECO_RAG_URL : '',
    'notebooks_url' => defined( 'MINDWECO_NOTEBOOKS_URL' ) ? MINDWECO_NOTEBOOKS_URL : '',
    'stripe_url'   => defined( 'MINDWECO_STRIPE_URL' ) ? MINDWECO_STRIPE_URL : '',
    'prod_id'      => defined( 'MINDWECO_PROD_ID' ) ? MINDWECO_PROD_ID : '',
  );
}

/**
 * Returns the Stripe base URL from options, falling back to the config constant.
 *
 * @return string
 */
function mindweco_get_stripe_base_url() {
  $option_value = get_option('mindweco_stripe_base_url');
  if ( ! empty( $option_value )) {
    return sanitize_text_field($option_value);
  }
  $config = mindweco_stripe_load_config();
  return isset($config['stripe_url']) ? $config['stripe_url'] : "";
}

/**
 * Returns the Stripe product ID from options, falling back to the config constant.
 *
 * @return string
 */
function mindweco_get_product_id() {
  $option_value = get_option('mindweco_stripe_product_id');
  if ( ! empty( $option_value )) {
    return sanitize_text_field($option_value);
  }
  $config = mindweco_stripe_load_config();
  return isset($config['prod_id']) ? $config['prod_id'] : "";
}

/**
 * Validates and returns subscription data unchanged.
 *
 * @param mixed $subscription_data Raw subscription data from API.
 * @return mixed
 */
function mindweco_check_subscription_status($subscription_data) {
  if ( ! is_array( $subscription_data ) || empty( $subscription_data )) {
    return $subscription_data;
  }
  return $subscription_data;
}

add_action('wp_ajax_mindweco_add_trial', 'mindweco_add_trial_ajax');

function mindweco_add_trial_ajax() {
  check_ajax_referer('mindweco_add_trial_nonce', 'nonce');

  if ( ! current_user_can( 'manage_options' ) ) {
    wp_send_json_error( array(  'message' => esc_html__('Access denied.', 'mind-web-concierge') ) );
    return;
  }

  $app_guid = get_option('mindweco_plugin_guid', '');
  $stripe_base_url = mindweco_get_stripe_base_url();
  $product_id = get_option('mindweco_stripe_product_id', '');

  if ( empty( $app_guid ) || empty( $stripe_base_url )) {
    wp_send_json_error( array( 'message' => esc_html__('Missing parameters.', 'mind-web-concierge') ) );
    return;
  }

  $user = wp_get_current_user();
  $user_email = $user->exists() ? $user->user_email : '';
  $title = get_option('siteurl');
  $site_base_url = get_option('siteurl');

  $add_trial_response = mindweco_stripe_add_trial(
    $stripe_base_url,
    $app_guid,
    $product_id,
    $user_email,
    $title,
    $site_base_url,
  );

  update_option( 'mindweco_trial_response', isset($add_trial_response['subscription'])? $add_trial_response['subscription'] : array() );

  if (isset($add_trial_response['error'])) {
    wp_send_json_error( array( 'message' => esc_html($add_trial_response['error']) ) );
    return;
  }

  wp_send_json_success($add_trial_response);
}

// This endpoint is intentionally accessible to unauthenticated users.
// It only reads subscription status from an external API and does not modify any data.
add_action('wp_ajax_mindweco_get_trial_status', 'mindweco_get_trial_status_ajax');
add_action('wp_ajax_nopriv_mindweco_get_trial_status', 'mindweco_get_trial_status_ajax',);

function mindweco_get_trial_status_ajax() {
  $nonce = "";
  if (isset($_GET['nonce'])) {
    $nonce = sanitize_text_field(wp_unslash($_GET['nonce']));
  } elseif (isset($_REQUEST['nonce'])) {
    $nonce = sanitize_text_field(wp_unslash($_REQUEST['nonce']));
  }

  if ( ! wp_verify_nonce($nonce, 'mindweco_trial_nonce')) {
    wp_send_json_error( array( 'message' => esc_html__('Invalid nonce.', 'mind-web-concierge' ) ) );
    return;
  }

  $app_guid = get_option('mindweco_plugin_guid', '');
  if (isset($_GET['app_guid'])) {
    $app_guid = sanitize_text_field(wp_unslash($_GET['app_guid']));
  } elseif (isset($_REQUEST['app_guid'])) {
    $app_guid = sanitize_text_field(wp_unslash($_REQUEST['app_guid']));
  }

  $stripe_base_url = mindweco_get_stripe_base_url();
  $api_response = mindweco_stripe_active_subscription(
    $stripe_base_url,
    $app_guid
  );

  $trial_option = get_option('mindweco_trial_response', array());

  if (empty($api_response) || isset($api_response['error'])) {
    $all_subscriptions = mindweco_get_all_subscriptions($stripe_base_url, $app_guid);

    if (is_array($all_subscriptions) && ! isset($all_subscriptions['error']) && ! empty($all_subscriptions)) {
      usort(
        $all_subscriptions,
        function($a, $b) {
          $a_end = isset($a['currentPeriodEnd']) ? strtotime($a['currentPeriodEnd']) : 0;
          $b_end = isset($b['currentPeriodEnd']) ? strtotime($b['currentPeriodEnd']) : 0;
          return $b_end <=> $a_end;
        }
      );

      $api_response = $all_subscriptions[0];
    } elseif (! empty($trial_option) && is_array($trial_option)) {
      $api_response = $trial_option;
    }
  }

  if (
    is_array($api_response) &&
    isset($api_response['currentPeriodEnd']) &&
    strtotime($api_response['currentPeriodEnd']) &&
    time() > strtotime($api_response['currentPeriodEnd'])
  ) {
    $api_response['status'] = 2;
  }

  if (isset($api_response['error'])) {
    wp_send_json_error( array( 'message' => esc_html($api_response['error'] ) ) );
    return;
  }

  $api_response = mindweco_check_subscription_status($api_response);
  $old_end_date = isset($trial_option['currentPeriodEnd']) ? $trial_option['currentPeriodEnd'] : null;
  $new_end_date = isset($api_response['currentPeriodEnd']) ? $api_response['currentPeriodEnd'] : null;
  $status = isset($api_response['status']) ? $api_response['status'] : null;
  $type = isset($api_response['type']) ? $api_response['type'] : null;
  $should_update = false;

  if ($new_end_date && $new_end_date !== $old_end_date) {
    $should_update = true;
  }

  if (isset($trial_option['status']) && $status != $trial_option['status']) {
    // phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison
    $should_update = true;
  }

  if ($should_update) {
    update_option('mindweco_trial_response', $api_response);
  }

  if (null === $api_response) {
    update_option('mindweco_trial_response', '');
  }
  
  wp_send_json_success( array(
    'oldEndDate' => $old_end_date,
    'newEndDate' => $new_end_date,
    'status' => $status,
    'type' => $type,
    'data' => $api_response, 
  ) );

}

// This endpoint is intentionally accessible to unauthenticated users.
// It only reads all subscriptions from an external API and does not modify any data.
add_action( 'wp_ajax_mindweco_get_all_subscriptions', 'mindweco_get_all_subscription_ajax', );
add_action( 'wp_ajax_nopriv_mindweco_get_all_subscriptions', 'mindweco_get_all_subscription_ajax', );

function mindweco_get_all_subscription_ajax() {
  $nonce = '';
  if (isset($_GET['nonce'])) {
    $nonce = sanitize_text_field(wp_unslash($_GET['nonce']));
  } elseif (isset($_REQUEST['nonce'])) {
    $nonce = sanitize_text_field(wp_unslash($_REQUEST['nonce']));
  }

  if ( ! wp_verify_nonce($nonce, 'mindweco_trial_nonce')) {
    wp_send_json_error( array( 'message' =>  esc_html__('Invalid nonce.', 'mind-web-concierge') ) );
    return;
  }

  $app_guid = get_option('mindweco_plugin_guid', '');
  $stripe_base_url = mindweco_get_stripe_base_url();
  $api_response = mindweco_get_all_subscriptions($stripe_base_url, $app_guid);

  if ( isset($api_response['error'])) {
    wp_send_json_error( array( 'message' => esc_html($api_response['error'] ) ) );
    return;
  }

  if ( is_array($api_response)) {
    foreach ($api_response as $key => $subscription) {
      $api_response[$key] = mindweco_check_subscription_status($subscription);
    }

    if ( ! empty( $api_response[0] )) {
      $current_trial = get_option('mindweco_trial_response', array());
      if (
        isset($current_trial['id']) &&
        isset($api_response[0]['id']) &&
        $current_trial['id'] == $api_response[0]['id'] // phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison
      ) {
        update_option('mindweco_trial_response', $api_response[0]);
      }
    }
  }

  wp_send_json_success($api_response);
}

// This endpoint is intentionally accessible to unauthenticated users.
// It only reads subscription history from an external API and does not modify any data.
add_action( 'wp_ajax_mindweco_get_history_subscriptions', 'mindweco_get_history_subscription_ajax', );
add_action( 'wp_ajax_nopriv_mindweco_get_history_subscriptions', 'mindweco_get_history_subscription_ajax',);

function mindweco_get_history_subscription_ajax() {
  $nonce = '';
  if ( isset($_GET['nonce'])) {
    $nonce = sanitize_text_field(wp_unslash($_GET['nonce']));
  } elseif ( isset($_REQUEST['nonce'])) {
    $nonce = sanitize_text_field(wp_unslash($_REQUEST['nonce']));
  }

  if ( ! wp_verify_nonce($nonce, 'mindweco_trial_nonce')) {
    wp_send_json_error( array( 'message' => esc_html__('Invalid nonce.', 'mind-web-concierge') ) );
    return;
  }

  $app_guid = get_option('mindweco_plugin_guid', '');
  $stripe_base_url = mindweco_get_stripe_base_url();
  $api_response = mindweco_get_history_subscription($stripe_base_url, $app_guid);

  if ( isset($api_response['error'])) {
    wp_send_json_error( array( 'message' => esc_html($api_response['error'] ) ) );
    return;
  }

  wp_send_json_success($api_response);
}

add_action( 'wp_ajax_mindweco_cancel_subscription', 'mindweco_cancel_subscription_ajax', );

function mindweco_cancel_subscription_ajax() {
  check_ajax_referer('mindweco_trial_nonce', 'nonce');

  if ( ! current_user_can( 'manage_options' ) ) {
    wp_send_json_error( array( 'message' => esc_html__('Access denied.' , 'mind-web-concierge') ) );
    return;
  }

  $subscription_id = isset($_POST['subscription_id']) ? sanitize_text_field(wp_unslash($_POST['subscription_id'])) : "";
  if ( empty( $subscription_id )) {
    wp_send_json_error( array( 'message' => esc_html__('Missing subscription ID.', 'mind-web-concierge') ) );
    return;
  }

  $app_guid = get_option('mindweco_plugin_guid', '');
  $stripe_base_url = mindweco_get_stripe_base_url();
  $api_response = mindweco_plugin_cancel_subscription(
    $stripe_base_url,
    $app_guid,
    $subscription_id,
    true,
  );

  if ( isset($api_response['error'])) {
    wp_send_json_error( array( 'message' => esc_html($api_response['error']) ) );
    return;
  }

  wp_send_json_success( array( 'message' => esc_html__(
      'Subscription cancelled successfully.',
      'mind-web-concierge',
    ), ) );

}

add_action( 'wp_ajax_mindweco_reactivate_subscription', 'mindweco_reactivate_subscription_ajax', );

function mindweco_reactivate_subscription_ajax() {
  check_ajax_referer('mindweco_trial_nonce', 'nonce');

  if ( ! current_user_can( 'manage_options' ) ) {
    wp_send_json_error( array(  'message' => esc_html__('Access denied.', 'mind-web-concierge') ) );
    return;
  }

  $subscription_id = isset($_POST['subscription_id']) ? sanitize_text_field(wp_unslash($_POST['subscription_id'])) : "";
  if ( empty( $subscription_id )) {
    wp_send_json_error( array( 'message' =>  esc_html__('Missing subscription ID.', 'mind-web-concierge'  ), ) );
    return;
  }

  $app_guid = get_option('mindweco_plugin_guid', '');
  $stripe_base_url = mindweco_get_stripe_base_url();
  $api_response = mindweco_plugin_reactivate_subscription(
    $stripe_base_url,
    $app_guid,
    $subscription_id,
    false,
  );

  if ( isset($api_response['error'])) {
    wp_send_json_error( array( 'message' => esc_html($api_response['error']) ) );
    return;
  }

  wp_send_json_success( array( 'message' => esc_html__(
      'Subscription reactivated successfully.',
      'mind-web-concierge',
    ), ) );

}

add_action( 'wp_ajax_mindweco_add_trial_subscription', 'mindweco_add_trial_subscription_ajax', );

function mindweco_add_trial_subscription_ajax() {
  check_ajax_referer('mindweco_trial_nonce', 'nonce');

  if ( ! is_user_logged_in()) {
    wp_send_json_error( array( 'message' => esc_html__('User not logged in.', 'mind-web-concierge') ) );
    return;
  }

  $guid = isset($_POST['app_guid']) ? sanitize_text_field(wp_unslash($_POST['app_guid'])) : '';
  $stripe_base_url = mindweco_get_stripe_base_url();
  $product_id = mindweco_get_product_id();
  $user = wp_get_current_user();
  $user_email = $user->user_email;
  $title = get_option('siteurl');
  $site_base_url = get_option('siteurl');

  $response = mindweco_stripe_add_trial(
    $stripe_base_url,
    $guid,
    $product_id,
    $user_email,
    $title,
    $site_base_url
  );

  if ( ! $response || isset($response['error'])) {
    wp_send_json_error( 
      array( 'message' => isset($response['error']) ? esc_html($response['error']) : esc_html__('Unknown error.', 'mind-web-concierge')  ) );
    return;
  }

  $subscription = isset($response['subscription']) ? $response['subscription'] : array();

  mindweco_save_subscription_options($subscription);

  wp_send_json_success($response);
}

add_action( 'wp_ajax_mindweco_add_trial_without_user', 'mindweco_add_trial_without_user_ajax' );

function mindweco_add_trial_without_user_ajax() {
  check_ajax_referer('mindweco_trial_nonce', 'nonce');

  if ( ! is_user_logged_in()) {
    wp_send_json_error( array( 'message' => esc_html__('User not logged in.', 'mind-web-concierge') ) );
    return;
  }

  $guid = isset($_POST['app_guid']) ? sanitize_text_field(wp_unslash($_POST['app_guid'])) : '';
  $stripe_base_url = mindweco_get_stripe_base_url();
  $product_id = mindweco_get_product_id();
  $user = wp_get_current_user();
  $user_email = $user->user_email;

  $response = mindweco_stripe_add_trial_without_user(
    $stripe_base_url,
    $guid,
    $product_id,
    $user_email,
  );

  if ( ! $response || isset($response['error'])) {
    wp_send_json_error( 
      array( 'message' => isset($response['error'])
        ? esc_html($response['error'])
        : esc_html__('Unknown error.', 'mind-web-concierge')
       ) );

    return;
  }

  $subscription = isset($response['subscription']) ? $response['subscription'] : array();
  mindweco_save_subscription_options($subscription);

  wp_send_json_success($response);
}

add_action('wp_ajax_mindweco_download_invoice', 'mindweco_download_invoice');

function mindweco_download_invoice() {
  check_ajax_referer('mindweco_trial_nonce', 'nonce');

  if ( ! current_user_can( 'manage_options' ) ) {
    wp_send_json_error( array(  'message' => esc_html__('Access denied.', 'mind-web-concierge') ) );
    return;
  }

  $stripe_base_url = mindweco_get_stripe_base_url();
  $invoice_number = isset($_POST['invoice_number']) ? sanitize_text_field(wp_unslash($_POST['invoice_number'])) : "";

  if ( empty( $invoice_number )) {
    wp_send_json_error( array( 'message' => esc_html__('Invoice number missing.', 'mind-web-concierge') ) );
    return;
  }

  $result = mindweco_download_subscription_invoice($stripe_base_url, $invoice_number);

  if ( isset($result['url'])) {
    wp_send_json_success( array('url' => esc_url_raw($result['url'] ) ) );
    return;
  }

  wp_send_json_error( array(
    'message' => isset($result['error'])
        ? esc_html($result['error'])
        : esc_html__('Unknown error.', 'mind-web-concierge')
  ) );
}

/**
 * @param array $subscription Subscription data array from the API.
 */
function mindweco_save_subscription_options( $subscription ) {
    update_option( 'mindweco_trial_response', $subscription );

    if ( isset( $subscription['currentPeriodStart'] ) ) {
        update_option( 'mindweco_trial_start', sanitize_text_field( $subscription['currentPeriodStart'] ) );
    }
    if ( isset( $subscription['currentPeriodEnd'] ) ) {
        update_option( 'mindweco_trial_end', sanitize_text_field( $subscription['currentPeriodEnd'] ) );
    }
    if ( isset( $subscription['id'] ) ) {
        update_option( 'mindweco_subscription_id', sanitize_text_field( $subscription['id'] ) );
    }
    if ( isset( $subscription['customerEmail'] ) ) {
        update_option( 'mindweco_customer_email', sanitize_email( $subscription['customerEmail'] ) );
    }
    if ( isset( $subscription['status'] ) ) {
        update_option( 'mindweco_subscription_status', sanitize_text_field( $subscription['status'] ) );
    }
}

add_action('wp_ajax_mindweco_get_buy_url', 'mindweco_get_buy_url_ajax');

function mindweco_get_buy_url_ajax() {
    check_ajax_referer('mindweco_trial_nonce', 'nonce');

    $product_id  = mindweco_get_product_id();
    $app_guid    = get_option('mindweco_plugin_guid', '');
    $stripe_base = rtrim(mindweco_get_stripe_base_url() , '/');
    $user        = wp_get_current_user();
    $user_email  = ( $user->exists() && ! empty( $user->user_email ) ) ? (string) $user->user_email : '';

    if ( empty( $product_id ) || empty( $app_guid ) || empty( $stripe_base )) {
      wp_send_json_error( 
        array( 'message' => esc_html__('Missing configuration.', 'mind-web-concierge') ) 
      );
        return;
    }

    $stripe_base = mindweco_get_stripe_base_url();
    $buy_base    = preg_replace('#/api/?$#', '', rtrim($stripe_base, '/'));

    $url = $buy_base . '/Product/' . rawurlencode($product_id)
      . '?app-guid='       . rawurlencode($app_guid)
      . '&customer-email=' . str_replace('%40', '@', rawurlencode($user_email));

    wp_send_json_success( array( 'url' => $url ) );
}
