<?php
/**
 * Impulse Blank Template
 * 
 * Used for checkout/cart preview with optional global header/footer
 * Renders global header/footer as Impulse pages
 * 
 * @package Instinctor
 */

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

// Get global header/footer pages
$headerPage = get_posts([
    'post_type' => 'page',
    'posts_per_page' => 1,
    'post_status' => 'publish',
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery,WordPress.DB.SlowDBQuery -- direct query against the plugin's own custom table; the WP options/post API does not model this data and the read is request-scoped (object caching would add complexity without benefit)
    'meta_query' => [
        [
            'key' => '_impulse_type',
            'value' => 'global_header',
        ]
    ]
]);
$footerPage = get_posts([
    'post_type' => 'page',
    'posts_per_page' => 1,
    'post_status' => 'publish',
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery,WordPress.DB.SlowDBQuery -- direct query against the plugin's own custom table; the WP options/post API does not model this data and the read is request-scoped (object caching would add complexity without benefit)
    'meta_query' => [
        [
            'key' => '_impulse_type',
            'value' => 'global_footer',
        ]
    ]
]);

$hasHeader = !empty($headerPage);
$hasFooter = !empty($footerPage);
?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
    <meta charset="<?php bloginfo('charset'); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?php
    // Static reset CSS lives in assets/css/frontend-critical.css; reuse it here.
    \Instinctor\Core\Assets::enqueue('instinctor-frontend-critical');
    wp_head();
    ?>
</head>
<body <?php body_class('impulse-blank-template'); ?>>
<?php wp_body_open(); ?>

<div class="impulse-blank-wrapper">

<?php if ($hasHeader): 
    $headerPost = $headerPage[0];
    $headerSettings = get_post_meta($headerPost->ID, '_impulse_settings', true) ?: [];
    $headerElements = get_post_meta($headerPost->ID, '_impulse_elements', true) ?: [];
    
    $bgColor = $headerSettings['bg_color'] ?? '#ffffff';
    $maxWidth = $headerSettings['max_width'] ?? 1200;
    $paddingTop = $headerSettings['padding_top'] ?? 16;
    $paddingBottom = $headerSettings['padding_bottom'] ?? 16;
    $paddingLeft = $headerSettings['padding_left'] ?? 24;
    $paddingRight = $headerSettings['padding_right'] ?? 24;
?>
<header class="impulse-global-header" style="background:<?php echo esc_attr($bgColor); ?>;padding:<?php echo intval($paddingTop); ?>px <?php echo intval($paddingRight); ?>px <?php echo intval($paddingBottom); ?>px <?php echo intval($paddingLeft); ?>px;border-bottom:1px solid #e5e5e5;">
    <div style="max-width:<?php echo intval($maxWidth); ?>px;margin:0 auto;">
        <?php 
        if (!empty($headerElements)) {
            echo '<div style="display:flex;align-items:center;justify-content:space-between;gap:24px;flex-wrap:wrap;">';
            foreach ($headerElements as $element) {
                impulse_render_blank_element($element);
            }
            echo '</div>';
        }
        ?>
    </div>
</header>
<?php endif; ?>

<main class="impulse-main-content">
    <?php
    while (have_posts()) {
        the_post();
        the_content();
    }
    ?>
</main>

<?php if ($hasFooter): 
    $footerPost = $footerPage[0];
    $footerSettings = get_post_meta($footerPost->ID, '_impulse_settings', true) ?: [];
    $footerElements = get_post_meta($footerPost->ID, '_impulse_elements', true) ?: [];
    
    $bgColor = $footerSettings['bg_color'] ?? '#1d1d1f';
    $maxWidth = $footerSettings['max_width'] ?? 1200;
    $paddingTop = $footerSettings['padding_top'] ?? 48;
    $paddingBottom = $footerSettings['padding_bottom'] ?? 48;
    $paddingLeft = $footerSettings['padding_left'] ?? 24;
    $paddingRight = $footerSettings['padding_right'] ?? 24;
