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

class WAE_Page_Generator {
    public static function activate() {
        $opts = get_option('wae_options', array());
        if (empty($opts)) {
            $opts = array(
                'mode' => 'development',
                'landingpage_enabled' => '0',
                'matching_shape' => 'rounded',
                'primary_color' => '',
                'button_color' => '',
                'button_text_color' => '',
            );
            add_option('wae_options', $opts, '', false);
        }
    }

    public static function generate_test_landingpage() {
        if (!current_user_can('manage_options')) {
            return new WP_Error('wae_forbidden', 'Keine Berechtigung.');
        }

        $opts = get_option('wae_options', array());
        $parent_id = !empty($opts['wedding_page_id']) ? (int) $opts['wedding_page_id'] : 0;
        $slug = 'trauredner';
        $content = self::default_landingpage_content();

        $existing = null;
        if (!empty($opts['generated_landingpage_id'])) {
            $maybe = get_post((int) $opts['generated_landingpage_id']);
            if ($maybe instanceof WP_Post && $maybe->post_type === 'page') { $existing = $maybe; }
        }
        if (!$existing && $parent_id) {
            $children = get_posts(array(
                'post_type' => 'page',
                'post_status' => array('publish','draft','pending','private'),
                'post_parent' => $parent_id,
                'name' => $slug,
                'numberposts' => 1,
            ));
            if (!empty($children[0]) && $children[0] instanceof WP_Post) { $existing = $children[0]; }
        }
        if (!$existing) { $existing = get_page_by_path($slug, OBJECT, 'page'); }

        $postarr = array(
            'post_title' => 'Trauredner-Service für Eure Hochzeit',
            'post_name' => $slug,
            'post_content' => $content,
            'post_status' => 'publish',
            'post_type' => 'page',
            'post_parent' => $parent_id,
        );

        if ($existing instanceof WP_Post) {
            $postarr['ID'] = $existing->ID;
            $page_id = wp_update_post($postarr, true);
        } else {
            $page_id = wp_insert_post($postarr, true);
        }

        if (is_wp_error($page_id)) {
            return $page_id;
        }

        $opts = get_option('wae_options', array());
        $opts['generated_landingpage_id'] = (int) $page_id;
        $opts['landingpage_enabled'] = '1';
        update_option('wae_options', $opts, false);

        return $page_id;
    }

    private static function default_landingpage_content() {
        return '<!-- wp:shortcode -->[wedding_ai_trauredner_landingpage]<!-- /wp:shortcode -->';
    }
}
