<?php

/**
 * WDPOP_Template Class
 * Handles preset template library for Wing Popup plugin.
 */

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



class WDPOP_Template {

    /**
     * Directory path to preset files.
     */
    private string $presets_dir;

    /**
     * URL to presets directory (for preview images).
     */
    private string $presets_url;

    public function __construct() {
        $this->presets_dir = WDPOP_DIR . 'templates/presets/';
        $this->presets_url = WDPOP_URL . 'templates/presets/';

        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_assets' ] );
        add_action( 'admin_footer',          [ $this, 'render_modal_html' ] );
        add_action( 'wp_ajax_wdpop_get_presets', [ $this, 'ajax_get_presets' ] );
        add_action( 'wp_ajax_wdpop_use_preset',  [ $this, 'ajax_use_preset' ] );
        add_action( 'admin_head-edit.php', [ $this, 'load_insert_template_button' ] );
    }

    function load_insert_template_button() {
        $screen = get_current_screen();
        if ( ! $screen || $screen->post_type !== 'wdpop_template' ) {
            return;
        }

        $button = sprintf(
            '<a href="#" id="wdpop-open-library" class="button button-primary" style="margin-left:6px;margin-top:-10px;">%s</a>',
            esc_html__( '+ Insert Template', 'wing-popup' )
        );
        ?>
        <script>
            document.addEventListener('DOMContentLoaded', function () {
                const addNewBtn = document.querySelector('.page-title-action');
                if ( addNewBtn ) {
                    addNewBtn.insertAdjacentHTML('afterend', <?php echo wp_json_encode( $button ); ?>);
                }
            });
        </script>
        <?php
    }

    /* -----------------------------------------------------------------------
     * 1. Assets
     * -------------------------------------------------------------------- */

    public function enqueue_assets( string $hook ): void {
        if ( 'edit.php' !== $hook ) {
            return;
        }
        if ( ! isset( $_GET['post_type'] ) || 'wdpop_template' !== $_GET['post_type'] ) {
            return;
        }

        wp_enqueue_style( 'wdpop-template-library', WDPOP_URL . 'admin/css/template-library.css', [], '1.0.0' );

        wp_enqueue_script( 'wdpop-template-library', WDPOP_URL . 'admin/js/template-library.js', [ 'jquery' ], '1.0.0', true );

        wp_localize_script( 'wdpop-template-library', 'wdpopTemplates', [
            'ajaxUrl' => admin_url( 'admin-ajax.php' ),
            'nonce'   => wp_create_nonce( 'wdpop_template_nonce' ),
            'strings' => [
                'loading'     => __( 'Loading templates…', 'wing-popup' ),
                'error'       => __( 'Could not load templates. Please try again.', 'wing-popup' ),
                'useThis'     => __( 'Use This Template', 'wing-popup' ),
                'creating'    => __( 'Creating…', 'wing-popup' ),
                'noTemplates' => __( 'No preset templates found.', 'wing-popup' ),
            ],
        ] );
    }

    /* -----------------------------------------------------------------------
     * 2. "Insert Template" button
     * -------------------------------------------------------------------- */

    public function add_insert_template_button( array $views ): array {
        $button = sprintf(
            '<a href="#" id="wdpop-open-library" class="button button-primary" style="margin-left:6px;">%s</a>',
            esc_html__( '+ Insert Template', 'wing-popup' )
        );
        $views['wdpop_insert'] = $button;
        return $views;
    }

    /* -----------------------------------------------------------------------
     * 3. Modal HTML skeleton
     * -------------------------------------------------------------------- */

    public function render_modal_html(): void {
        $screen = get_current_screen();
        if ( ! $screen || 'edit-wdpop_template' !== $screen->id ) {
            return;
        }
        ?>
        <div id="wdpop-library-overlay" class="wdpop-overlay" style="display:none;" role="dialog" aria-modal="true" aria-labelledby="wdpop-library-title">
            <div class="wdpop-modal">

                <div class="wdpop-modal__header">
                    <h2 id="wdpop-library-title"><?php esc_html_e( 'Preset Template Library', 'wing-popup' ); ?></h2>
                    <button class="wdpop-modal__close" aria-label="<?php esc_attr_e( 'Close', 'wing-popup' ); ?>">&times;</button>
                </div>

                <div class="wdpop-modal__toolbar">
                    <input
                        type="search"
                        id="wdpop-search"
                        placeholder="<?php esc_attr_e( 'Search templates…', 'wing-popup' ); ?>"
                        autocomplete="off"
                    />
                </div>

                <div class="wdpop-modal__body">
                    <div id="wdpop-template-grid" class="wdpop-grid">
                        <p class="wdpop-loading"><?php esc_html_e( 'Loading templates…', 'wing-popup' ); ?></p>
                    </div>
                </div>

                <div class="wdpop-modal__footer">
                    <button class="button wdpop-modal__close-btn"><?php esc_html_e( 'Close', 'wing-popup' ); ?></button>
                </div>

            </div>
        </div>
        <?php
    }