?>
<footer class="impulse-global-footer" style="background:<?php echo esc_attr($bgColor); ?>;padding:<?php echo intval($paddingTop); ?>px <?php echo intval($paddingRight); ?>px <?php echo intval($paddingBottom); ?>px <?php echo intval($paddingLeft); ?>px;color:#fff;">
    <div style="max-width:<?php echo intval($maxWidth); ?>px;margin:0 auto;">
        <?php 
        if (!empty($footerElements)) {
            echo '<div style="display:flex;align-items:center;justify-content:space-between;gap:24px;flex-wrap:wrap;">';
            foreach ($footerElements as $element) {
                impulse_render_blank_element($element);
            }
            echo '</div>';
        }
        ?>
    </div>
</footer>
<?php endif; ?>

</div>

<?php wp_footer(); ?>
</body>
</html>
<?php

/**
 * Render element for blank template
 */
function impulse_render_blank_element($element) {
    $type = $element['type'] ?? '';
    $settings = $element['settings'] ?? [];
    
    switch ($type) {
        case 'site_logo':
            $logoId = get_theme_mod('custom_logo');
            $logoUrl = $settings['custom_url'] ?? '';
            if (!$logoUrl && $logoId) {
                $logoUrl = wp_get_attachment_image_url($logoId, 'full');
            }
            if ($logoUrl) {
                $maxHeight = $settings['max_height'] ?? 40;
                echo '<a href="' . esc_url(home_url('/')) . '" style="display:flex;align-items:center;">';
                echo '<img src="' . esc_url($logoUrl) . '" alt="' . esc_attr(get_bloginfo('name')) . '" style="max-height:' . intval($maxHeight) . 'px;width:auto;">';
                echo '</a>';
            }
            break;
            
        case 'site_title':
            $fontSize = $settings['font_size'] ?? 20;
            $fontWeight = $settings['font_weight'] ?? 600;
            $color = $settings['color'] ?? 'inherit';
            echo '<a href="' . esc_url(home_url('/')) . '" style="font-size:' . intval($fontSize) . 'px;font-weight:' . intval($fontWeight) . ';color:' . esc_attr($color) . ';">';
            echo esc_html(get_bloginfo('name'));
            echo '</a>';
            break;
            
        case 'nav_menu':
            $menuId = $settings['menu_id'] ?? '';
            $menuLocation = $settings['menu_location'] ?? 'primary';
            echo '<nav>';
            wp_nav_menu([
                'menu' => $menuId ?: '',
                'theme_location' => $menuLocation,
                'container' => false,
                'fallback_cb' => false,
                'depth' => 1,
                'items_wrap' => '<ul style="display:flex;gap:24px;list-style:none;margin:0;padding:0;">%3$s</ul>',
            ]);
            echo '</nav>';
            break;

        case 'cart':
            $cartCount = 0;
            if (class_exists('\Instinctor\Core\CartSession')) {
                $cartData = \Instinctor\Core\CartSession::get('cart');
                if (is_array($cartData) && !empty($cartData['items'])) {
                    foreach ($cartData['items'] as $_ci) {
                        $cartCount += intval($_ci['quantity'] ?? 1);
                    }
                }
            }
            $iconSize = $settings['icon_size'] ?? 24;
            echo '<a href="' . esc_url(\Instinctor\Services\PageService::resolveUrl('cart')) . '" style="position:relative;display:flex;align-items:center;">';
            echo '<svg viewBox="0 0 24 24" width="' . intval($iconSize) . '" height="' . intval($iconSize) . '" fill="none" stroke="currentColor" stroke-width="2"><circle cx="9" cy="21" r="1"/><circle cx="20" cy="21" r="1"/><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"/></svg>';
            if ($cartCount > 0) {
                echo '<span style="position:absolute;top:-8px;right:-8px;background:#1d2327;color:#fff;font-size:11px;min-width:18px;height:18px;border-radius:50%;display:flex;align-items:center;justify-content:center;">' . esc_html($cartCount) . '</span>';
            }
            echo '</a>';
            break;
            
        case 'social_icons':
            $icons = $settings['icons'] ?? [];
            $iconSize = $settings['icon_size'] ?? 20;
            $gap = $settings['gap'] ?? 16;
            if (!empty($icons)) {
                echo '<div style="display:flex;gap:' . intval($gap) . 'px;">';
                foreach ($icons as $icon) {
                    $url = $icon['url'] ?? '#';
                    $platform = $icon['platform'] ?? 'link';
                    echo '<a href="' . esc_url($url) . '" target="_blank" rel="noopener" style="opacity:0.7;">';
                    echo wp_kses(impulse_blank_get_social_icon($platform, $iconSize), impulse_blank_svg_allowed());
                    echo '</a>';
                }
                echo '</div>';
            }
            break;
            
        case 'copyright':
            $text = $settings['text'] ?? '© {year} {site_name}. All rights reserved.';
            $text = str_replace('{year}', gmdate('Y'), $text);
            $text = str_replace('{site_name}', get_bloginfo('name'), $text);
            $fontSize = $settings['font_size'] ?? 13;
            echo '<div style="font-size:' . intval($fontSize) . 'px;opacity:0.7;">' . esc_html($text) . '</div>';
            break;
            
        case 'title':
            $content = $settings['content'] ?? 'Heading';
            $tag = $settings['tag'] ?? 'h2';
            $fontSize = $settings['font_size'] ?? 24;
            $fontWeight = $settings['font_weight'] ?? 600;
            $color = $settings['color'] ?? 'inherit';
            $allowedTags = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'span', 'div'];
            $tag = in_array($tag, $allowedTags) ? $tag : 'h2';
            echo '<' . esc_html($tag) . ' style="margin:0;font-size:' . intval($fontSize) . 'px;font-weight:' . intval($fontWeight) . ';color:' . esc_attr($color) . ';">';
            echo wp_kses_post($content);
            echo '</' . esc_html($tag) . '>';
            break;
            
        case 'text':
            $content = $settings['content'] ?? '';
            $fontSize = $settings['font_size'] ?? 14;
            $color = $settings['color'] ?? 'inherit';
            echo '<div style="font-size:' . intval($fontSize) . 'px;color:' . esc_attr($color) . ';">' . wp_kses_post($content) . '</div>';
            break;
            
        case 'button':
            $text = $settings['text'] ?? 'Button';
            $url = $settings['url'] ?? '#';
            $bgColor = $settings['bg_color'] ?? '#1d1d1f';
            $textColor = $settings['text_color'] ?? '#ffffff';
            $fontSize = $settings['font_size'] ?? 14;
            $paddingX = $settings['padding_x'] ?? 20;
            $paddingY = $settings['padding_y'] ?? 10;
            $borderRadius = $settings['border_radius'] ?? 6;
            echo '<a href="' . esc_url($url) . '" style="display:inline-block;background:' . esc_attr($bgColor) . ';color:' . esc_attr($textColor) . ';padding:' . intval($paddingY) . 'px ' . intval($paddingX) . 'px;border-radius:' . intval($borderRadius) . 'px;font-size:' . intval($fontSize) . 'px;font-weight:500;">';
            echo esc_html($text);
            echo '</a>';
            break;
            
        case 'image':
            $url = $settings['url'] ?? '';
            $alt = $settings['alt'] ?? '';
            $width = $settings['width'] ?? 'auto';
            $height = $settings['height'] ?? 'auto';
            if ($url) {
                $style = 'max-width:100%;';
                if ($width !== 'auto') $style .= 'width:' . intval($width) . 'px;';
                if ($height !== 'auto') $style .= 'height:' . intval($height) . 'px;';
                echo '<img src="' . esc_url($url) . '" alt="' . esc_attr($alt) . '" style="' . esc_attr($style) . '">';
            }
            break;
            
        case 'spacer':
            $height = $settings['height'] ?? 20;
            echo '<div style="height:' . intval($height) . 'px;"></div>';
            break;
            
        case 'divider':
            $color = $settings['color'] ?? '#e5e5e5';
            $width = $settings['width'] ?? 1;
            echo '<hr style="border:none;border-top:' . intval($width) . 'px solid ' . esc_attr($color) . ';margin:0;width:100%;">';
            break;
            
        case 'html':
            $html = $settings['html'] ?? '';
            $canRenderHtml = (defined('INSTINCTOR_ENV') && INSTINCTOR_ENV === 'standalone')
                || (function_exists('current_user_can') && current_user_can('unfiltered_html'));
            // Custom-HTML block: capability-gated raw output (owner on standalone /
            // unfiltered_html on WP) mirrors WP core's Custom HTML widget and code.php;
            // wp_kses_post would strip legitimate admin-authored scripts/embeds, so the
            // capable path stays raw. Non-capable users get wp_kses_post.
            // phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped
            echo $canRenderHtml ? $html : wp_kses_post($html);
            // phpcs:enable WordPress.Security.EscapeOutput.OutputNotEscaped
            break;
    }
}

