<?php
if ( ! defined( 'ABSPATH' ) ) exit;

class Sifency_Addons_Prebuild_Website {

    /**
     * Renders the entire dynamic theme library page with filtering functionality.
     */
    public function render() {

        $is_premium_unlocked = Sifency_Addons_Theme_Builder_Master::sifency_addons_is_legal();

        $themes = [
            [
                'name' => 'Architecture Design',
                'image' => 'https://sifency-addons-images.vercel.app/prebuild/anglo-architecture.png',
                'live' => 'https://sifency.com/anglo',
                'buy' => 'https://sifency-addons.sifency.com/',
                'category' => 'Business',
                'is_pro' => true,
                'required_plugins' => ['elementor/elementor.php', 'woocommerce/woocommerce.php'],
                'demo_file' => 'anglo_demo.json',
            ],
            [
                'name' => 'Interior Design',
                'image' => 'https://sifency-addons-images.vercel.app/prebuild/anglo-interior.png',
                'live' => 'https://sifency.com/anglo',
                'buy' => 'https://sifency-addons.sifency.com/',
                'category' => 'Business',
                'is_pro' => true,
                'required_plugins' => ['elementor/elementor.php', 'woocommerce/woocommerce.php'],
                'demo_file' => 'anglo_demo.json',
            ],
            [
                'name' => 'Arhitecture & Interior Design',
                'image' => 'https://sifency-addons-images.vercel.app/prebuild/anglo-architecture-and-interior.png',
                'live' => 'https://sifency.com/anglo/interior',
                'buy' => 'https://sifency-addons.sifency.com/',
                'category' => 'Business',
                'is_pro' => true,
                'required_plugins' => ['elementor/elementor.php', 'woocommerce/woocommerce.php'],
                'demo_file' => 'anglo_demo.json',
            ],
            [
                'name' => 'Digital Agency',
                'image' => 'https://sifency-addons-images.vercel.app/prebuild/portnew-digital-agency.png',
                'live' => 'https://sifency.com/portnew',
                'buy' => 'https://sifency-addons.sifency.com/',
                'category' => 'Creative',
                'is_pro' => true,
                'required_plugins' => ['elementor/elementor.php'],
                'demo_file' => 'portnew_demo.json',
            ],
            [
                'name' => 'Portfolio Showcase',
                'image' => 'https://sifency-addons-images.vercel.app/prebuild/portnew-personal-portfolio.png',
                'live' => 'https://sifency.com/portnew/personal-portfolio',
                'buy' => 'https://sifency-addons.sifency.com/',
                'category' => 'Creative',
                'is_pro' => true,
                'required_plugins' => ['elementor/elementor.php'],
                'demo_file' => 'portnew_demo.json',
            ],
        ];
        
        $categories = array_unique( wp_list_pluck( $themes, 'category' ) );
        array_unshift( $categories, 'All' );
        
        ?>

        <div class="sifency-dashboard-layout">
            
            <div class="sifency-dashboard-nav">
                <?php foreach ( $categories as $index => $cat ) : ?>
                    <button class="sifency-nav-item sifency-admin-btn <?php echo ( 0 === $index ) ? 'active' : ''; ?>" data-filter="<?php echo esc_attr( strtolower( $cat ) ); ?>">
                        <?php echo esc_html( $cat ); ?>
                    </button>
                <?php endforeach; ?>
            </div>

            <div class="sifency-theme-grid">
                <?php foreach ( $themes as $theme ) : 
                    $pro_label = $theme['is_pro'] ? '<span class="sifency-pro-badge sifency-theme-pro-badge">Pro</span>' : '';

                    // Determine button output
                    if ( $theme['is_pro'] && ! $is_premium_unlocked ) {
                        $button_html = sprintf(
                            '<a href="%s" target="_blank" class="sifency-upgrade-btn sifency-admin-btn">%s</a>',
                            esc_url( $theme['buy'] ),
                            esc_html__( 'Upgrade to Pro', 'sifency-addons' )
                        );
                    } else {

                        $button_html = sprintf(
                            '<button class="sifency-import-btn sifency-admin-btn button primary-button" data-theme-name="%s" data-plugins=\'%s\' data-demo-file="%s">%s</button>',
                            esc_attr( $theme['name'] ),
                            esc_attr( wp_json_encode( $theme['required_plugins'] ) ),
                            esc_attr( $theme['demo_file'] ),
                            esc_html__( 'Import', 'sifency-addons' )
                        );
                    }
                    ?>
                    <div class="sifency-theme-card" data-category="<?php echo esc_attr( strtolower( $theme['category'] ) ); ?>">
                        <div class="sifency-theme-thumb">
                            <img src="<?php echo esc_url( $theme['image'] ); ?>" alt="<?php echo esc_attr( $theme['name'] ); ?>">
                            <div class="sifency-theme-hover">
                                <a href="<?php echo esc_url( $theme['live'] ); ?>" target="_blank" class="sifency-admin-btn live-link-btn"><span><?php esc_html_e( 'Live Preview', 'sifency-addons' ); ?></span></a>
                            </div>
                            <?php echo wp_kses_post($pro_label); ?>
                        </div>
                        <div class="sifency-theme-info">
                            <h3 class="sifency-theme-title"><?php echo esc_html( $theme['name'] ); ?></h3>
                            <?php echo wp_kses_post( $button_html ); // Output the determined button ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
            
            <div id="sifency-import-status" style="display:none; margin-top: 20px; padding: 10px; border: 1px solid #ccc;"></div>

        </div>

        <?php
        $this->enqueue_scripts(); // Call a method to enqueue necessary JS/CSS
    }

/**
 * Handles the AJAX request to install and activate a required plugin.
 */
public function install_plugin() {
    if ( ! current_user_can( 'install_plugins' ) ) {
        wp_send_json_error( [ 'message' => esc_html__( 'Permission denied. You cannot install plugins.', 'sifency-addons' ) ] );
    }
    check_ajax_referer( 'sifency_demo_import_nonce', 'nonce' );
    if ( empty( $_POST['plugin_slug'] ) ) {
        wp_send_json_error( [ 'message' => esc_html__( 'Plugin slug is missing.', 'sifency-addons' ) ] );
    }
    
    $plugin_path = sanitize_text_field( $_POST['plugin_slug'] );
    $plugin_slug = dirname( $plugin_path );

    if ( is_plugin_active( $plugin_path ) ) {
        wp_send_json_success( [
            /* translators: %s: plugin slug */
            'message' => sprintf( esc_html__( 'Plugin %s is already active.', 'sifency-addons' ), $plugin_slug ),
            'plugin_slug' => $plugin_path,
        ] );
    }

    include_once ABSPATH . 'wp-admin/includes/plugin.php';
    include_once ABSPATH . 'wp-admin/includes/file.php';
    include_once ABSPATH . 'wp-admin/includes/plugin-install.php';
    include_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';

    if ( ! file_exists( WP_PLUGIN_DIR . '/' . $plugin_path ) ) {
        
        $api = plugins_api( 'plugin_information', [ 'slug' => $plugin_slug, 'fields' => [ 'sections' => false ] ] );

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

        $upgrader = new Plugin_Upgrader( new Automatic_Upgrader_Skin( [ 'type' => 'plugin', 'title' => 'Install Plugin' ] ) );
        $install_result = $upgrader->install( $api->download_link );
        
        if ( is_wp_error( $install_result ) || ! $install_result ) {
            $error = is_wp_error( $install_result ) ? $install_result->get_error_message() : 'Installation failed.';

            wp_send_json_error( [
                'message' => sprintf(
                    /* translators: 1: plugin slug (e.g. "akismet"), 2: error message */
                    esc_html__( 'Failed to install plugin: %1$s. Error: %2$s', 'sifency-addons' ),
                    $plugin_slug,
                    $error
                ),
            ] );
        }

    }

    $activate_result = activate_plugin( $plugin_path );

    if ( is_wp_error( $activate_result ) ) {
        wp_send_json_error( [
            'message' => sprintf(
                /* translators: 1: plugin slug (e.g. "akismet"), 2: error message */
                esc_html__( 'Failed to activate plugin: %1$s. Error: %2$s', 'sifency-addons' ),
                $plugin_slug,
                $activate_result->get_error_message()
            ),
        ] );
    }

    wp_send_json_success( [
        /* translators: %s: plugin slug */
        'message' => sprintf(
            /* translators: 1: plugin slug */
            esc_html__( 'Plugin %1$s installed and activated successfully.', 'sifency-addons' ),
            $plugin_slug
        ),
        'plugin_slug' => $plugin_path,
    ] );

}

    /**
     * Enqueue JavaScript for AJAX handling.
     */
    private function enqueue_scripts() {
        wp_enqueue_script( 'sifency-prebuild-import', plugin_dir_url(__FILE__) . 'prebuild.js', ['jquery'], '1.0.4', true );
        wp_localize_script( 'sifency-prebuild-import', 'SifencyImportData', [
            'ajax_url' => admin_url( 'admin-ajax.php' ),
            'nonce' => wp_create_nonce( 'sifency_demo_import_nonce' ),
        ] );
    }
}