<?php

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

/**
 * Fired during plugin got token and keys
 *
 * @link       https://ship-safely.com
 * @since      1.0.0
 *
 * @package    Ship_Safely
 * @subpackage Ship_Safely/controllers
 */

class SHIPSAFELY_Cart
{
  /**
   * Verify the insurance product exists and return price info.
   */
  public static function shpsafe_get_variant($request)
  {
    try {
      $parameters = $request->get_params();
      $id = $parameters["id"];
      $price = isset($parameters["price"]) ? floatval($parameters["price"]) : 0;
      $currency = isset($parameters["currency"]) ? $parameters["currency"] : 'USD';

      $product = wc_get_product($id);

      if (!$product) {
        return new WP_Error("Cart", "Failed to get ship-safely product.", [
          "status" => 400,
        ]);
      }

      return [
        "product_id" => $id,
        "display_price" => $price,
        "currency" => $currency,
      ];
    } catch (\Exception $error) {
      return new WP_Error(
        "Cart",
        "Failed to find 'Ship-Safely Shipping Protection' product.",
        [
          "status" => 400,
        ]
      );
    }
  }

  /**
   * add ship-safely to cart
   */
  public static function shpsafe_add_to_cart($request)
  {
    try {
      defined("WC_ABSPATH") || exit();

      // Load cart functions which are loaded only on the front-end.
      include_once WC_ABSPATH . "includes/wc-cart-functions.php";
      include_once WC_ABSPATH . "includes/class-wc-cart.php";

      if (is_null(WC()->cart)) {
        wc_load_cart();
      }

      global $woocommerce;
      $items = $woocommerce->cart->get_cart();

      $parameters = $request->get_params();
      $id = $parameters["id"];
      $exact_price = isset($parameters["price"]) ? floatval($parameters["price"]) : null;

      $product = wc_get_product($id);
      if (!$product) {
        return new WP_Error("Cart", "Can't find Ship-Safely products.", [
          "status" => 400,
        ]);
      }

      // Remove existing insurance from cart (limit to 1)
      foreach ($items as $item) {
        if ($item["product_id"] == $id) {
          $woocommerce->cart->remove_cart_item($item["key"]);
        }
      }

      // Pass exact price as cart item data so the price filter can use it
      $cart_item_data = [];
      if ($exact_price !== null) {
        $cart_item_data['shipsafely_exact_price'] = $exact_price;
      }

      // Handle both simple and variable products
      $variation_id = 0;
      if ($product->is_type('variable')) {
        $variations = $product->get_available_variations();
        if (!empty($variations)) {
          $variation_id = $variations[0]['variation_id'];
        }
      }

      $res = $woocommerce->cart->add_to_cart($id, 1, $variation_id, [], $cart_item_data);

      return true;
    } catch (\Exception $error) {
      return new WP_Error(
        "Cart",
        "Failed to add 'Ship-Safely Shipping Protection' product to cart.",
        [
          "status" => 400,
        ]
      );
    }

    return "Success";
  }

  /**
   * remove ship-safely from cart
   *
   */
  public static function shpsafe_remove_from_cart($request)
  {
    try {
      defined("WC_ABSPATH") || exit();

      // Load cart functions which are loaded only on the front-end.
      include_once WC_ABSPATH . "includes/wc-cart-functions.php";
      include_once WC_ABSPATH . "includes/class-wc-cart.php";

      if (is_null(WC()->cart)) {
        wc_load_cart();
      }

      global $woocommerce;
      $items = $woocommerce->cart->get_cart();

      $parameters = $request->get_params();

      $id = $parameters["id"];

      // delete a cart item
      foreach ($items as $item) {
        if ($item["product_id"] == $id) {
          $r = $woocommerce->cart->remove_cart_item($item["key"]);
        }
      }
    } catch (\Exception $error) {
      return new WP_Error(
        "Cart",
        "Failed to delete 'Ship-Safely Shipping Protection' product from cart.",
        [
          "status" => 400,
        ]
      );
    }

    return "Success";
  }

  /**
   * Get cart price
   *
   */
  public static function shpsafe_cart_price($request)
  {
    try {
      defined("WC_ABSPATH") || exit();

      // Load cart functions which are loaded only on the front-end.
      include_once WC_ABSPATH . "includes/wc-cart-functions.php";
      include_once WC_ABSPATH . "includes/class-wc-cart.php";

      if (is_null(WC()->cart)) {
        wc_load_cart();
      }


      global $woocommerce;
      // Force WooCommerce to recalculate the cart totals for accuracy
      $woocommerce->cart->calculate_totals();
      $items = $woocommerce->cart->get_cart();

      $parameters = $request->get_json_params() ?: $request->get_params();
      $id = $parameters["id"];

      // Sum tax-inclusive display prices (mirrors prices.price * quantity
      // from the Store API) so insurance is priced on what the customer sees.
      $base_total = 0;
      foreach ($items as $item) {
        if ($item["product_id"] == $id) {
          continue; // skip the insurance item itself
        }
        $base_total += wc_get_price_including_tax($item["data"]) * $item["quantity"];
      }

      // Store the base cart total so we can verify at checkout that
      // the insurance price is still valid for the current cart.
      if ( function_exists('WC') && WC()->session ) {
        WC()->session->set( 'shipsafely_base_cart_total', round( $base_total, 2 ) );
      }

      return $base_total;
    } catch (\Exception $error) {
      return new WP_Error("Cart", "Failed to get cart price.", [
        "status" => 400,
      ]);
    }

    return new WP_Error("Cart", "Failed to get cart price.", [
      "status" => 400,
    ]);
  }

  /**
   * Get cart insurance instance
   *
   */
  public static function shpsafe_cart_insurance($request)
  {
    try {
      defined("WC_ABSPATH") || exit();

      // Load cart functions which are loaded only on the front-end.
      include_once WC_ABSPATH . "includes/wc-cart-functions.php";
      include_once WC_ABSPATH . "includes/class-wc-cart.php";

      if (is_null(WC()->cart)) {
        wc_load_cart();
      }

      global $woocommerce;
      $items = $woocommerce->cart->get_cart();

      $parameters = $request->get_json_params() ?: $request->get_params();

      $id = $parameters["id"];

      foreach ($items as $item) {
        if ($item["product_id"] == $id) {
          return $item["line_total"];
        }
      }

      return null;
    } catch (\Exception $error) {
      return new WP_Error("Cart", "Failed to get ship-safely insurance.", [
        "status" => 400,
      ]);
    }

    return new WP_Error("Cart", "Failed to get ship-safely insurance.", [
      "status" => 400,
    ]);
  }
}
