<?php

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

class AIEO_Brand_Page_Installer {

    const SLUG               = 'brand-shopping';
    const LEGACY_SLUG        = 'shop-by-brand';
    const PAGE_OPTION        = 'aieo_brand_shopping_page_id';
    const ADMIN_INSTALL_NONCE = 'aieo_install_brand_page';

    private static $registered = false;

    public static function bootstrap() {
        if (self::$registered) { return; }
        self::$registered = true;

        
        
        add_action('template_redirect', array(__CLASS__, 'maybe_legacy_redirect'), 1);

        
        
        
        
        add_filter('wp_get_nav_menu_items', array(__CLASS__, 'rewrite_brands_menu_url'), 20, 3);

        
        add_action('wp_ajax_aieo_install_brand_page', array(__CLASS__, 'ajax_install'));
    }

    
    public static function rewrite_brands_menu_url($items, $menu, $args) {
        if (!is_array($items) || empty($items)) { return $items; }
        $target = home_url('/' . self::SLUG . '/');
        foreach ($items as $item) {
            if (!isset($item->title)) { continue; }
            $title = trim((string) $item->title);
            if ($title === '') { continue; }
            
            
            
            if (strcasecmp($title, 'brands') !== 0) { continue; }
            if (isset($item->url) && (string) $item->url === $target) { continue; }
            $item->url = $target;
        }
        return $items;
    }

    
    public static function install() {
        $existing_id = (int) get_option(self::PAGE_OPTION, 0);
        if ($existing_id > 0 && get_post_status($existing_id) !== false) {
            return $existing_id;
        }

        $existing = get_page_by_path(self::SLUG);
        if ($existing instanceof \WP_Post) {
            update_option(self::PAGE_OPTION, (int) $existing->ID, false);
            return (int) $existing->ID;
        }

        
        
        
        
        
        
        
        
        
        
        if ( empty( $GLOBALS['wp_rewrite'] ) || ! ( $GLOBALS['wp_rewrite'] instanceof \WP_Rewrite ) ) {
            if ( ! has_action( 'init', array( __CLASS__, 'install' ) ) ) {
                add_action( 'init', array( __CLASS__, 'install' ), 99 );
            }
            return 0;
        }

        
        
        $content = '<!-- wp:pattern {"slug":"aieo/brand-shopping-page"} /-->';

        $id = wp_insert_post(array(
            'post_title'   => __('Αγορά ανά Brand', 'ai-eshop-optimizer'),
            'post_name'    => self::SLUG,
            'post_status'  => 'publish',
            'post_type'    => 'page',
            'post_content' => $content,
            'comment_status' => 'closed',
            'ping_status'    => 'closed',
        ), true);

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

        update_option(self::PAGE_OPTION, (int) $id, false);
        return (int) $id;
    }

    
    public static function maybe_legacy_redirect() {
        if (!isset($_SERVER['REQUEST_URI'])) { return; }
        $uri = (string) wp_unslash($_SERVER['REQUEST_URI']);
        $path = strtolower((string) wp_parse_url($uri, PHP_URL_PATH));
        $path = untrailingslashit($path);
        if ($path !== '/' . self::LEGACY_SLUG) { return; }

        $target = home_url('/' . self::SLUG . '/');
        wp_safe_redirect($target, 301);
        exit;
    }

    
    public static function ajax_install() {
        check_ajax_referer(self::ADMIN_INSTALL_NONCE, 'nonce');
        if (!current_user_can(defined('AIEO_CAPABILITY') ? AIEO_CAPABILITY : 'manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied.', 'ai-eshop-optimizer')));
        }
        $result = self::install();
        if (is_wp_error($result)) {
            wp_send_json_error(array('message' => $result->get_error_message()));
        }
        wp_send_json_success(array(
            'page_id' => (int) $result,
            'edit_url' => get_edit_post_link((int) $result, ''),
            'view_url' => get_permalink((int) $result),
        ));
    }
}
