<?php
/**
 * Settings Controller for Warranty Cart Admin REST API
 *
 * Handles settings and checkout fields REST API operations.
 *
 * @package WarrantyCart
 */

namespace WarrantyCart\REST\Controllers;

use WarrantyCart\REST\BaseController;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;

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

/**
 * SettingsController class
 */
class SettingsController extends BaseController {

	/**
	 * Constructor
	 */
	public function __construct() {
		$this->rest_base = 'admin';
	}

	/**
	 * Register routes
	 */
	public function register_routes(): void {
		// Settings endpoints
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/settings',
			array(
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_settings' ),
					'permission_callback' => array( $this, 'check_admin_permission' ),
				),
				array(
					'methods'             => WP_REST_Server::EDITABLE,
					'callback'            => array( $this, 'update_settings' ),
					'permission_callback' => array( $this, 'check_admin_permission' ),
					'args'                => $this->get_settings_args(),
				),
			)
		);

		// Checkout fields endpoints
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/checkout-fields',
			array(
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_checkout_fields' ),
					'permission_callback' => array( $this, 'check_admin_permission' ),
				),
				array(
					'methods'             => WP_REST_Server::EDITABLE,
					'callback'            => array( $this, 'update_checkout_fields' ),
					'permission_callback' => array( $this, 'check_admin_permission' ),
					'args'                => $this->get_checkout_fields_args(),
				),
			)
		);
	}

	/**
	 * Get settings endpoint arguments.
	 *
	 * @return array
	 */
	private function get_settings_args(): array {
		return array(
			'enable_pdf_certificates'        => array(
				'required'          => false,
				'type'              => 'boolean',
				'description'       => __( 'Enable PDF certificates.', 'warranty-cart' ),
				'sanitize_callback' => 'wp_validate_boolean',
			),
			'enable_email_notifications'     => array(
				'required'          => false,
				'type'              => 'boolean',
				'description'       => __( 'Enable email notifications.', 'warranty-cart' ),
				'sanitize_callback' => 'wp_validate_boolean',
			),
			'default_warranty_cart_duration' => array(
				'required'          => false,
				'type'              => 'integer',
				'description'       => __( 'Default warranty duration.', 'warranty-cart' ),
				'sanitize_callback' => 'absint',
				'validate_callback' => 'rest_validate_request_arg',
				'minimum'           => 1,
			),
			'default_warranty_unit'          => array(
				'required'          => false,
				'type'              => 'string',
				'enum'              => array( 'days', 'months', 'years' ),
				'description'       => __( 'Default warranty duration unit.', 'warranty-cart' ),
				'sanitize_callback' => 'sanitize_text_field',
			),
			'enable_guest_checkout'          => array(
				'required'          => false,
				'type'              => 'boolean',
				'description'       => __( 'Enable guest checkout.', 'warranty-cart' ),
				'sanitize_callback' => 'wp_validate_boolean',
			),
			'require_warranty_terms'         => array(
				'required'          => false,
				'type'              => 'boolean',
				'description'       => __( 'Require warranty terms acceptance.', 'warranty-cart' ),
				'sanitize_callback' => 'wp_validate_boolean',
			),
			'require_billing_phone'          => array(
				'required'          => false,
				'type'              => 'boolean',
				'description'       => __( 'Require phone number in billing address.', 'warranty-cart' ),
				'sanitize_callback' => 'wp_validate_boolean',
			),
			'max_file_size'                  => array(
				'required'          => false,
				'type'              => 'integer',
				'description'       => __( 'Maximum file size in MB.', 'warranty-cart' ),
				'sanitize_callback' => 'absint',
				'validate_callback' => 'rest_validate_request_arg',
				'minimum'           => 1,
				'maximum'           => 50,
			),
			'allowed_file_types'             => array(
				'required'          => false,
				'type'              => 'string',
				'description'       => __( 'Comma-separated allowed file types.', 'warranty-cart' ),
				'sanitize_callback' => 'sanitize_text_field',
			),
		);
	}

	/**
	 * Get checkout fields endpoint arguments.
	 *
	 * @return array
	 */
	private function get_checkout_fields_args(): array {
		return array(
			'fields' => array(
				'required'          => true,
				'type'              => 'array',
				'description'       => __( 'Array of checkout field configurations.', 'warranty-cart' ),
				'validate_callback' => array( $this, 'validate_checkout_fields' ),
				'items'             => array(
					'type'       => 'object',
					'properties' => array(
						'id'          => array( 'type' => 'string' ),
						'label'       => array( 'type' => 'string' ),
						'type'        => array(
							'type' => 'string',
							'enum' => array( 'text', 'email', 'number', 'textarea', 'select', 'checkbox', 'radio' ),
						),
						'placeholder' => array( 'type' => 'string' ),
						'required'    => array( 'type' => 'boolean' ),
						'options'     => array(
							'type'  => 'array',
							'items' => array( 'type' => 'string' ),
						),
						'order'       => array( 'type' => 'integer' ),
						'enabled'     => array( 'type' => 'boolean' ),
					),
				),
			),
		);
	}

	/**
	 * Get plugin settings.
	 *
	 * @param WP_REST_Request $request REST request object.
	 *
	 * @return WP_REST_Response
	 */
	public function get_settings( WP_REST_Request $request ): WP_REST_Response {
		$settings = array(
			'enable_pdf_certificates'        => (bool) \get_option( 'warranty_enable_pdf_certificates', true ),
			'enable_email_notifications'     => (bool) \get_option( 'warranty_enable_email_notifications', true ),
			'default_warranty_cart_duration' => (int) \get_option( 'warranty_cart_default_duration', 1 ),
			'default_warranty_unit'          => \get_option( 'warranty_cart_default_unit', 'years' ),
			'enable_guest_checkout'          => (bool) \get_option( 'warranty_guest_checkout', false ),
			'require_warranty_terms'         => (bool) \get_option( 'warranty_cart_require_terms', true ),
			'require_billing_phone'          => (bool) \get_option( 'warranty_cart_require_billing_phone', false ),
			'max_file_size'                  => (int) \get_option( 'warranty_max_file_size', 5 ),
			'allowed_file_types'             => \get_option( 'warranty_allowed_file_types', 'pdf,jpg,jpeg,png' ),
		);

		return $this->success_response( $settings );
	}

	/**
	 * Update plugin settings.
	 *
	 * @param WP_REST_Request $request REST request object.
	 *
	 * @return WP_REST_Response
	 */
	public function update_settings( WP_REST_Request $request ): WP_REST_Response {
		$settings       = array();
		$option_mapping = array(
			'enable_pdf_certificates'        => 'warranty_enable_pdf_certificates',
			'enable_email_notifications'     => 'warranty_enable_email_notifications',
			'default_warranty_cart_duration' => 'warranty_cart_default_duration',
			'default_warranty_unit'          => 'warranty_cart_default_unit',
			'enable_guest_checkout'          => 'warranty_guest_checkout',
			'require_warranty_terms'         => 'warranty_cart_require_terms',
			'require_billing_phone'          => 'warranty_cart_require_billing_phone',
			'max_file_size'                  => 'warranty_max_file_size',
			'allowed_file_types'             => 'warranty_allowed_file_types',
		);

		foreach ( $option_mapping as $field => $option_key ) {
			$value = $request->get_param( $field );
			if ( null !== $value ) {
				$settings[ $field ] = $value;
				update_option( $option_key, $value );
			}
		}

		return $this->success_response(
			array(
				'message'  => __( 'Settings updated successfully.', 'warranty-cart' ),
				'settings' => $settings,
			)
		);
	}

	/**
	 * Get checkout fields configuration.
	 *
	 * @param WP_REST_Request $request REST request object.
	 *
	 * @return WP_REST_Response
	 */
	public function get_checkout_fields( WP_REST_Request $request ): WP_REST_Response {
		$fields = get_option( 'warranty_checkout_fields', array() );

		// If no fields are saved, return default fields
		if ( empty( $fields ) ) {
			$fields = $this->get_default_checkout_fields();
			update_option( 'warranty_checkout_fields', $fields );
		}

		return $this->success_response( array( 'fields' => $fields ) );
	}

	/**
	 * Update checkout fields configuration.
	 *
	 * @param WP_REST_Request $request REST request object.
	 *
	 * @return WP_REST_Response|WP_Error
	 */
	public function update_checkout_fields( WP_REST_Request $request ) {
		$fields = $request->get_param( 'fields' );

		if ( ! is_array( $fields ) ) {
			return $this->error_response( __( 'Invalid fields data.', 'warranty-cart' ), 400 );
		}

		// Validate and sanitize fields
		$validated_fields = array();
		foreach ( $fields as $field ) {
			if ( ! $this->validate_checkout_field( $field ) ) {
				return $this->error_response( __( 'Invalid field data.', 'warranty-cart' ), 400 );
			}

			$validated_fields[] = $this->sanitize_checkout_field( $field );
		}

		// Sort fields by order
		usort(
			$validated_fields,
			function ( $a, $b ) {
				return $a['order'] <=> $b['order'];
			}
		);

		// Update the option
		update_option( 'warranty_checkout_fields', $validated_fields );

		return $this->success_response(
			array(
				'message' => __( 'Checkout fields updated successfully.', 'warranty-cart' ),
				'fields'  => $validated_fields,
			)
		);
	}

	/**
	 * Validate checkout fields array.
	 *
	 * @param array $fields Fields to validate.
	 *
	 * @return bool
	 */
	public function validate_checkout_fields( $fields ): bool {
		if ( ! is_array( $fields ) ) {
			return false;
		}

		foreach ( $fields as $field ) {
			if ( ! $this->validate_checkout_field( $field ) ) {
				return false;
			}
		}

		return true;
	}

	/**
	 * Validate a single checkout field.
	 *
	 * @param mixed $field Field to validate.
	 *
	 * @return bool
	 */
	private function validate_checkout_field( $field ): bool {
		if ( ! is_array( $field ) ) {
			return false;
		}

		$required_keys = array( 'id', 'label', 'type', 'required', 'order', 'enabled' );
		foreach ( $required_keys as $key ) {
			if ( ! array_key_exists( $key, $field ) ) {
				return false;
			}
		}

		// Validate field type
		$valid_types = array( 'text', 'email', 'number', 'textarea', 'select', 'checkbox', 'radio' );
		if ( ! in_array( $field['type'], $valid_types, true ) ) {
			return false;
		}

		// Validate options for select, checkbox, radio
		if ( in_array( $field['type'], array( 'select', 'checkbox', 'radio' ), true ) ) {
			if ( ! isset( $field['options'] ) || ! is_array( $field['options'] ) ) {
				return false;
			}
		}

		return true;
	}

	/**
	 * Sanitize a checkout field.
	 *
	 * @param mixed $field Field to sanitize.
	 *
	 * @return array
	 */
	private function sanitize_checkout_field( $field ): array {
		return array(
			'id'          => sanitize_key( $field['id'] ),
			'label'       => sanitize_text_field( $field['label'] ),
			'type'        => sanitize_text_field( $field['type'] ),
			'placeholder' => isset( $field['placeholder'] ) ? sanitize_text_field( $field['placeholder'] ) : '',
			'required'    => (bool) $field['required'],
			'options'     => isset( $field['options'] ) && is_array( $field['options'] )
				? array_map( 'sanitize_text_field', $field['options'] )
				: array(),
			'order'       => absint( $field['order'] ),
			'enabled'     => (bool) $field['enabled'],
		);
	}

	/**
	 * Get default checkout fields configuration.
	 *
	 * @return array
	 */
	private function get_default_checkout_fields(): array {
		return array(
			array(
				'id'          => 'civic_number',
				'label'       => __( 'N. Civic', 'warranty-cart' ),
				'type'        => 'text',
				'placeholder' => __( 'N. Civic', 'warranty-cart' ),
				'required'    => true,
				'order'       => 4,
				'enabled'     => true,
			),
			array(
				'id'          => 'car_brand',
				'label'       => __( 'Car Brand', 'warranty-cart' ),
				'type'        => 'text',
				'placeholder' => __( 'Car brand', 'warranty-cart' ),
				'required'    => true,
				'order'       => 10,
				'enabled'     => true,
			),
			array(
				'id'          => 'car_model',
				'label'       => __( 'Car Model', 'warranty-cart' ),
				'type'        => 'text',
				'placeholder' => __( 'Car model', 'warranty-cart' ),
				'required'    => true,
				'order'       => 11,
				'enabled'     => true,
			),
			array(
				'id'          => 'kilometers',
				'label'       => __( 'Km', 'warranty-cart' ),
				'type'        => 'number',
				'placeholder' => __( 'Km', 'warranty-cart' ),
				'required'    => true,
				'order'       => 12,
				'enabled'     => true,
			),
			array(
				'id'          => 'license_plate',
				'label'       => __( 'License Plate', 'warranty-cart' ),
				'type'        => 'text',
				'placeholder' => __( 'License Plate', 'warranty-cart' ),
				'required'    => true,
				'order'       => 13,
				'enabled'     => true,
			),
			array(
				'id'          => 'frame_number',
				'label'       => __( 'N. Frame', 'warranty-cart' ),
				'type'        => 'text',
				'placeholder' => __( 'N. Frame', 'warranty-cart' ),
				'required'    => true,
				'order'       => 14,
				'enabled'     => true,
			),
			array(
				'id'          => 'first_registration',
				'label'       => __( '1st Registration', 'warranty-cart' ),
				'type'        => 'text',
				'placeholder' => __( '1st Registration', 'warranty-cart' ),
				'required'    => true,
				'order'       => 15,
				'enabled'     => true,
			),
		);
	}
}
