<?php
/**
 * Wizard Step 2: Template Gallery
 * 
 * phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
 * phpcs:disable WordPress.PHP.DevelopmentFunctions.error_log_error_log
 * phpcs:disable WordPress.PHP.DevelopmentFunctions.error_log_print_r
 * phpcs:disable WordPress.Security.NonceVerification.Recommended
 * phpcs:disable WordPress.Security.NonceVerification.Missing
 */

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

// Debug session data

$trstemp_placeholder_image = TRSTEMP_URI . 'assets/images/placeholder.png';

// Check wizard session data
$wizard_data = get_option('trstemp_wizard_data', array());
// ✅ Step-1 selected parent slug (from wizard)
$step1_parent_slug = '';

if (
    isset($wizard_data['step_1']['website_type']) &&
    ! empty($wizard_data['step_1']['website_type'])
) {
    $step1_parent_slug = sanitize_title(
        $wizard_data['step_1']['website_type']
    );
}
error_log('TRSTEMP STEP2: Wizard data: ' . print_r($wizard_data, true));

// Clear old step 3 data when returning to step 2
if (isset($wizard_data['step_3'])) {
    unset($wizard_data['step_3']);
    update_option('trstemp_wizard_data', $wizard_data);
    error_log('TRSTEMP STEP2: Cleared old step 3 data');
}

// Get templates from Laravel API
$api_base = 'https://templates.wp-turbo.com/api/v1';

// Get both single templates and template packs
$templates = array();
$categories = array();
$api_errors = array();

// Fetch categories from Laravel API
$cat_response = wp_remote_get($api_base . '/categories', array(
    'timeout' => 30,
    'headers' => array('Accept' => 'application/json')
));

if (is_wp_error($cat_response)) {
    $api_errors[] = 'Categories: ' . $cat_response->get_error_message();
} else {
    $status_code = wp_remote_retrieve_response_code($cat_response);
    if ($status_code === 200) {
        $body = wp_remote_retrieve_body($cat_response);
        $cat_data = json_decode($body, true);
        if (isset($cat_data['data']) && is_array($cat_data['data'])) {
            $categories = $cat_data['data'];
        }
    } else {
        $api_errors[] = 'Categories HTTP ' . $status_code;
    }
}

// Fetch single templates with category info (with pagination)
$page = isset($_GET['template_page']) ? max(1, absint($_GET['template_page'])) : 1;
$per_page = 500; // Load enough templates to cover all categories
$template_api_url = $api_base . '/templates?include=category&page=' . $page . '&per_page=' . $per_page;
if ( ! empty( $step1_parent_slug ) ) {
    $template_api_url .= '&category=' . rawurlencode( $step1_parent_slug );
}
$response1 = wp_remote_get( $template_api_url, array(
    'timeout' => 30,
    'headers' => array('Accept' => 'application/json')
));



if (is_wp_error($response1)) {
    $api_errors[] = 'Templates: ' . $response1->get_error_message();
} else {
    $status_code = wp_remote_retrieve_response_code($response1);
    if ($status_code === 200) {
        $body = wp_remote_retrieve_body($response1);
        $data = json_decode($body, true);
        if (isset($data['data']) && is_array($data['data'])) {
            foreach ($data['data'] as $template) {
                $template['type'] = 'single';
                $template['template_type'] = 'single';
                
                // Fix preview image URL for single templates
                if (isset($template['preview_image']) && !empty($template['preview_image'])) {
                    if (strpos($template['preview_image'], 'http') === 0) {
                        $template['preview_image'] = $template['preview_image'];
                    } else {
                        $template['preview_image'] = 'https://templates.wp-turbo.com/public/templates/images/' . rawurlencode($template['preview_image']);
                    }
                } else {
                    $template['preview_image'] = $trstemp_placeholder_image;
                }
                $templates[] = $template;
            }
        }
    } else {
        $api_errors[] = 'Templates HTTP ' . $status_code;
    }
}

// Fetch template packs with category info (with pagination)
$pack_api_url = $api_base . '/template-packs?include=category&page=' . $page . '&per_page=' . $per_page;
if ( ! empty( $step1_parent_slug ) ) {
    $pack_api_url .= '&category=' . rawurlencode( $step1_parent_slug );
}
$response2 = wp_remote_get( $pack_api_url, array(
    'timeout' => 30,
    'headers' => array('Accept' => 'application/json')
));



