<?php
/**
 * Shois Chat Button — Template Custom Post Type
 *
 * Registers and manages the shcb_template CPT for storing
 * widget template configurations.
 *
 * @package ShoisChatButton
 */

// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class SHCB_Template_CPT
 *
 * Handles registration and helpers for the shcb_template CPT.
 */
class SHCB_Template_CPT {

	/**
	 * Post type slug.
	 *
	 * @var string
	 */
	const POST_TYPE = 'shcb_template';

	/**
	 * Meta key constants.
	 */
	const META_TYPE           = '_shcb_template_type';
	const META_PREVIEW_THUMB  = '_shcb_preview_thumb';
	const META_SCHEMA_VERSION = '_shcb_schema_version';
	const META_IS_DEFAULT     = '_shcb_is_default';

	/**
	 * Initialize hooks.
	 *
	 * @return void
	 */
	public static function init() {
		add_action( 'init', array( __CLASS__, 'register_post_type' ) );
		add_action( 'init', array( __CLASS__, 'register_meta_fields' ) );
	}

	/**
	 * Register the shcb_template custom post type.
	 *
	 * @return void
	 */
	public static function register_post_type() {
		$args = array(
			'labels'              => array(
				'name'          => esc_html__( 'Chat Templates', 'shois-chat-button' ),
				'singular_name' => esc_html__( 'Chat Template', 'shois-chat-button' ),
			),
			'public'              => false,
			'publicly_queryable'  => false,
			'show_ui'             => false,
			'show_in_menu'        => false,
			'show_in_rest'        => true,
			'rest_base'           => 'shcb-templates',
			'rest_namespace'      => SHCB_REST_NAMESPACE,
			'capability_type'     => 'post',
			'map_meta_cap'        => true,
			'supports'            => array( 'title', 'editor', 'custom-fields' ),
			'has_archive'         => false,
			'rewrite'             => false,
			'query_var'           => false,
			'can_export'          => true,
			'delete_with_user'    => false,
		);

		register_post_type( self::POST_TYPE, $args );
	}

	/**
	 * Register meta fields for REST API access.
	 *
	 * @return void
	 */
	public static function register_meta_fields() {
		$meta_fields = array(
			self::META_TYPE           => array(
				'type'    => 'string',
				'default' => 'bubble',
			),
			self::META_PREVIEW_THUMB  => array(
				'type'    => 'string',
				'default' => '',
			),
			self::META_SCHEMA_VERSION => array(
				'type'    => 'integer',
				'default' => SHCB_SCHEMA_VERSION,
			),
			self::META_IS_DEFAULT     => array(
				'type'    => 'boolean',
				'default' => false,
			),
		);

		foreach ( $meta_fields as $key => $config ) {
			register_post_meta(
				self::POST_TYPE,
				$key,
				array(
					'show_in_rest'      => true,
					'single'            => true,
					'type'              => $config['type'],
					'default'           => $config['default'],
					'sanitize_callback' => self::get_sanitize_callback( $config['type'] ),
					'auth_callback'     => function () {
						return current_user_can( 'manage_options' );
					},
				)
			);
		}
	}

	/**
	 * Get the appropriate sanitize callback for a meta field type.
	 *
	 * @param string $type The meta field type.
	 * @return callable
	 */
	private static function get_sanitize_callback( $type ) {
		switch ( $type ) {
			case 'integer':
				return 'absint';
			case 'boolean':
				return 'rest_sanitize_boolean';
			case 'string':
			default:
				return 'sanitize_text_field';
		}
	}

	/**
	 * Get the default template ID.
	 *
	 * @return int Template ID or 0.
	 */
	public static function get_default_template_id() {
		$settings = get_option( 'shcb_global_settings', array() );
		return isset( $settings['default_template_id'] ) ? absint( $settings['default_template_id'] ) : 0;
	}

	/**
	 * Get all published templates.
	 *
	 * @return array Array of WP_Post objects.
	 */
	public static function get_all_templates() {
		return get_posts(
			array(
				'post_type'      => self::POST_TYPE,
				'posts_per_page' => -1,
				'post_status'    => array( 'publish', 'draft' ),
				'orderby'        => 'date',
				'order'          => 'DESC',
			)
		);
	}
}
