<?php
namespace WooNooW\Setup;

/**
 * Default Pages Setup
 * Creates default pages with WooNooW structure on plugin activation
 */
class DefaultPages
{
    /**
     * Ensure all default pages exist
     */
    public static function create_pages()
    {
        self::create_home_page();
        self::create_about_page();
        self::create_contact_page();
        self::create_legal_pages();
        self::create_woocommerce_pages();
        self::ensure_spa_settings();
    }

    /**
     * Ensure SPA Settings are configured
     */
    private static function ensure_spa_settings()
    {
        $settings = get_option('woonoow_appearance_settings', []);
        
        // Ensure General array exists
        if (!isset($settings['general'])) {
            $settings['general'] = [];
        }

        // Enable SPA mode if not set
        if (empty($settings['general']['spa_mode']) || $settings['general']['spa_mode'] === 'disabled') {
            $settings['general']['spa_mode'] = 'full';
        }

        // Set SPA Root Page if missing (prioritize Home, then Shop)
        if (empty($settings['general']['spa_page'])) {
            $home_page = get_page_by_path('home');
            $shop_page_id = get_option('woocommerce_shop_page_id');
            
            if ($home_page) {
                // If Home exists, make it the Front Page AND SPA Root
                $settings['general']['spa_page'] = $home_page->ID;
                update_option('show_on_front', 'page');
                update_option('page_on_front', $home_page->ID);
            } elseif ($shop_page_id) {
                // Fallback to Shop
                $settings['general']['spa_page'] = $shop_page_id;
            }
        }

        update_option('woonoow_appearance_settings', $settings);
    }

    /**
     * Create Home Page with Rich Layout
     */
    private static function create_home_page()
    {
        $slug = 'home';
        $title = 'Home';
        
        if (self::page_exists($slug)) {
            return;
        }

        $structure = [
            'type' => 'page',
            'sections' => [
                [
                    'id' => 'section-hero-home',
                    'type' => 'hero',
                    'layoutVariant' => 'default',
                    'colorScheme' => 'primary',
                    'props' => [
                        'title' => ['type' => 'static', 'value' => 'Welcome onto WooNooW'],
                        'subtitle' => ['type' => 'static', 'value' => 'Discover our premium collection of products tailored just for you. Quality meets style in every item.'],
                        'cta_text' => ['type' => 'static', 'value' => 'Shop Now'],
                        'cta_url' => ['type' => 'static', 'value' => '/shop'],
                        'image' => ['type' => 'static', 'value' => 'https://images.unsplash.com/photo-1441986300917-64674bd600d8?w=1600&q=80'],
                    ],
                    'elementStyles' => [
                        'title' => ['fontSize' => 'text-5xl', 'fontWeight' => 'font-bold'],
                    ]
                ],
                [
                    'id' => 'section-features-home',
                    'type' => 'feature-grid',
                    'layoutVariant' => 'grid-3',
                    'props' => [
                        'heading' => ['type' => 'static', 'value' => 'Why Choose Us'],
                        'features' => ['type' => 'static', 'value' => json_encode([
                            ['icon' => 'truck', 'title' => 'Free Shipping', 'description' => 'On all orders over $50'],
                            ['icon' => 'shield', 'title' => 'Secure Payment', 'description' => '100% secure payment processing'],
                            ['icon' => 'clock', 'title' => '24/7 Support', 'description' => 'Dedicated support anytime you need'],
                        ])]
                    ]
                ],
                [
                    'id' => 'section-story-home',
                    'type' => 'image-text',
                    'layoutVariant' => 'image-left',
                    'props' => [
                        'title' => ['type' => 'static', 'value' => 'Our Story'],
                        'text' => ['type' => 'static', 'value' => 'Founded with a passion for quality and design, we strive to bring you products that elevate your everyday life. Every item is carefully curated and inspected to ensure it meets our high standards.'],
                        'image' => ['type' => 'static', 'value' => 'https://images.unsplash.com/photo-1497366216548-37526070297c?w=800&q=80'],
                    ]
                ],
                [
                    'id' => 'section-cta-home',
                    'type' => 'cta-banner',
                    'colorScheme' => 'muted',
                    'props' => [
                        'title' => ['type' => 'static', 'value' => 'Ready to start shopping?'],
                        'text' => ['type' => 'static', 'value' => 'Join thousands of satisfied customers today.'],
                        'button_text' => ['type' => 'static', 'value' => 'View Catalog'],
                        'button_url' => ['type' => 'static', 'value' => '/shop'],
                    ]
                ]
            ],
            'created_at' => current_time('mysql'),
        ];

        self::insert_page($title, $slug, $structure);
    }

