<?php

namespace CF7PA_Pay_Addons\Shared;

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

use CF7PA_Pay_Addons\Stripe\Stripe_API;
use CF7PA_Pay_Addons\Shared\Utils;

class Placeholder
{
  public static function get_receipt_placeholders($payment_intent_id, $last_payment_error = [])
  {
    $payment_intent = Stripe_API::retrieve_payment_intent($payment_intent_id, ['expand' => ['customer', 'payment_method', 'latest_charge']]);

    $placeholders = array();
    $billDetail = $payment_intent['payment_method']['billing_details'];
    $shippingDetail = $payment_intent['shipping'];
    $charge = $payment_intent['latest_charge'];

    // Get customer object
    $customer = null;
    if (!empty($payment_intent['customer'])) {
      $customer = Stripe_API::retrieve_customer($payment_intent['customer']['id'], []);
    }

    // Handle customer information with shared logic
    self::set_customer_placeholders($customer, $billDetail, $placeholders);

    // Set basic payment intent info
    $placeholders['payment_intent_id'] = $payment_intent['id'];
    $placeholders['description'] = $payment_intent['description'];
    $placeholders['currency'] = $payment_intent['currency'];
    $placeholders['amount'] = Utils::format_stripe_amount($payment_intent['amount']);
    $placeholders['created'] = Utils::format_stripe_date($payment_intent['created']);
    $placeholders['format_date'] = Utils::format_stripe_date($payment_intent['created']);
    $placeholders['format_time'] = Utils::format_stripe_time($payment_intent['created']);
    $placeholders['amount_currency'] = Utils::format_amount_with_symbol($payment_intent['amount'], $payment_intent['currency']);

    // Handle billing details with shared logic
    self::set_billing_placeholders($billDetail, $placeholders);

    // Handle shipping details with shared logic
    self::set_shipping_placeholders($shippingDetail, $placeholders);

    // Set payment method details
    $placeholders['payment_method.type'] = $payment_intent['payment_method']['type'];
    $placeholders['payment_method.card.brand'] = $payment_intent['payment_method']['card']['brand'] ?? '';
    $placeholders['payment_method.card.last4'] = $payment_intent['payment_method']['card']['last4'] ?? '';

    // Handle metadata
    if (!empty($payment_intent['metadata'])) {
      self::append_metadata_placeholder($payment_intent, $placeholders);
    }

    // Error handling
    if (!empty($last_payment_error)) {
      $placeholders['error.message'] = $last_payment_error['message'];
    }

    $placeholders['receipt.url'] = $charge['receipt_url'];

    return $placeholders;
  }

  public static function get_checkout_session_placeholders($checkout_session_id, $last_payment_error = [])
  {
    $checkout_session = Stripe_API::retrieve_checkout_session($checkout_session_id, [
      'expand' => ['customer', 'subscription', 'invoice']
    ]);

    $placeholders = array();

    // Set basic checkout session info
    $placeholders['checkout_session_id'] = $checkout_session['id'];
    $placeholders['currency'] = $checkout_session['currency'] ?? 'usd';
    $placeholders['amount'] = Utils::format_stripe_amount($checkout_session['amount_total'] ?? 0);
    $placeholders['amount_currency'] = Utils::format_amount_with_symbol($checkout_session['amount_total'] ?? 0, $checkout_session['currency'] ?? 'usd');
    $placeholders['created'] = Utils::format_stripe_date($checkout_session['created']);
    $placeholders['format_date'] = Utils::format_stripe_date($checkout_session['created']);
    $placeholders['format_time'] = Utils::format_stripe_time($checkout_session['created']);

    // Prepare data for shared helper methods
    $customer = $checkout_session['customer'] ?? null;
    $customer_details = $checkout_session['customer_details'] ?? [];
    $shippingDetail = $checkout_session['shipping_details'] ?? null;

    // Handle customer information with shared logic
    self::set_customer_placeholders($customer, $customer_details, $placeholders);

    // Handle billing details with shared logic
    self::set_billing_placeholders($customer_details, $placeholders);

    // Handle shipping details with shared logic
    self::set_shipping_placeholders($shippingDetail, $placeholders);

    // Handle metadata
    if (!empty($checkout_session['metadata'])) {
      self::append_metadata_placeholder($checkout_session, $placeholders);
    }

    // Error handling
    if (!empty($last_payment_error)) {
      $placeholders['error.message'] = $last_payment_error['message'];
    }

    // For no-cost orders, there's no receipt URL or payment method
    $placeholders['receipt.url'] = '';
    $placeholders['payment_method.type'] = '';
    $placeholders['payment_method.card.brand'] = '';
    $placeholders['payment_method.card.last4'] = '';

    return $placeholders;
  }

