<?php

if ( ! defined( 'WPINC' ) ) {
	die;
}

require_once __DIR__ . "/../controllers/cart.php";

function shpsafe_register_route()
{
  $baseurl = "shipsafely/v1";

  // get insurance price
  register_rest_route($baseurl, "cart/insuranceprice", [
    "methods" => "POST",
    "callback" => "SHIPSAFELY_Cart::shpsafe_get_variant",
    "permission_callback" => "__return_true",
  ]);

  // add insurance to cart
  register_rest_route($baseurl, "cart/insurance", [
    "methods" => "PUT",
    "callback" => "SHIPSAFELY_Cart::shpsafe_add_to_cart",
    "permission_callback" => "__return_true",
  ]);

  // remove insurance from cart
  register_rest_route($baseurl, "cart/insurance/(?P<id>\d+)", [
    "methods" => "DELETE",
    "callback" => "SHIPSAFELY_Cart::shpsafe_remove_from_cart",
    "permission_callback" => "__return_true",
  ]);

  // get cart price (POST to prevent CDN/proxy caching)
  register_rest_route($baseurl, "cart/price", [
    "methods" => "POST",
    "callback" => "SHIPSAFELY_Cart::shpsafe_cart_price",
    "permission_callback" => "__return_true",
  ]);

  // get cart insurance (POST to prevent CDN/proxy caching)
  register_rest_route($baseurl, "cart/insurance/current", [
    "methods" => "POST",
    "callback" => "SHIPSAFELY_Cart::shpsafe_cart_insurance",
    "permission_callback" => "__return_true",
  ]);

  // refresh API token (admin only)
  register_rest_route($baseurl, "auth/refresh", [
    "methods" => "POST",
    "callback" => "shpsafe_refresh_api_token",
    "permission_callback" => function() {
      return current_user_can( 'manage_options' );
    },
  ]);
}

add_action("rest_api_init", "shpsafe_register_route");

/**
 * Add no-cache headers to all Ship-Safely REST API responses.
 * Prevents CDN/proxy layers (e.g. Cloudflare) from caching cart-state responses.
 */
add_filter( 'rest_post_dispatch', 'shpsafe_add_no_cache_headers', 10, 3 );
function shpsafe_add_no_cache_headers( $response, $server, $request ) {
  $route = $request->get_route();
  if ( strpos( $route, '/shipsafely/' ) === 0 ) {
    $response->header( 'Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0' );
    $response->header( 'Pragma', 'no-cache' );
    $response->header( 'Expires', '0' );
  }
  return $response;
}

/**
 * Delete stale API keys and re-request a fresh token from Ship-Safely.
 */
function shpsafe_refresh_api_token() {
  delete_option( 'shpsafe_woo_user_api_token' );
  delete_option( 'shpsafe_woo_admin_api_token' );

  require_once __DIR__ . '/../includes/config.php';
  $base_url = SHIPSAFELY_Config::shpsafe_server_url();
  $hostname = parse_url( get_site_url(), PHP_URL_HOST );

  $response = wp_remote_post( $base_url . '/v3/apitoken', [
    'method'   => 'POST',
    'timeout'  => 45,
    'blocking' => true,
    'body'     => [ 'context' => $hostname ],
  ]);

  if ( is_wp_error( $response ) || wp_remote_retrieve_response_code( $response ) !== 200 ) {
    return new WP_REST_Response( [ 'success' => false ], 500 );
  }

  $body = json_decode( wp_remote_retrieve_body( $response ) );
  update_option( 'shpsafe_woo_user_api_token', $body->user_token );
  update_option( 'shpsafe_woo_admin_api_token', $body->admin_token );

  return new WP_REST_Response( [
    'success' => true,
    'token'   => $body->admin_token,
  ], 200 );
}

/**
 * Override the cart item price with the exact backend price
 * when a Ship-Safely insurance product is in the cart.
 */
function shpsafe_set_exact_cart_item_price( $cart ) {
  if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
    return;
  }

  if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) {
    return;
  }

  foreach ( $cart->get_cart() as $cart_item ) {
    if ( isset( $cart_item['shipsafely_exact_price'] ) ) {
      $cart_item['data']->set_price( $cart_item['shipsafely_exact_price'] );
      // Keep the display name clean — strip any trailing price from the product title
      $name = $cart_item['data']->get_name();
      $clean = preg_replace( '/\s*[-–—]\s*[\d,.]+\s*$/', '', $name );
      if ( $clean !== $name ) {
        $cart_item['data']->set_name( $clean );
      }
    }
  }
}
add_action( 'woocommerce_before_calculate_totals', 'shpsafe_set_exact_cart_item_price', 20, 1 );

/**
 * Hide variation attributes (e.g. "Insurance: 1.28") shown below the
 * product name in cart / checkout for Ship-Safely insurance items.
 */
function shpsafe_hide_insurance_item_meta( $item_data, $cart_item ) {
  if ( isset( $cart_item['shipsafely_exact_price'] ) ) {
    return [];
  }
  return $item_data;
}
add_filter( 'woocommerce_get_item_data', 'shpsafe_hide_insurance_item_meta', 10, 2 );

/**
 * When a cart item becomes an order item, remove the variation attribute
 * meta (e.g. "Insurance: 1.28") from Ship-Safely insurance line items.
 */
function shpsafe_clean_insurance_order_item_meta( $item, $cart_item_key, $values, $order ) {
  if ( isset( $values['shipsafely_exact_price'] ) ) {
    // Remove all "pa_" or "attribute_" meta entries (variation attributes)
    foreach ( $item->get_meta_data() as $meta ) {
      $key = $meta->key;
      if ( strpos( $key, 'pa_' ) === 0 || strpos( $key, 'attribute_' ) === 0 ) {
        $item->delete_meta_data( $key );
      }
    }
    // Also remove the common "Insurance" display attribute
    $item->delete_meta_data( 'insurance' );
    $item->delete_meta_data( 'Insurance' );
  }
}
add_action( 'woocommerce_checkout_create_order_line_item', 'shpsafe_clean_insurance_order_item_meta', 10, 4 );

