<?php
/**
 * 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() {
    check_ajax_referer( 'sifency_section_builder_nonce', 'nonce' );
    if ( ! current_user_can( 'edit_posts' ) ) {
        wp_send_json_error( [ '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( [ 'message' => 'Template title cannot be empty.' ] );
    }
    $post_data = [
        '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( [ 'message' => $post_id->get_error_message() ] );
    }
    
    update_post_meta($post_id, '_elementor_edit_mode', 'builder');

        $response_data = [];
        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' );