/**
 * Self-contained inline-SVG allowlist for wp_kses.
 *
 * impulse_svg_allowed() is not guaranteed loaded in this template
 * context, so the allowlist is defined here. Covers the curated
 * Lucide/social icon markup this file emits (svg + shape/path
 * elements and their geometry/style attributes).
 */
if (!function_exists('impulse_blank_svg_allowed')) {
    function impulse_blank_svg_allowed() {
        $attrs = [
            'viewbox' => true, 'd' => true, 'fill' => true, 'stroke' => true,
            'stroke-width' => true, 'stroke-linecap' => true, 'stroke-linejoin' => true,
            'cx' => true, 'cy' => true, 'r' => true, 'rx' => true, 'ry' => true,
            'x' => true, 'y' => true, 'x1' => true, 'y1' => true, 'x2' => true, 'y2' => true,
            'width' => true, 'height' => true, 'points' => true, 'transform' => true,
            'opacity' => true, 'class' => true, 'style' => true, 'gradientunits' => true,
            'offset' => true, 'stop-color' => true, 'stop-opacity' => true,
            'fill-rule' => true, 'vector-effect' => true,
        ];
        return [
            'svg' => $attrs, 'path' => $attrs, 'circle' => $attrs, 'ellipse' => $attrs,
            'rect' => $attrs, 'line' => $attrs, 'polyline' => $attrs, 'polygon' => $attrs,
            'g' => $attrs, 'defs' => $attrs, 'lineargradient' => $attrs,
            'radialgradient' => $attrs, 'stop' => $attrs, 'use' => $attrs,
        ];
    }
}

