<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;  }
/**
 * AJAX handler for creating a new section template.
 *
 * This function handles the request from the admin JavaScript to create a new post
 * of the 'section_templates' CPT. It now returns the HTML for the new table row
 * when saving as a draft.
 */
function sifency_ajax_create_section_template() {
	if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( $_POST['nonce'], 'sifency_section_builder_nonce' ) ) {
		wp_send_json_error( array( 'message' => 'Security verification failed.' ) );
	}

	if ( ! current_user_can( 'edit_posts' ) ) {
		wp_send_json_error( array( 'message' => 'You do not have permission to do this.' ) );
	}
	$title           = isset( $_POST['title'] ) ? sanitize_text_field( wp_unslash( $_POST['title'] ) ) : '';
	$redirect_action = isset( $_POST['redirect_action'] ) ? sanitize_key( $_POST['redirect_action'] ) : 'draft';

	if ( empty( $title ) ) {
		wp_send_json_error( array( 'message' => 'Template title cannot be empty.' ) );
	}
	$post_data = array(
		'post_title'  => $title,
		'post_status' => 'draft',
		'post_type'   => 'section_templates',
	);

	$post_id = wp_insert_post( $post_data );

	if ( is_wp_error( $post_id ) ) {
		wp_send_json_error( array( 'message' => $post_id->get_error_message() ) );
	}

	update_post_meta( $post_id, '_elementor_edit_mode', 'builder' );

		$response_data = array();
	if ( 'edit' === $redirect_action ) {
		$response_data['redirect_url'] = get_admin_url() . 'post.php?post=' . $post_id . '&action=elementor';
	} else {
		$edit_url      = get_edit_post_link( $post_id, 'raw' );
		$elementor_url = get_admin_url() . 'post.php?post=' . $post_id . '&action=elementor';
		$delete_url    = get_delete_post_link( $post_id );
		$shortcode     = sprintf( '[section_template id="%d"]', $post_id );
		$new_row_html  = sprintf(
			'<tr>
                <td class="title column-title has-row-actions column-primary" data-colname="Title">
                    <strong><a class="row-title" href="%s" aria-label="%s">%s (Draft)</a></strong>
                    <div class="row-actions">
                        <span class="edit"><a href="%s">Edit</a> | </span>
                        <span class="edit_with_elementor"><a href="%s">Edit with Elementor</a> | </span>
                        <span class="trash"><a href="%s" class="submitdelete">Trash</a></span>
                    </div>
                </td>
                <td data-colname="Shortcode">
                    <div class="sifency-shortcode-wrapper">
                        <input type="text" readonly value="%s" class="sifency-shortcode-input">
                        <button class="button button-secondary sifency-copy-btn" title="Copy Shortcode">
                            <span class="dashicons dashicons-admin-page"></span>
                        </button>
                    </div>
                </td>
                <td data-colname="Date">%s</td>
            </tr>',
			esc_url( $edit_url ),
			esc_attr( $title ),
			esc_html( $title ),
			esc_url( $edit_url ),
			esc_url( $elementor_url ),
			esc_url( $delete_url ),
			esc_attr( $shortcode ),
			esc_html( get_the_date( '', $post_id ) )
		);

		$response_data['new_row_html'] = $new_row_html;
	}

	wp_send_json_success( $response_data );
}
add_action( 'wp_ajax_sifency_create_section_template', 'sifency_ajax_create_section_template' );

/**
 * AJAX: update section template title, slug, and publish status.
 */
function sifency_ajax_update_section_template_details() {
	if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'sifency_section_builder_nonce' ) ) {
		wp_send_json_error( array( 'message' => __( 'Security verification failed.', 'sifency-addons' ) ) );
	}

	$template_id = isset( $_POST['template_id'] ) ? absint( $_POST['template_id'] ) : 0;
	$title       = isset( $_POST['title'] ) ? sanitize_text_field( wp_unslash( $_POST['title'] ) ) : '';
	$slug        = isset( $_POST['slug'] ) ? sanitize_title( wp_unslash( $_POST['slug'] ) ) : '';
	$post_status = isset( $_POST['post_status'] ) ? sanitize_key( wp_unslash( $_POST['post_status'] ) ) : '';

	$result = sifency_addons_update_template_inline_meta(
		$template_id,
		$title,
		$slug,
		$post_status,
		'section_templates'
	);

	if ( is_wp_error( $result ) ) {
		wp_send_json_error( array( 'message' => $result->get_error_message() ) );
	}

	wp_send_json_success(
		array_merge(
			array( 'message' => __( 'Section updated.', 'sifency-addons' ) ),
			$result
		)
	);
}
add_action( 'wp_ajax_sifency_update_section_template_details', 'sifency_ajax_update_section_template_details' );
