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

if ( ! class_exists( 'WC_Payment_Gateway' ) ) { return; }


class Flexilay_WC_Gateway extends WC_Payment_Gateway {

	public function __construct() {
		$this->id                 = 'flexilay';
		$this->method_title       = __( 'FlexiLay', 'flexilay-gateway-for-woocommerce' );
		$this->method_description = __( 'Customers choose a lay-buy schedule and pay via FlexiLay.', 'flexilay-gateway-for-woocommerce' );
		$this->has_fields         = false;

		$this->init_form_fields();
		$this->init_settings();

		$this->title       = $this->get_option( 'title', __( 'FlexiLay', 'flexilay-gateway-for-woocommerce' ) );
		$this->description = $this->get_option( 'description', __( 'Pay with FlexiLay lay-buy.', 'flexilay-gateway-for-woocommerce' ) );

		add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
	}

	public function init_form_fields() {
		$this->form_fields = array(
			'enabled' => array(
				'title'   => __( 'Enable/Disable', 'flexilay-gateway-for-woocommerce' ),
				'type'    => 'checkbox',
				'label'   => __( 'Enable FlexiLay', 'flexilay-gateway-for-woocommerce' ),
				'default' => 'no',
			),
			'title' => array(
				'title'       => __( 'Title', 'flexilay-gateway-for-woocommerce' ),
				'type'        => 'text',
				'description' => __( 'Displayed to customers at checkout.', 'flexilay-gateway-for-woocommerce' ),
				'default'     => __( 'FlexiLay', 'flexilay-gateway-for-woocommerce' ),
			),
			'description' => array(
				'title'       => __( 'Description', 'flexilay-gateway-for-woocommerce' ),
				'type'        => 'textarea',
				'description' => __( 'Displayed to customers at checkout.', 'flexilay-gateway-for-woocommerce' ),
				'default'     => __( 'Choose your deposit and payment schedule.', 'flexilay-gateway-for-woocommerce' ),
			),
		);
	}