/**
 * Get social icon SVG
 */
function impulse_blank_get_social_icon($platform, $size = 20) {
    $icons = [
        'facebook' => '<svg width="' . intval($size) . '" height="' . intval($size) . '" viewBox="0 0 24 24" fill="currentColor"><path d="M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z"/></svg>',
        'twitter' => '<svg width="' . intval($size) . '" height="' . intval($size) . '" viewBox="0 0 24 24" fill="currentColor"><path d="M23 3a10.9 10.9 0 0 1-3.14 1.53 4.48 4.48 0 0 0-7.86 3v1A10.66 10.66 0 0 1 3 4s-4 9 5 13a11.64 11.64 0 0 1-7 2c9 5 20 0 20-11.5a4.5 4.5 0 0 0-.08-.83A7.72 7.72 0 0 0 23 3z"/></svg>',
        'instagram' => '<svg width="' . intval($size) . '" height="' . intval($size) . '" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="2" width="20" height="20" rx="5"/><path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z"/><line x1="17.5" y1="6.5" x2="17.51" y2="6.5"/></svg>',
        'linkedin' => '<svg width="' . intval($size) . '" height="' . intval($size) . '" viewBox="0 0 24 24" fill="currentColor"><path d="M16 8a6 6 0 0 1 6 6v7h-4v-7a2 2 0 0 0-2-2 2 2 0 0 0-2 2v7h-4v-7a6 6 0 0 1 6-6z"/><rect x="2" y="9" width="4" height="12"/><circle cx="4" cy="4" r="2"/></svg>',
        'youtube' => '<svg width="' . intval($size) . '" height="' . intval($size) . '" viewBox="0 0 24 24" fill="currentColor"><path d="M22.54 6.42a2.78 2.78 0 0 0-1.94-2C18.88 4 12 4 12 4s-6.88 0-8.6.46a2.78 2.78 0 0 0-1.94 2A29 29 0 0 0 1 11.75a29 29 0 0 0 .46 5.33A2.78 2.78 0 0 0 3.4 19c1.72.46 8.6.46 8.6.46s6.88 0 8.6-.46a2.78 2.78 0 0 0 1.94-2 29 29 0 0 0 .46-5.25 29 29 0 0 0-.46-5.33z"/><polygon points="9.75 15.02 15.5 11.75 9.75 8.48 9.75 15.02" fill="#fff"/></svg>',
        'link' => '<svg width="' . intval($size) . '" height="' . intval($size) . '" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>',
    ];
    return $icons[$platform] ?? $icons['link'];
}