  // Unified customer placeholders method
  private static function set_customer_placeholders($customer, $fallbackDetail, &$placeholders)
  {
    // Set from customer object first
    if (!empty($customer)) {
      $placeholders['customer.email'] = $customer['email'] ?? '';
      $placeholders['customer.name'] = $customer['name'] ?? '';
      $placeholders['customer.phone'] = $customer['phone'] ?? '';

      if (!empty($customer['address'])) {
        self::set_address_placeholders($customer['address'], 'customer.address', $placeholders);
      } else {
        self::set_empty_address_placeholders('customer.address', $placeholders);
      }
    } else {
      // Set empty customer placeholders
      $placeholders['customer.email'] = '';
      $placeholders['customer.name'] = '';
      $placeholders['customer.phone'] = '';
      self::set_empty_address_placeholders('customer.address', $placeholders);
    }

    // Fallback to provided detail (billing_details or customer_details)
    if (!empty($fallbackDetail)) {
      if (empty($placeholders['customer.name'])) {
        $placeholders['customer.name'] = $fallbackDetail['name'] ?? '';
      }
      if (empty($placeholders['customer.email'])) {
        $placeholders['customer.email'] = $fallbackDetail['email'] ?? '';
      }
      if (empty($placeholders['customer.phone'])) {
        $placeholders['customer.phone'] = $fallbackDetail['phone'] ?? '';
      }
    }
  }

  // Unified billing placeholders method
  private static function set_billing_placeholders($billDetail, &$placeholders)
  {
    if (!empty($billDetail)) {
      $placeholders['billing_detail.email'] = $billDetail['email'] ?? '';
      $placeholders['billing_detail.name'] = $billDetail['name'] ?? '';
      $placeholders['billing_detail.phone'] = $billDetail['phone'] ?? '';

      if (!empty($billDetail['address'])) {
        self::set_address_placeholders($billDetail['address'], 'billing_detail.address', $placeholders);
      } else {
        self::set_empty_address_placeholders('billing_detail.address', $placeholders);
      }
    } else {
      // Set empty billing placeholders
      $placeholders['billing_detail.email'] = '';
      $placeholders['billing_detail.name'] = '';
      $placeholders['billing_detail.phone'] = '';
      self::set_empty_address_placeholders('billing_detail.address', $placeholders);
    }
  }

  // Unified shipping placeholders method
  private static function set_shipping_placeholders($shippingDetail, &$placeholders)
  {
    if (!empty($shippingDetail)) {
      $placeholders['shipping_detail.name'] = $shippingDetail['name'] ?? '';
      $placeholders['shipping_detail.phone'] = $shippingDetail['phone'] ?? '';

      if (!empty($shippingDetail['address'])) {
        self::set_address_placeholders($shippingDetail['address'], 'shipping_detail.address', $placeholders);
      } else {
        self::set_empty_address_placeholders('shipping_detail.address', $placeholders);
      }
    } else {
      // Set empty shipping placeholders
      $placeholders['shipping_detail.name'] = '';
      $placeholders['shipping_detail.phone'] = '';
      self::set_empty_address_placeholders('shipping_detail.address', $placeholders);
    }
  }

  // Shared address placeholder logic
  private static function set_address_placeholders($address, $prefix, &$placeholders)
  {
    $placeholders[$prefix . '.country'] = $address['country'] ?? '';
    $placeholders[$prefix . '.state'] = $address['state'] ?? '';
    $placeholders[$prefix . '.city'] = $address['city'] ?? '';
    $placeholders[$prefix . '.line1'] = $address['line1'] ?? '';
    $placeholders[$prefix . '.line2'] = $address['line2'] ?? '';
    $placeholders[$prefix . '.postal_code'] = $address['postal_code'] ?? '';
    $placeholders[$prefix . '.formatted'] = Utils::get_formatted_address($address);
  }

  // Shared empty address placeholder logic
  private static function set_empty_address_placeholders($prefix, &$placeholders)
  {
    $placeholders[$prefix . '.country'] = '';
    $placeholders[$prefix . '.state'] = '';
    $placeholders[$prefix . '.city'] = '';
    $placeholders[$prefix . '.line1'] = '';
    $placeholders[$prefix . '.line2'] = '';
    $placeholders[$prefix . '.postal_code'] = '';
    $placeholders[$prefix . '.formatted'] = '';
  }

  public static function append_metadata_placeholder( &$payment_intent, &$placeholders ) {
        $placeholders['metadata'] = json_encode( $payment_intent['metadata'] );
        $payment_intent_metadata = $payment_intent['metadata']->toArray();
        foreach ( $payment_intent_metadata as $k => $v ) {
            $placeholders['metadata.' . $k] = $v;
        }
    }
}