	public function process_payment( $order_id ) {
		$order = wc_get_order( $order_id );
		if ( ! $order ) {
			wc_add_notice( __( 'Unable to load order for FlexiLay.', 'flexilay-gateway-for-woocommerce' ), 'error' );
			return array( 'result' => 'failure' );
		}

		$api_base = Flexilay_Woo_Options::get_api_base();
		if ( $api_base === '' ) {
			wc_add_notice( __( 'FlexiLay is not configured (missing API base).', 'flexilay-gateway-for-woocommerce' ), 'error' );
			return array( 'result' => 'failure' );
		}

		// Require onboarding token present.
		$install_token = Flexilay_Woo_Options::ensure_install_token();
		if ( $install_token === '' ) {
			wc_add_notice( __( 'FlexiLay is not configured. Please contact the store owner.', 'flexilay-gateway-for-woocommerce' ), 'error' );
			return array( 'result' => 'failure' );
		}

		$total = (float) $order->get_total();
		if ( $total <= 0 ) {
			wc_add_notice( __( 'Order total must be greater than zero for FlexiLay.', 'flexilay-gateway-for-woocommerce' ), 'error' );
			return array( 'result' => 'failure' );
		}

		$shop_domain  = Flexilay_Woo_Options::get_shop_domain();
		$currency     = (string) $order->get_currency();
		$amount_cents = (int) round( $total * 100 );

		$customer_name  = trim( (string) $order->get_billing_first_name() . ' ' . (string) $order->get_billing_last_name() );
		if ( $customer_name === '' ) {
			$customer_name = (string) $order->get_formatted_billing_full_name();
		}

		$shipping_address = array(
			'address1' => (string) $order->get_shipping_address_1(),
			'address2' => (string) $order->get_shipping_address_2(),
			'city'     => (string) $order->get_shipping_city(),
			'state'    => (string) $order->get_shipping_state(),
			'postcode' => (string) $order->get_shipping_postcode(),
			'country'  => (string) $order->get_shipping_country(),
		);

		$shipping_title = '';
		$shipping_cents = (int) round( (float) $order->get_shipping_total() * 100 );

		$line_items = array();
		foreach ( $order->get_items() as $item ) {
			if ( ! is_a( $item, 'WC_Order_Item_Product' ) ) { continue; }
			$qty = (int) $item->get_quantity();
			$total_line = (float) $item->get_total();
			$price_cents = (int) round( ( $qty > 0 ? ( $total_line / $qty ) : $total_line ) * 100 );
			$line_items[] = array(
				'title'      => (string) $item->get_name(),
				'quantity'   => $qty,
				'priceCents' => $price_cents,
			);
		}

		$payload = array(
			'shopDomain'        => $shop_domain,
			'amountCents'       => $amount_cents,
			'currency'          => $currency,
			'customerName'      => $customer_name,
			'customerEmail'     => (string) $order->get_billing_email(),
			'customerMobile'    => (string) $order->get_billing_phone(),
			'externalOrderId'   => (string) $order->get_id(),
			'externalOrderName' => (string) $order->get_order_number(),
			'lineItems'         => $line_items,
			'shippingAddress'   => $shipping_address,
			'shippingTitle'     => $shipping_title,
			'shippingPriceCents'=> $shipping_cents,
			'rawOrderJson'      => array(
				'woocommerce' => true,
				'orderId'     => (string) $order->get_id(),
				'siteUrl'     => home_url(),
			),
		);

		// Check merchant is paired before proceeding
		$api_key = Flexilay_Woo_Options::get_api_key();
		if ( $api_key === '' ) {
			wc_add_notice( __( 'FlexiLay is not yet fully configured. Please contact the store owner.', 'flexilay-gateway-for-woocommerce' ), 'error' );
			return array( 'result' => 'failure' );
		}

		// Use API key + shop header for draft plan creation
		$headers = array(
			'Content-Type'        => 'application/json',
			'X-Flexilay-Shop'     => $shop_domain,
			'X-Flexilay-Api-Key'  => $api_key,
		);

		$url = $api_base . '/api/plans/draft';

		$resp = wp_remote_post( $url, array(
			'timeout' => 25,
			'headers' => $headers,
			'body'    => wp_json_encode( $payload ),
		) );

		if ( is_wp_error( $resp ) ) {
			if ( defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
				error_log( '[FlexiLay] process_payment failed: ' . $resp->get_error_message() );
			}
			wc_add_notice( __( 'FlexiLay request failed. Please try again.', 'flexilay-gateway-for-woocommerce' ), 'error' );
			return array( 'result' => 'failure' );
		}

		$code = (int) wp_remote_retrieve_response_code( $resp );
		$raw = (string) wp_remote_retrieve_body( $resp );
		$data = json_decode( $raw, true );

		if ( $code >= 400 || json_last_error() !== JSON_ERROR_NONE || ! is_array( $data ) || empty( $data['ok'] ) ) {
			$error_msg = isset( $data['error'] ) ? (string) $data['error'] : 'Unknown error';
			if ( defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
				error_log( '[FlexiLay] process_payment error: HTTP ' . $code . ' — ' . $error_msg );
			}
			wc_add_notice( __( 'FlexiLay could not process this order. Please try again or contact the store owner.', 'flexilay-gateway-for-woocommerce' ), 'error' );
			return array( 'result' => 'failure' );
		}

		// Expect planUrl to redirect customer to schedule selection.
		$redirect = '';
		if ( ! empty( $data['planUrl'] ) && is_string( $data['planUrl'] ) ) {
			$redirect = $data['planUrl'];
		} elseif ( ! empty( $data['url'] ) && is_string( $data['url'] ) ) {
			$redirect = $data['url'];
		}

		if ( $redirect === '' ) {
			wc_add_notice( __( 'FlexiLay did not return a redirect URL. Please contact the store owner.', 'flexilay-gateway-for-woocommerce' ), 'error' );
			return array( 'result' => 'failure' );
		}

		$order->update_status( 'pending', __( 'Awaiting FlexiLay schedule setup.', 'flexilay-gateway-for-woocommerce' ) );

		return array(
			'result'   => 'success',
			'redirect' => esc_url_raw( $redirect ),
		);
	}
}