    /* -----------------------------------------------------------------------
     * 4. Load presets from PHP file
     * -------------------------------------------------------------------- */

    private function get_presets(): array {
        $file = $this->presets_dir . 'presets.php';

        if ( ! file_exists( $file ) ) {
            return [];
        }

        $presets = require $file;

        return is_array( $presets ) ? $presets : [];
    }

    /* -----------------------------------------------------------------------
     * 5. AJAX — return preset list
     * -------------------------------------------------------------------- */

    public function ajax_get_presets(): void {
        check_ajax_referer( 'wdpop_template_nonce', 'nonce' );

        if ( ! current_user_can( 'edit_posts' ) ) {
            wp_send_json_error( [ 'message' => __( 'Permission denied.', 'wing-popup' ) ], 403 );
        }

        $presets = $this->get_presets();

        if ( empty( $presets ) ) {
            wp_send_json_error( [ 'message' => __( 'No preset templates found.', 'wing-popup' ) ] );
        }

        // Attach preview image URLs and strip the content key — JS doesn't need it
        $response = array_map( function( $preset ) {
            return [
                'slug'        => $preset['slug']        ?? '',
                'title'       => $preset['title']       ?? '',
                'description' => $preset['description'] ?? '',
                'preview_url' => ! empty( $preset['preview_image'] )
                                    ? esc_url( $this->presets_url . 'previews/' . $preset['preview_image'] )
                                    : '',
            ];
        }, $presets );

        wp_send_json_success( array_values( $response ) );
    }

    /* -----------------------------------------------------------------------
     * 6. AJAX — create post from preset and return edit URL
     * -------------------------------------------------------------------- */

    public function ajax_use_preset(): void {
        check_ajax_referer( 'wdpop_template_nonce', 'nonce' );

        if ( ! current_user_can( 'edit_posts' ) ) {
            wp_send_json_error( [ 'message' => __( 'Permission denied.', 'wing-popup' ) ], 403 );
        }

        $slug = isset( $_POST['slug'] ) ? sanitize_file_name( wp_unslash( $_POST['slug'] ) ) : '';

        if ( empty( $slug ) ) {
            wp_send_json_error( [ 'message' => __( 'No template slug provided.', 'wing-popup' ) ] );
        }

        $post_id = $this->create_post_from_preset( $slug );

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

        wp_send_json_success( [
            'post_id'  => $post_id,
            'edit_url' => get_edit_post_link( $post_id, 'raw' ),
        ] );
    }

    /* -----------------------------------------------------------------------
     * 7. Core — create a new wdpop_template post from a preset
     * -------------------------------------------------------------------- */
    private function create_post_from_preset( string $slug ): int|WP_Error {
        $presets = $this->get_presets();

        // Find the preset matching the requested slug
        $data = null;
        foreach ( $presets as $preset ) {
            if ( isset( $preset['slug'] ) && $preset['slug'] === $slug ) {
                $data = $preset;
                break;
            }
        }

        if ( ! $data ) {
            return new WP_Error( 'not_found', __( 'Preset template not found.', 'wing-popup' ) );
        }

        if ( empty( $data['content'] ) ) {
            return new WP_Error( 'invalid', __( 'Invalid preset data.', 'wing-popup' ) );
        }

        // Images are already resolved via PHP constants in presets.php — no replacement needed
        $post_id = wp_insert_post( [
            'post_title'   => ! empty( $data['title'] ) ? sanitize_text_field( $data['title'] ) : __( 'New Popup Template', 'wing-popup' ),
            // 'post_content' => $data['content'],
            'post_content' => wp_slash( $data['content'] ),
            'post_status'  => 'publish',
            'post_type'    => 'wdpop_template',
        ], true );

        return $post_id;
    }
}

// Instantiate
new WDPOP_Template();