    /**
     * Create About Us Page
     */
    private static function create_about_page()
    {
        $slug = 'about';
        $title = 'About Us';
        
        if (self::page_exists($slug)) {
            return;
        }

        $structure = [
            'type' => 'page',
            'sections' => [
                [
                    'id' => 'section-hero-about',
                    'type' => 'hero',
                    'layoutVariant' => 'centered',
                    'colorScheme' => 'secondary',
                    'props' => [
                        'title' => ['type' => 'static', 'value' => 'About Us'],
                        'subtitle' => ['type' => 'static', 'value' => 'Learn more about our journey and mission.'],
                        'image' => ['type' => 'static', 'value' => 'https://images.unsplash.com/photo-1522071820081-009f0129c71c?w=1600&q=80'],
                    ]
                ],
                [
                    'id' => 'section-story-about',
                    'type' => 'image-text',
                    'layoutVariant' => 'image-right',
                    'props' => [
                        'title' => ['type' => 'static', 'value' => 'Who We Are'],
                        'text' => ['type' => 'static', 'value' => 'We are a team of passionate individuals dedicated to providing the best shopping experience. Our mission is to make quality products accessible to everyone.'],
                        'image' => ['type' => 'static', 'value' => 'https://images.unsplash.com/photo-1556761175-5973dc0f32e7?w=800&q=80'],
                    ]
                ],
                [
                    'id' => 'section-values-about',
                    'type' => 'feature-grid',
                    'layoutVariant' => 'grid-3',
                    'props' => [
                        'heading' => ['type' => 'static', 'value' => 'Our Core Values'],
                        'features' => ['type' => 'static', 'value' => json_encode([
                            ['icon' => 'heart', 'title' => 'Passion', 'description' => 'We love what we do'],
                            ['icon' => 'star', 'title' => 'Excellence', 'description' => 'We aim for the best'],
                            ['icon' => 'users', 'title' => 'Community', 'description' => 'We build relationships'],
                        ])]
                    ]
                ]
            ],
            'created_at' => current_time('mysql'),
        ];

        self::insert_page($title, $slug, $structure);
    }

    /**
     * Create Contact Page
     */
    private static function create_contact_page()
    {
        $slug = 'contact';
        $title = 'Contact Us';
        
        if (self::page_exists($slug)) {
            return;
        }

        $structure = [
            'type' => 'page',
            'sections' => [
                [
                    'id' => 'section-hero-contact',
                    'type' => 'hero',
                    'layoutVariant' => 'default',
                    'colorScheme' => 'gradient',
                    'props' => [
                        'title' => ['type' => 'static', 'value' => 'Get in Touch'],
                        'subtitle' => ['type' => 'static', 'value' => 'Have questions? We are here to help.'],
                    ]
                ],
                [
                    'id' => 'section-form-contact',
                    'type' => 'contact-form',
                    'props' => [
                        'title' => ['type' => 'static', 'value' => 'Send us a Message'],
                    ]
                ]
            ],
            'created_at' => current_time('mysql'),
        ];

        self::insert_page($title, $slug, $structure);
    }

