<?php
/**
 * REST — Theme Builder header/footer documents.
 *
 * @package AuraBuilder
 */

declare(strict_types=1);

namespace AuraBuilder\REST;

use AuraBuilder\Theme\ThemeBuilder;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;

final class ThemePartsController {

	public function register( string $ns ): void {
		register_rest_route(
			$ns,
			'/theme-parts',
			array(
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'list_parts' ),
					'permission_callback' => array( $this, 'can_edit' ),
				),
			)
		);
		register_rest_route(
			$ns,
			'/theme-parts/(?P<type>header|footer|single)',
			array(
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_part' ),
					'permission_callback' => array( $this, 'can_edit' ),
				),
				array(
					'methods'             => WP_REST_Server::EDITABLE,
					'callback'            => array( $this, 'update_part' ),
					'permission_callback' => array( $this, 'can_edit' ),
				),
			)
		);
		register_rest_route(
			$ns,
			'/nav-menus',
			array(
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'nav_menus' ),
					'permission_callback' => array( $this, 'can_edit' ),
				),
			)
		);
	}

	/**
	 * Header/footer/single are site-wide theme chrome.
	 * Allow admins, theme editors, and page editors (same as EditorPage shell).
	 */
	public function can_edit(): bool {
		return \AuraBuilder\Support\Capabilities::can_edit_theme_parts();
	}

	public function list_parts(): WP_REST_Response {
		return new WP_REST_Response(
			array(
				'ok'    => true,
				'parts' => ThemeBuilder::get_all(),
			)
		);
	}

	public function get_part( WP_REST_Request $req ): WP_REST_Response {
		$type = ThemeBuilder::normalize_type( (string) $req['type'] );
		$part = ThemeBuilder::get_part( $type );
		$payload = array(
			'ok'       => true,
			'type'     => $type,
			'part'     => $part,
			'document' => $part['document'] ?? null,
			'nonce'    => wp_create_nonce( 'wp_rest' ),
		);
		// Single editor: real header/footer chrome like the page (Home) editor.
		if ( $type === 'single' ) {
			try {
				$payload['theme'] = ( new \AuraBuilder\Theme\ThemeChrome() )->parts();
			} catch ( \Throwable $e ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
				$payload['theme'] = array(
					'header'    => '',
					'footer'    => '',
					'hasHeader' => false,
					'hasFooter' => false,
					'styles'    => array( 'links' => array(), 'inline' => '' ),
					'homeUrl'   => home_url( '/' ),
				);
			}
		}
		return new WP_REST_Response( $payload );
	}

	/**
	 * @return WP_REST_Response|WP_Error
	 */
	public function update_part( WP_REST_Request $req ) {
		$type = ThemeBuilder::normalize_type( (string) $req['type'] );
		$body = $req->get_json_params();
		if ( ! is_array( $body ) ) {
			return new WP_Error( 'ab_invalid', 'Payload inválido', array( 'status' => 400 ) );
		}
		$current = ThemeBuilder::get_part( $type );
		// Merge: body.part or flat fields + document.
		$incoming = is_array( $body['part'] ?? null ) ? $body['part'] : $body;
		if ( isset( $body['document'] ) && is_array( $body['document'] ) ) {
			$incoming['document'] = $body['document'];
		}
		$merged = array_merge( $current, $incoming );
		$saved  = ThemeBuilder::save_part( $type, $merged );
		return new WP_REST_Response(
			array(
				'ok'       => true,
				'type'     => $type,
				'part'     => $saved,
				'document' => $saved['document'] ?? null,
				'nonce'    => wp_create_nonce( 'wp_rest' ),
			)
		);
	}

	public function nav_menus(): WP_REST_Response {
		$menus = wp_get_nav_menus();
		$out   = array();
		if ( is_array( $menus ) ) {
			foreach ( $menus as $m ) {
				$out[] = array(
					'id'    => (int) $m->term_id,
					'name'  => (string) $m->name,
					'slug'  => (string) $m->slug,
					'count' => (int) $m->count,
				);
			}
		}
		return new WP_REST_Response(
			array(
				'ok'    => true,
				'menus' => $out,
			)
		);
	}
}
