<?php
defined( 'ABSPATH' ) || exit;

/**
 * GET + POST /tukiflow/v1/landing-pages — Manage TukiFlow checkout pages.
 */
class TFDC_Endpoint_Landing_Pages extends TFDC_Endpoint_Base {

	/**
	 * Register routes.
	 */
	public function register_routes() {
		register_rest_route(
			$this->namespace,
			'/landing-pages',
			array(
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_landing_pages' ),
					'permission_callback' => array( $this, 'check_permission' ),
				),
				array(
					'methods'             => WP_REST_Server::CREATABLE,
					'callback'            => array( $this, 'create_landing_page' ),
					'permission_callback' => array( $this, 'check_permission' ),
				),
			)
		);

		register_rest_route(
			$this->namespace,
			'/landing-pages/templates',
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( $this, 'get_templates' ),
				'permission_callback' => array( $this, 'check_permission' ),
			)
		);
	}

	/**
	 * Permission: manage_options + valid WP REST nonce.
	 *
	 * @param WP_REST_Request $request REST request.
	 * @return bool|WP_Error
	 */
	public function check_permission( WP_REST_Request $request ) {
		if ( ! current_user_can( 'manage_options' ) ) {
			return new WP_Error( 'rest_forbidden', __( 'Insufficient permissions.', 'tukiflow-direct-checkout-woocommerce' ), array( 'status' => 403 ) );
		}

		$nonce_check = $this->check_nonce( $request );
		if ( is_wp_error( $nonce_check ) ) {
			return $nonce_check;
		}

		return true;
	}

	/**
	 * Return all TukiFlow checkout landing pages or search products.
	 *
	 * @param WP_REST_Request $request REST request.
	 * @return WP_REST_Response
	 */
	public function get_landing_pages( WP_REST_Request $request ) {
		$page_ids = TFDC_Landing_Checkout::get_enabled_page_ids();
		if ( empty( $page_ids ) ) {
			return rest_ensure_response( array() );
		}

		$query = new WP_Query(
			array(
				'post_type'      => 'page',
				'post_status'    => array( 'publish', 'draft', 'pending', 'private', 'future' ),
				'posts_per_page' => 100,
				'post__in'       => $page_ids,
				'orderby'        => 'modified',
				'order'          => 'DESC',
			)
		);

		$pages = array();
		foreach ( $query->posts as $post ) {
			$pages[] = $this->format_page( $post );
		}

		return rest_ensure_response( $pages );
	}

	/**
	 * Create a checkout landing page with selected products.
	 *
	 * @param WP_REST_Request $request REST request.
	 * @return WP_REST_Response|WP_Error
	 */
	public function create_landing_page( WP_REST_Request $request ) {
		$body = $request->get_json_params();
		if ( ! is_array( $body ) ) {
			return $this->json_error( __( 'Invalid request body.', 'tukiflow-direct-checkout-woocommerce' ), 400 );
		}

		$title       = isset( $body['title'] ) ? sanitize_text_field( $body['title'] ) : '';
		$slug        = isset( $body['slug'] ) ? sanitize_title( $body['slug'] ) : '';
		$template_id = isset( $body['template_id'] ) ? sanitize_key( $body['template_id'] ) : 'blank';
		$product_ids = isset( $body['product_ids'] ) && is_array( $body['product_ids'] )
			? array_values( array_unique( array_filter( array_map( 'absint', $body['product_ids'] ) ) ) )
			: array();
		$raw_quantities = isset( $body['quantities'] ) && is_array( $body['quantities'] ) ? $body['quantities'] : array();

		if ( '' === $title ) {
			return $this->json_error( __( 'Page title is required.', 'tukiflow-direct-checkout-woocommerce' ), 422 );
		}

		if ( empty( $product_ids ) ) {
			return $this->json_error( __( 'Select at least one product.', 'tukiflow-direct-checkout-woocommerce' ), 422 );
		}

		$quantities = array();
		foreach ( $product_ids as $product_id ) {
			$product = wc_get_product( $product_id );
			if ( ! $product || ! $product->is_purchasable() ) {
				return $this->json_error( __( 'One or more selected products are not purchasable.', 'tukiflow-direct-checkout-woocommerce' ), 422 );
			}

			$quantities[ $product_id ] = max( 1, absint( $raw_quantities[ $product_id ] ?? 1 ) );
		}

		$page_id = wp_insert_post(
			array(
				'post_type'    => 'page',
				'post_status'  => 'draft',
				'post_title'   => $title,
				'post_name'    => $slug,
				'post_content' => TFDC_Template_Library::build_checkout_shortcode( $product_ids ),
			),
			true
		);

		if ( is_wp_error( $page_id ) ) {
			return $this->json_error( $page_id->get_error_message(), 500 );
		}

		$template_result = TFDC_Template_Library::apply_template( $page_id, $template_id, $product_ids );
		if ( is_wp_error( $template_result ) ) {
			wp_delete_post( $page_id, true );
			return $this->json_error( $template_result->get_error_message(), 422 );
		}

		update_post_meta( $page_id, TFDC_Landing_Checkout::META_ENABLED, 'yes' );
		TFDC_Landing_Checkout::set_page_enabled( $page_id, true );
		update_post_meta( $page_id, TFDC_Landing_Checkout::META_PRODUCTS, $product_ids );
		update_post_meta( $page_id, TFDC_Landing_Checkout::META_QUANTITIES, $quantities );

		return rest_ensure_response( $this->format_page( get_post( $page_id ) ) );
	}

	/**
	 * Return the bundled landing page templates.
	 *
	 * @return WP_REST_Response
	 */
	public function get_templates() {
		return rest_ensure_response( TFDC_Template_Library::get_templates() );
	}

	/**
	 * Format page data for the admin UI.
	 *
	 * @param WP_Post $post Page post.
	 * @return array
	 */
	private function format_page( $post ) {
		$product_ids = TFDC_Landing_Checkout::get_page_product_ids( $post->ID );
		$quantities  = TFDC_Landing_Checkout::get_page_quantities( $post->ID );
		$products    = array();

		foreach ( $product_ids as $product_id ) {
			$product = wc_get_product( $product_id );
			if ( ! $product ) {
				continue;
			}

			$products[] = array(
				'id'       => $product_id,
				'name'     => wp_strip_all_tags( $product->get_formatted_name() ),
				'quantity' => $quantities[ $product_id ] ?? 1,
				'image'    => $this->get_product_image_url( $product ),
			);
		}

		return array(
			'id'        => $post->ID,
			'title'     => get_the_title( $post ),
			'status'    => $post->post_status,
			'products'  => $products,
			'shortcode' => TFDC_Template_Library::build_checkout_shortcode( $product_ids ),
			'edit_url'  => get_edit_post_link( $post->ID, 'raw' ),
			'view_url'  => get_permalink( $post ),
		);
	}

	/**
	 * Get a product thumbnail URL, falling back to the parent product for variations.
	 *
	 * @param WC_Product $product Product object.
	 * @return string
	 */
	private function get_product_image_url( $product ) {
		$image_id = $product->get_image_id();

		if ( ! $image_id && $product->is_type( 'variation' ) ) {
			$parent = wc_get_product( $product->get_parent_id() );
			if ( $parent ) {
				$image_id = $parent->get_image_id();
			}
		}

		return $image_id ? wp_get_attachment_image_url( $image_id, 'thumbnail' ) : '';
	}
}