if (is_wp_error($response2)) {
    $api_errors[] = 'Template Packs: ' . $response2->get_error_message();
} else {
    $status_code = wp_remote_retrieve_response_code($response2);
    if ($status_code === 200) {
        $body = wp_remote_retrieve_body($response2);
        $data = json_decode($body, true);
        if (isset($data['data']) && is_array($data['data'])) {
        foreach ($data['data'] as $template) {
            $template['type'] = 'pack';
            $template['template_type'] = 'pack';

            $img = $template['preview'] ?? ($template['preview_image'] ?? null);

            if ($img) {
                if (strpos($img, 'http') === 0) {
                    $template['preview_image'] = $img;
                } else {
                    $template['preview_image'] = 'https://templates.wp-turbo.com/public/templates_pack/images/' . rawurlencode($img);
                }
            } else {
                $template['preview_image'] = $trstemp_placeholder_image;
            }

            $templates[] = $template;
        }

        }
    } else {
        $api_errors[] = 'Template Packs HTTP ' . $status_code;
    }
}


?>

<div class="trstemp-step-row">
    <div class="trstemp-template-gallery">
        <div class="trstemp-gallery-header">
            <h2><?php echo esc_html__('Choose Your Starting Template', 'turbo-templates-library-for-elementor'); ?></h2>
            <p><?php echo esc_html__('Select a professionally designed template that matches your vision. You can customize everything later.', 'turbo-templates-library-for-elementor'); ?></p>
        </div>
        
        <div class="trstemp-search-section">
            <div class="trstemp-search-box-full">
                <input type="text" placeholder="<?php echo esc_attr__('Search templates...', 'turbo-templates-library-for-elementor'); ?>" id="trstemp-template-search">
                <span class="trstemp-search-icon">🔍︎</span>
            </div>
        </div>
        
        <div class="trstemp-gallery-controls">
            <div class="trstemp-category-filters">
                <?php 
                // Build hierarchical category structure
                $parent_categories = array();
                $child_categories = array();
                
                if (!empty($categories)) {
                    foreach($categories as $category) {
                        if (empty($category['parent_id'])) {
                            $parent_categories[] = $category;
                        } else {
                            $child_categories[$category['parent_id']][] = $category;
                        }
                    }
                }
                
                // Display parent categories with dropdowns
                foreach ($parent_categories as $parent):

                    // ❌ Hide other parent categories (not selected in Step-1)
                    if (
                        ! empty($step1_parent_slug) &&
                        sanitize_title($parent['slug']) !== $step1_parent_slug
                    ) {
                        continue;
                    }

                    $has_children = isset($child_categories[$parent['id']]) && !empty($child_categories[$parent['id']]);
                ?>
                    <?php if ($has_children): ?>
                        <div class="trstemp-filter-dropdown">
                            <button class="trstemp-filter" data-category="<?php echo esc_attr($parent['slug'] ?? strtolower($parent['name'])); ?>" data-category-id="<?php echo esc_attr($parent['id']); ?>">
                                <?php echo esc_html($parent['name']); ?>
                                <span class="dropdown-arrow">▼</span>
                            </button>
                            <div class="subcategory-dropdown">
                                <?php foreach($child_categories[$parent['id']] as $child): ?>
                                    <button class="subfilter" data-category="<?php echo esc_attr($child['slug'] ?? strtolower($child['name'])); ?>" data-category-id="<?php echo esc_attr($child['id']); ?>">
                                        <?php echo esc_html($child['name']); ?>
                                    </button>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php else: ?>
                        <button class="trstemp-filter" data-category="<?php echo esc_attr($parent['slug'] ?? strtolower($parent['name'])); ?>" data-category-id="<?php echo esc_attr($parent['id']); ?>">
                            <?php echo esc_html($parent['name']); ?>
                        </button>
                    <?php endif; ?>
                <?php endforeach; ?>
            </div>
            
            <div class="right-controls">
                <div class="type-filters">
                    <button class="type-filter active" data-type="all"><?php echo esc_html__('All', 'turbo-templates-library-for-elementor'); ?></button>
                    <button class="type-filter" data-type="free"><?php echo esc_html__('Free', 'turbo-templates-library-for-elementor'); ?></button>
                    <button class="type-filter" data-type="pro"><?php echo esc_html__('Pro', 'turbo-templates-library-for-elementor'); ?></button>
                </div>
                
                <div class="template-type-filters">
                    <select id="template-type">
                        <option value="all"><?php echo esc_html__('All Types', 'turbo-templates-library-for-elementor'); ?></option>
                        <option value="pack"><?php echo esc_html__('Full Website', 'turbo-templates-library-for-elementor'); ?></option>
                        <option value="single"><?php echo esc_html__('Landing Page', 'turbo-templates-library-for-elementor'); ?></option>
                    </select>
                </div>
                
            </div>
        </div>
    
    <div class="templates-grid" id="templates-grid">
        
        <?php if (!empty($templates)): ?>
            <?php foreach($templates as $template): ?>
            <?php 
                $parent_id  = '';
                $child_id   = '';
                $parent_slug = '';
                $child_slug  = '';
                $category_name = 'General';

                if ( isset( $template['parent_category'] ) && is_array( $template['parent_category'] ) ) {
                    $parent_id   = $template['parent_category']['id'] ?? '';
                    $parent_slug = $template['parent_category']['slug'] ?? '';
                    $category_name = $template['parent_category']['name'] ?? $category_name;
                } elseif ( isset( $template['parent_category_id'] ) ) {
                    $parent_id = $template['parent_category_id'];
                }

                if ( isset( $template['child_category'] ) && is_array( $template['child_category'] ) ) {
                    $child_id   = $template['child_category']['id'] ?? '';
                    $child_slug = $template['child_category']['slug'] ?? '';
                    $child_category_name = $template['child_category']['name'];
                } elseif ( isset( $template['child_category_id'] ) ) {
                    $child_id = $template['child_category_id'];
                }
            
            // if (isset($template['category']) && !empty($template['category'])) {
            //     if (is_array($template['category'])) {
            //         $category_name = isset($template['category']['name']) && !empty($template['category']['name']) 
            //             ? $template['category']['name'] 
            //             : (isset($template['category'][0]) && !empty($template['category'][0]) ? $template['category'][0] : 'General');
            //         $category_slug = isset($template['category']['slug']) && !empty($template['category']['slug']) 
            //             ? $template['category']['slug'] 
            //             : strtolower($category_name);
            //         $category_id = isset($template['category']['id']) ? $template['category']['id'] : '';
            //         $parent_id = isset($template['category']['parent_id']) ? $template['category']['parent_id'] : '';
            //     } else {
            //         $category_name = $template['category'];
            //         $category_slug = strtolower($category_name);
            //     }
            // }
            ?>
            <div class="template-card"
                data-template="<?php echo esc_attr( $template['id'] ); ?>"
                data-name="<?php echo esc_attr( $template['name'] ?? 'Template' ); ?>"
                data-parent-id="<?php echo esc_attr( $parent_id ); ?>"
                data-child-id="<?php echo esc_attr( $child_id ); ?>"
                data-template-type="<?php echo esc_attr( $template['template_type'] ?? 'single' ); ?>"
                data-pro="<?php echo ( isset( $template['is_pro'] ) && $template['is_pro'] === true ) ? 'true' : 'false'; ?>"
                data-downloads="<?php echo esc_attr( $template['downloads'] ?? 0 ); ?>"
                data-created="<?php echo esc_attr( $template['created_at'] ?? '' ); ?>"
                data-demo-url="<?php echo esc_url( $template['demo_url'] ?? '' ); ?>">

                <div class="template-preview">
                    <img
                        src="<?php echo esc_url( $template['preview_image'] ?? $trstemp_placeholder_image ); ?>"
                        alt="<?php echo esc_attr( $template['name'] ?? 'Template' ); ?>"
                        loading="lazy"
                        onerror="this.onerror=null;this.src='<?php echo esc_url( $trstemp_placeholder_image ); ?>';"
                    >

                    <!-- Hover Overlay -->
                    <div class="template-overlay">

                        <!-- Preview button (JS will handle this) -->
                        <button
                            type="button"
                            class="btn-preview"
                            data-template="<?php echo esc_attr( $template['id'] ); ?>">
                            👁️ Preview
                        </button>

                        <!-- Select button (JS will handle redirect + save) -->
                        <button
                            type="button"
                            class="btn-select">
                            ✓ Select
                        </button>

                    </div>
                </div>

                <div class="template-info">
                    <h3><?php echo esc_html( $template['name'] ?? 'Template' ); ?></h3>

                    <div class="template-meta">
                        <span class="category">
                            <?php echo esc_html( ucfirst( $child_category_name ?? 'General' ) ); ?>
                        </span>
                        <?php if ( isset( $template['is_pro'] ) && $template['is_pro'] === false ) : ?>
                            <span class="free-badge">Free</span>
                        <?php else : ?>
                            <span class="pro-badge pro-badge-large">Pro</span>
                        <?php endif; ?>
                        <?php if ( isset( $template['type'] ) && $template['type'] === 'pack' ) : ?>
                            <span class="pack-badge">Full Site</span>
                        <?php else : ?>
                            <span class="single-badge">Landing Page</span>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        <?php else: ?>
            <!-- Show message when Laravel API is not available -->
            <div class="api-error-message" style="text-align: center; padding: 60px 20px; background: #f8f9fa; border-radius: 12px; margin: 40px 0;">
                <div style="font-size: 48px; margin-bottom: 20px;">🔌</div>
                <h3 style="color: #333; margin-bottom: 15px;"><?php echo esc_html__('Template Server Unavailable', 'turbo-templates-library-for-elementor'); ?></h3>
                <p style="color: #666; margin-bottom: 20px;"><?php echo esc_html__('Unable to connect to the template server at', 'turbo-templates-library-for-elementor'); ?> <code>templates.wp-turbo.com</code></p>
                <?php if (!empty($api_errors)): ?>
                    <div style="background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 6px; padding: 15px; margin: 20px 0; text-align: left;">
                        <strong>Debug Info:</strong><br>
                        <?php foreach ($api_errors as $error): ?>
                            <div style="color: #856404; font-size: 14px; margin: 5px 0;">• <?php echo esc_html($error); ?></div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
                <p style="color: #666; margin-bottom: 20px;"><?php echo esc_html__('Please check your internet connection and try again.', 'turbo-templates-library-for-elementor'); ?></p>
                <button onclick="location.reload()" class="turbo-btn-primary" style="background: #667eea; color: white; padding: 12px 24px; border: none; border-radius: 6px; cursor: pointer;"><?php echo esc_html__('Retry Connection', 'turbo-templates-library-for-elementor'); ?></button>
            </div>
        <?php endif; ?>

        <!-- 🔔 No Templates Fallback (JS controlled) -->
        <div id="trstemp-no-templates"
            style="display:none; text-align:center; padding:60px 20px;">

            <h3 style="margin-bottom:10px;">
                🚫 No Templates Found
            </h3>

            <p style="color:#666; margin-bottom:20px;">
                This category has no templates.<br>
                Please go back and change your category.
            </p>

            <button
                type="button"
                class="turbo-btn-secondary"
                onclick="window.history.back();">
                ← Go Back
            </button>

        </div>

        </div>
        
        <div class="load-more-section" id="load-more-section" style="text-align: center; margin: 40px 0; display: none;">
            <button id="load-more-btn" class="load-more-btn">
                <span class="load-text"><?php echo esc_html__('Load More Templates', 'turbo-templates-library-for-elementor'); ?></span>
                <span class="loading-text" style="display: none;"><?php echo esc_html__('Loading...', 'turbo-templates-library-for-elementor'); ?></span>
            </button>
        </div>
    </div>
    
</div>

<?php
// Enqueue step-2 specific assets
wp_enqueue_script(
    'trstemp-step-2',
    TRSTEMP_URI . 'assets/step-2.js', // Use the constant directly
    array('jquery'),
    '1.0.5',
    true
);

wp_enqueue_style(
    'trstemp-step-2',
    TRSTEMP_URI . 'assets/step-2.css', // Use the constant directly
    array(),
    '1.0.5'
);

// Localize script with necessary data
wp_localize_script('trstemp-step-2', 'trstempStep2', array(
    'ajaxurl' => admin_url('admin-ajax.php'),
    'nonce' => wp_create_nonce('trstemp_wizard_step'),
    'step' => 2
));
?>
