<?php
// DESCRIPTION: REST API endpoints for suggesting column headers based on data source fields
// and writing those headers to row 1 of a Google Spreadsheet.

namespace SheetWise\Api;

use SheetWise\Admin\GoogleSheet;
use WP_REST_Server;

class SheetHeaders extends Swise_REST_Controller {

	/**
	 * Route name
	 *
	 * @since 2.0.0
	 *
	 * @var string
	 */
	protected $base = 'sheet-headers';

	/**
	 * Register routes
	 *
	 * @since 2.0.0
	 *
	 * @return void
	 */
	public function register_routes() {
		register_rest_route(
			$this->namespace,
			'/' . $this->base . '/suggest/(?P<hook>[a-zA-Z0-9_-]+)',
			[
				[
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => [ $this, 'get_suggestions' ],
					'permission_callback' => [ $this, 'permission_check' ],
				],
			]
		);

		register_rest_route(
			$this->namespace,
			'/' . $this->base . '/create',
			[
				[
					'methods'             => WP_REST_Server::CREATABLE,
					'callback'            => [ $this, 'create_headers' ],
					'permission_callback' => [ $this, 'permission_check' ],
				],
			]
		);
	}

	/**
	 * Get suggested column headers for a data source hook
	 *
	 * @since 2.0.0
	 *
	 * @param \WP_REST_Request $request
	 *
	 * @return \WP_REST_Response
	 */
	public function get_suggestions( $request ) {
		$hook    = sanitize_text_field( $request->get_param( 'hook' ) );
		$headers = swise_get_suggested_headers( $hook );

		if ( empty( $headers ) ) {
			return $this->error_response(
				new \WP_Error( 'no_headers', __( 'No field definitions found for this data source.', 'sheet-wise' ) )
			);
		}

		return rest_ensure_response( [
			'code'    => 200,
			'success' => true,
			'headers' => $headers,
		] );
	}

	/**
	 * Write column headers to row 1 of a Google Spreadsheet
	 *
	 * @since 2.0.0
	 *
	 * @param \WP_REST_Request $request
	 *
	 * @return \WP_REST_Response
	 */
	public function create_headers( $request ) {
		$body = json_decode( $request->get_body() );

		if ( ! $body || empty( $body->spreadsheet_id ) || empty( $body->headers ) ) {
			return $this->error_response(
				new \WP_Error( 'invalid_data', __( 'Spreadsheet ID and headers are required.', 'sheet-wise' ) )
			);
		}

		$spreadsheet_id = sanitize_text_field( $body->spreadsheet_id );
		$headers        = array_map( 'sanitize_text_field', (array) $body->headers );
		$sheet_title    = ! empty( $body->sheet_title ) ? sanitize_text_field( $body->sheet_title ) : 'Sheet1';

		$sheet  = new GoogleSheet( $spreadsheet_id );
		$result = $sheet->write_headers( $spreadsheet_id, $headers, $sheet_title );

		if ( ! $result ) {
			return $this->error_response(
				new \WP_Error( 'write_failed', __( 'Failed to write headers to the spreadsheet.', 'sheet-wise' ) )
			);
		}

		return rest_ensure_response( [
			'code'    => 200,
			'success' => true,
			'message' => __( 'Headers written to row 1 of your spreadsheet.', 'sheet-wise' ),
		] );
	}
}
