<?php
/**
 * Shared inline edit (title, slug, status) for template list tables.
 *
 * @package Sifency_Addons
 */

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

/**
 * Allowed publish statuses for inline edit tooltips.
 *
 * @return array<string, string>
 */
function sifency_addons_get_template_inline_status_options(): array {
	return array(
		'publish' => __( 'Published', 'sifency-addons' ),
		'draft'   => __( 'Draft', 'sifency-addons' ),
		'pending' => __( 'Pending Review', 'sifency-addons' ),
	);
}

/**
 * Update template post title, slug, and status.
 *
 * @param int    $post_id           Post ID.
 * @param string $title             Post title.
 * @param string $slug              Post slug.
 * @param string $post_status       Post status.
 * @param string $expected_post_type Expected post type.
 * @return array{title: string, slug: string, status: string, status_label: string}|WP_Error
 */
function sifency_addons_update_template_inline_meta( $post_id, $title, $slug, $post_status, $expected_post_type = null ) {
	$post_id      = absint( $post_id );
	$current_type = get_post_type( $post_id );

	if ( ! $post_id || ! $current_type ) {
		return new WP_Error( 'invalid_post', __( 'Invalid post ID.', 'sifency-addons' ) );
	}

	if ( null !== $expected_post_type && $expected_post_type !== $current_type ) {
		return new WP_Error( 'invalid_post', __( 'Invalid template ID.', 'sifency-addons' ) );
	}

	$disallowed_types = array( 'attachment', 'revision', 'nav_menu_item', 'custom_css', 'customize_changeset' );
	if ( in_array( $current_type, $disallowed_types, true ) ) {
		return new WP_Error( 'invalid_post', __( 'This post type cannot be edited here.', 'sifency-addons' ) );
	}

	if ( ! current_user_can( 'edit_post', $post_id ) ) {
		return new WP_Error( 'permission', __( 'Permission denied.', 'sifency-addons' ) );
	}

	if ( '' === $title ) {
		return new WP_Error( 'empty_title', __( 'Title cannot be empty.', 'sifency-addons' ) );
	}

	$post = get_post( $post_id );
	if ( ! $post ) {
		return new WP_Error( 'not_found', __( 'Template not found.', 'sifency-addons' ) );
	}

	$allowed_statuses = array_keys( sifency_addons_get_template_inline_status_options() );
	if ( ! in_array( $post_status, $allowed_statuses, true ) ) {
		return new WP_Error( 'invalid_status', __( 'Invalid publish status.', 'sifency-addons' ) );
	}

	if ( 'publish' === $post_status && ! current_user_can( 'publish_post', $post_id ) ) {
		return new WP_Error( 'publish_permission', __( 'You cannot publish this template.', 'sifency-addons' ) );
	}

	if ( '' === $slug ) {
		$slug = sanitize_title( $title );
	}

	$slug = wp_unique_post_slug( $slug, $post_id, $post_status, $post->post_type, (int) $post->post_parent );

	$updated = wp_update_post(
		array(
			'ID'          => $post_id,
			'post_title'  => $title,
			'post_name'   => $slug,
			'post_status' => $post_status,
		),
		true
	);

	if ( is_wp_error( $updated ) ) {
		return $updated;
	}

	$status_options = sifency_addons_get_template_inline_status_options();
	$final_status   = get_post_status( $post_id );

	return array(
		'title'        => get_the_title( $post_id ),
		'slug'         => get_post_field( 'post_name', $post_id ),
		'status'       => $final_status,
		'status_label' => $status_options[ $final_status ] ?? ucfirst( (string) $final_status ),
	);
}

/**
 * Render status badge for list table column.
 *
 * @param int $post_id Post ID.
 */
function sifency_addons_render_template_status_badge( int $post_id ): void {
	$post_status       = get_post_status( $post_id );
	$status_options    = sifency_addons_get_template_inline_status_options();
	$post_status_label = $status_options[ $post_status ] ?? ucfirst( (string) $post_status );
	$note_text         = esc_html__( 'This template is not published.', 'sifency-addons' );
	$span_attributes   = '';

	if ( in_array( $post_status, array( 'draft', 'pending' ), true ) ) {
		$span_attributes = ' data-tooltip="' . esc_attr( $note_text ) . '"';
	}

	printf(
		'<span class="sifency-status-label sifency-template-status-display" data-status="%1$s"%2$s>%3$s</span>',
		esc_attr( $post_status ),
		wp_kses_post( $span_attributes ),
		esc_html( $post_status_label )
	);
}

/**
 * Render inline edit UI (title view + tooltip with title, slug, status).
 *
 * @param int   $post_id Post ID.
 * @param array $args {
 *     @type bool   $editable        Whether to show edit UI (false for trash tab).
 *     @type string $variant         `default` or `cpt-card`.
 *     @type string $title_fallback  Title when post has no title (cpt-card).
 * }
 */