    /**
     * Create Legal Pages
     */
    private static function create_legal_pages()
    {
        $pages = [
            'privacy-policy' => 'Privacy Policy',
            'terms-conditions' => 'Terms & Conditions',
        ];

        foreach ($pages as $slug => $title) {
            if (self::page_exists($slug)) {
                continue;
            }

            $content = "<h2>{$title}</h2><p>This is a placeholder for your {$title}. Please update this content with your actual legal text.</p><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>";

            $structure = [
                'type' => 'page',
                'sections' => [
                    [
                        'id' => 'section-content-' . $slug,
                        'type' => 'content',
                        'layoutVariant' => 'narrow',
                        'props' => [
                            'content' => ['type' => 'static', 'value' => $content],
                        ]
                    ]
                ],
                'created_at' => current_time('mysql'),
            ];

            self::insert_page($title, $slug, $structure);
            
            // If privacy policy, link it in WP settings
            if ($slug === 'privacy-policy') {
                $page = get_page_by_path($slug);
                if ($page) {
                    update_option('wp_page_for_privacy_policy', $page->ID);
                }
            }
        }
    }

    /**
     * Create WooCommerce Pages (Shop, Cart, Checkout, My Account)
     */
    private static function create_woocommerce_pages()
    {
        if (!class_exists('WooCommerce')) {
            return;
        }

        $wc_pages = [
            'shop' => ['title' => 'Shop', 'content' => '', 'option' => 'woocommerce_shop_page_id'],
            'cart' => ['title' => 'Cart', 'content' => '<!-- wp:shortcode -->[woocommerce_cart]<!-- /wp:shortcode -->', 'option' => 'woocommerce_cart_page_id'],
            'checkout' => ['title' => 'Checkout', 'content' => '<!-- wp:shortcode -->[woocommerce_checkout]<!-- /wp:shortcode -->', 'option' => 'woocommerce_checkout_page_id'],
            'my-account' => ['title' => 'My Account', 'content' => '<!-- wp:shortcode -->[woocommerce_my_account]<!-- /wp:shortcode -->', 'option' => 'woocommerce_myaccount_page_id'],
        ];

        foreach ($wc_pages as $slug => $data) {
            // Check if page is already assigned in WC options
            $existing_id = get_option($data['option']);
            if ($existing_id && get_post($existing_id)) {
                continue;
            }

            // Check if page exists by slug
            if (self::page_exists($slug)) {
                $page = get_page_by_path($slug);
                update_option($data['option'], $page->ID);
                continue;
            }

            // Create page
            $page_id = wp_insert_post([
                'post_title' => $data['title'],
                'post_name' => $slug,
                'post_content' => $data['content'],
                'post_status' => 'publish',
                'post_type' => 'page',
            ]);

            if ($page_id && !is_wp_error($page_id)) {
                update_option($data['option'], $page_id);
                
                // For Shop page, add a fallback structure (though content-product takes precedence in SPA)
                if ($slug === 'shop') {
                    $structure = [
                        'type' => 'page',
                        'sections' => [
                            [
                                'id' => 'section-shop-products',
                                'type' => 'content',
                                'props' => [
                                    'content' => ['type' => 'static', 'value' => '[products limit="12" columns="4"]'],
                                ]
                            ]
                        ],
                        'created_at' => current_time('mysql'),
                    ];
                    update_post_meta($page_id, '_wn_page_structure', $structure);
                } else {
                     // For other pages, add structre that wraps the shortcode for SPA rendering
                     $structure = [
                        'type' => 'page',
                        'sections' => [
                            [
                                'id' => 'section-' . $slug,
                                'type' => 'content',
                                'props' => [
                                    'content' => ['type' => 'static', 'value' => $data['content']],
                                ]
                            ]
                        ],
                        'created_at' => current_time('mysql'),
                    ];
                    update_post_meta($page_id, '_wn_page_structure', $structure);
                }
            }
        }
    }

    /**
     * Helper: Check if page exists
     */
    private static function page_exists($slug)
    {
        return !empty(get_page_by_path($slug));
    }

    /**
     * Helper: Insert Page and Structure
     */
    private static function insert_page($title, $slug, $structure)
    {
        $page_id = wp_insert_post([
            'post_title' => $title,
            'post_name' => $slug,
            'post_status' => 'publish',
            'post_type' => 'page',
        ]);

        if ($page_id && !is_wp_error($page_id)) {
            update_post_meta($page_id, '_wn_page_structure', $structure);
        }
    }
}