function sifency_addons_render_template_inline_edit( int $post_id, array $args = array() ): void {
	$args = wp_parse_args(
		$args,
		array(
			'editable'       => true,
			'variant'        => 'default',
			'title_fallback' => '',
		)
	);

	$post_slug       = get_post_field( 'post_name', $post_id );
	$post_status     = get_post_status( $post_id );
	$status_options  = sifency_addons_get_template_inline_status_options();
	$field_id_prefix = 'sifency-template-' . $post_id;
	$display_title   = get_the_title( $post_id );

	if ( '' === $display_title && '' !== $args['title_fallback'] ) {
		$display_title = $args['title_fallback'];
	}

	$wrap_class = 'sifency-template-inline-edit';
	if ( 'cpt-card' === $args['variant'] ) {
		$wrap_class .= ' sifency-template-inline-edit--cpt-card';
	}

	if ( ! $args['editable'] ) {
		echo '<strong class="table-list-item-title">' . esc_html( $display_title ) . '</strong>';
		return;
	}
	?>
	<div
		class="<?php echo esc_attr( $wrap_class ); ?>"
		data-template-id="<?php echo esc_attr( $post_id ); ?>"
		data-slug="<?php echo esc_attr( $post_slug ); ?>"
		data-status="<?php echo esc_attr( $post_status ); ?>"
	>
		<div class="sifency-template-meta-view">
			<strong class="table-list-item-title sifency-template-title-display"><?php echo esc_html( $display_title ); ?></strong>
			<button type="button" class="button-link sifency-edit-template-meta sifency-admin-btn text_underline_animation">
				<span><?php esc_html_e( 'Edit', 'sifency-addons' ); ?></span>
			</button>
		</div>
		<div class="sifency-template-meta-tooltip" hidden>
			<div class="sifency-template-meta-tooltip-card" role="dialog" aria-label="<?php esc_attr_e( 'Edit template', 'sifency-addons' ); ?>">
				<span class="sifency-template-meta-tooltip-arrow" aria-hidden="true"></span>
				<button type="button" class="sifency-tooltip-close" aria-label="<?php esc_attr_e( 'Close', 'sifency-addons' ); ?>">&times;</button>
				<div class="sifency-tooltip-field">
					<label for="<?php echo esc_attr( $field_id_prefix ); ?>-title">
						<?php esc_html_e( 'Title', 'sifency-addons' ); ?>
					</label>
					<input
						type="text"
						id="<?php echo esc_attr( $field_id_prefix ); ?>-title"
						class="sifency-template-title-input"
						value="<?php echo esc_attr( get_the_title( $post_id ) ); ?>"
						autocomplete="off"
					/>
				</div>
				<div class="sifency-tooltip-field">
					<label for="<?php echo esc_attr( $field_id_prefix ); ?>-slug">
						<?php esc_html_e( 'Slug', 'sifency-addons' ); ?>
					</label>
					<div class="sifency-template-slug-row">
						<span class="sifency-slug-prefix" aria-hidden="true">/</span>
						<input
							type="text"
							id="<?php echo esc_attr( $field_id_prefix ); ?>-slug"
							class="sifency-template-slug-input"
							value="<?php echo esc_attr( $post_slug ); ?>"
							autocomplete="off"
							spellcheck="false"
						/>
					</div>
				</div>
				<div class="sifency-tooltip-field">
					<label for="<?php echo esc_attr( $field_id_prefix ); ?>-status">
						<?php esc_html_e( 'Status', 'sifency-addons' ); ?>
					</label>
					<select id="<?php echo esc_attr( $field_id_prefix ); ?>-status" class="sifency-template-status-input">
						<?php foreach ( $status_options as $status_key => $status_label ) : ?>
							<option value="<?php echo esc_attr( $status_key ); ?>" <?php selected( $post_status, $status_key ); ?>>
								<?php echo esc_html( $status_label ); ?>
							</option>
						<?php endforeach; ?>
					</select>
				</div>
				<div class="sifency-template-tooltip-footer">
					<button type="button" class="button sifency-save-template-meta sifency-admin-btn">
						<?php esc_html_e( 'Save', 'sifency-addons' ); ?>
					</button>
					<span class="sifency-inline-save-feedback" aria-live="polite"></span>
				</div>
			</div>
		</div>
	</div>
	<?php
}

/**
 * Enqueue shared inline-edit script and styles.
 *
 * @param string $ajax_action  WP AJAX action name.
 * @param string $nonce_action Nonce action name.
 */
function sifency_addons_enqueue_template_inline_edit_assets( string $ajax_action, string $nonce_action ): void {
	if ( defined( 'SIFENCY_TB_URL' ) ) {
		wp_enqueue_style(
			'sifency-addons-admin-tb',
			SIFENCY_TB_URL . 'assets/css/admin.css',
			array(),
			defined( 'SIFENCY_TB_VERSION' ) ? SIFENCY_TB_VERSION : SIFENCY_ADDONS_VERSION
		);
	}

	wp_enqueue_script(
		'sifency-template-inline-edit',
		SIFENCY_ADDONS_URL . 'assets/js/admin/template-inline-edit.js',
		array( 'jquery' ),
		SIFENCY_ADDONS_VERSION,
		true
	);

	$status_options = sifency_addons_get_template_inline_status_options();

	wp_localize_script(
		'sifency-template-inline-edit',
		'sifencyTemplateInlineEdit',
		array(
			'ajaxUrl'      => admin_url( 'admin-ajax.php' ),
			'nonce'        => wp_create_nonce( $nonce_action ),
			'action'       => $ajax_action,
			'statusLabels' => $status_options,
			'draftTooltip' => __( 'This template is not published.', 'sifency-addons' ),
			'i18n'         => array(
				'emptyTitle' => __( 'Please enter a title.', 'sifency-addons' ),
				'saving'     => __( 'Saving...', 'sifency-addons' ),
			),
		)
	);
}
