<?php
/**
 * Custom Post Types and Custom Taxonomies Registration
 */

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

class Proto_Preview_CPT {

    public function init() {
        add_action('init', [$this, 'register_post_types']);
        add_action('init', [$this, 'register_taxonomies']);
        add_action('init', [$this, 'migrate_existing_project_slugs']);
        add_filter('use_block_editor_for_post_type', [$this, 'disable_gutenberg_for_projects'], 10, 2);
        add_filter('wp_unique_post_slug', [$this, 'generate_hashed_project_slug'], 10, 6);
        add_filter('wp_insert_post_data', [$this, 'enforce_hashed_post_name'], 10, 2);
        add_filter('wp_robots', [$this, 'prevent_indexing_projects']);
        add_filter('upload_mimes', [$this, 'allow_prototype_mime_types']);
    }

    public function allow_prototype_mime_types($mimes) {
        $mimes['html'] = 'text/html';
        $mimes['htm'] = 'text/html';
        $mimes['svg'] = 'image/svg+xml';
        $mimes['webp'] = 'image/webp';
        $mimes['png'] = 'image/png';
        $mimes['jpg|jpeg|jpe'] = 'image/jpeg';
        return $mimes;
    }

    public function prevent_indexing_projects($robots) {
        if (is_singular('proto_project') || get_query_var('proto_preview') || isset($_GET['proto_preview'])) {
            $robots['noindex'] = true;
            $robots['nofollow'] = true;
            $robots['noarchive'] = true;
            $robots['nosnippet'] = true;
        }
        return $robots;
    }

    public function generate_hashed_project_slug($slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug) {
        if ($post_type === 'proto_project') {
            if (!preg_match('/^[a-z0-9]{10}$/', $slug)) {
                $existing_token = get_post_meta($post_ID, '_proto_share_token', true);
                if (!empty($existing_token) && strlen($existing_token) >= 10 && preg_match('/^[a-z0-9]{10,}$/i', $existing_token)) {
                    return strtolower(substr($existing_token, 0, 10));
                }
                return strtolower(wp_generate_password(10, false, false));
            }
        }
        return $slug;
    }

    public function enforce_hashed_post_name($data, $postarr) {
        if ($data['post_type'] === 'proto_project' && !in_array($data['post_status'], ['trash', 'auto-draft'], true)) {
            if (!preg_match('/^[a-z0-9]{10}$/', $data['post_name'])) {
                $post_id = $postarr['ID'] ?? 0;
                $token = $post_id ? get_post_meta($post_id, '_proto_share_token', true) : '';
                if (!empty($token) && strlen($token) >= 10 && preg_match('/^[a-z0-9]{10,}$/i', $token)) {
                    $hash = strtolower(substr($token, 0, 10));
                } else {
                    $hash = strtolower(wp_generate_password(10, false, false));
                }
                $data['post_name'] = $hash;
            }
        }
        return $data;
    }

    public function migrate_existing_project_slugs() {
        global $wpdb;
        $projects = $wpdb->get_results("SELECT ID, post_name FROM {$wpdb->posts} WHERE post_type = 'proto_project' AND post_status != 'trash'");
        if ($projects) {
            foreach ($projects as $p) {
                if (!preg_match('/^[a-z0-9]{10}$/', $p->post_name)) {
                    $token = get_post_meta($p->ID, '_proto_share_token', true);
                    if (!empty($token) && strlen($token) >= 10 && preg_match('/^[a-z0-9]{10,}$/i', $token)) {
                        $new_slug = strtolower(substr($token, 0, 10));
                    } else {
                        $new_slug = strtolower(wp_generate_password(10, false, false));
                    }
                    $wpdb->update($wpdb->posts, ['post_name' => $new_slug], ['ID' => $p->ID]);
                }
            }
        }
    }

    public function disable_gutenberg_for_projects($use_block_editor, $post_type) {
        if ($post_type === 'proto_project') {
            return false;
        }
        return $use_block_editor;
    }

    public function register_post_types() {
        $labels = [
            'name'                  => _x('Projects', 'Post type general name', 'proto-preview'),
            'singular_name'         => _x('Project', 'Post type singular name', 'proto-preview'),
            'menu_name'             => _x('Proto Preview', 'Admin Menu text', 'proto-preview'),
            'name_admin_bar'        => _x('Prototype Project', 'Add New on Toolbar', 'proto-preview'),
            'add_new'               => __('Add New Project', 'proto-preview'),
            'add_new_item'          => __('Add New Project', 'proto-preview'),
            'new_item'              => __('New Project', 'proto-preview'),
            'edit_item'             => __('Edit Project', 'proto-preview'),
            'view_item'             => __('View Project in Player', 'proto-preview'),
            'all_items'             => __('All Projects', 'proto-preview'),
            'search_items'          => __('Search Projects', 'proto-preview'),
            'parent_item_colon'     => __('Parent Projects:', 'proto-preview'),
            'not_found'             => __('No projects found.', 'proto-preview'),
            'not_found_in_trash'    => __('No projects found in Trash.', 'proto-preview'),
        ];

        $args = [
            'labels'             => $labels,
            'public'             => true,
            'publicly_queryable' => true,
            'show_ui'            => true,
            'show_in_menu'       => true,
            'query_var'          => true,
            'rewrite'            => ['slug' => 'proto-project'],
            'capability_type'    => 'post',
            'has_archive'        => true,
            'hierarchical'       => false,
            'menu_position'      => 25,
            'menu_icon'          => 'dashicons-art',
            'show_in_rest'       => false, // Disabled for classic editor view
            'supports'           => ['title', 'thumbnail', 'author'],
        ];

        register_post_type('proto_project', $args);
    }

    public function register_taxonomies() {
        // 1. Clients Taxonomy (e.g. Nexus Financial Inc., Lumina Design Group)
        $client_labels = [
            'name'              => _x('Clients', 'taxonomy general name', 'proto-preview'),
            'singular_name'     => _x('Client', 'taxonomy singular name', 'proto-preview'),
            'search_items'      => __('Search Clients', 'proto-preview'),
            'all_items'         => __('All Clients', 'proto-preview'),
            'parent_item'       => __('Parent Client', 'proto-preview'),
            'parent_item_colon' => __('Parent Client:', 'proto-preview'),
            'edit_item'         => __('Edit Client', 'proto-preview'),
            'update_item'       => __('Update Client', 'proto-preview'),
            'add_new_item'      => __('Add New Client', 'proto-preview'),
            'new_item_name'     => __('New Client Name', 'proto-preview'),
            'menu_name'         => __('Clients', 'proto-preview'),
        ];

        register_taxonomy('proto_client', ['proto_project'], [
            'hierarchical'      => true,
            'labels'            => $client_labels,
            'show_ui'           => false,
            'show_in_menu'      => false,
            'show_admin_column' => false,
            'query_var'         => true,
            'rewrite'           => ['slug' => 'proto-client'],
            'show_in_rest'      => true,
        ]);


    }

    public function seed_demo_projects() {
        // Check if demo project already exists
        $existing = get_posts([
            'post_type'   => 'proto_project',
            'post_status' => 'any',
            'numberposts' => 1
        ]);

        if (!empty($existing)) {
            return;
        }

        // 1. Seed Taxonomies Terms
        $client1 = wp_insert_term('Nexus Financial Inc.', 'proto_client');
        $client2 = wp_insert_term('Lumina Design Group', 'proto_client');
        $client3 = wp_insert_term('Stripe Partner Team', 'proto_client');

        $status_in_review = wp_insert_term('In Review', 'proto_status');
        $status_approved  = wp_insert_term('Client Approved', 'proto_status');
        $status_draft     = wp_insert_term('Draft Exploration', 'proto_status');

        $cat_webapp = wp_insert_term('Web Application', 'proto_category');
        $cat_brand  = wp_insert_term('Brand Redesign', 'proto_category');

        $admin_id = get_current_user_id() ?: 1;
        $plugin_url = PROTO_PREVIEW_PLUGIN_URL;

        // 2. Seed Project 1: NexusPay Brand & Web App
        $proj1_id = wp_insert_post([
            'post_title'   => 'NexusPay Brand & Web App',
            'post_content' => 'Enterprise payment rails, checkout conversion optimization, and high-trust marketing experience built for Nexus Financial Inc.',
            'post_status'  => 'publish',
            'post_type'    => 'proto_project',
            'post_author'  => $admin_id,
        ]);

        if ($proj1_id && !is_wp_error($proj1_id)) {
            if (!is_wp_error($client1)) wp_set_post_terms($proj1_id, [$client1['term_id']], 'proto_client');
            if (!is_wp_error($status_in_review)) wp_set_post_terms($proj1_id, [$status_in_review['term_id']], 'proto_status');
            if (!is_wp_error($cat_webapp)) wp_set_post_terms($proj1_id, [$cat_webapp['term_id']], 'proto_category');

            // Set Meta for Screens & Variations
            $screens = [
                [
                    'id' => 1,
                    'name' => 'Homepage',
                    'slug' => 'home',
                    'layouts' => [
                        [
                            'id' => 1,
                            'version' => 'Option 1',
                            'name' => 'Homepage 1 (Modern SaaS)',
                            'file_path' => $plugin_url . 'layouts/saas-v1.html',
                            'badge' => 'Clean & High Conversion',
                            'color' => 'red',
                            'description' => 'Clean SaaS aesthetic with interactive live metrics and terminal simulator.',
                            'is_selected_choice' => 1
                        ],
                        [
                            'id' => 2,
                            'version' => 'Option 2',
                            'name' => 'Homepage 2 (Dark Cyber AI)',
                            'file_path' => $plugin_url . 'layouts/dark-v2.html',
                            'badge' => 'Dark Mode & High Tech',
                            'color' => 'cyan',
                            'description' => 'High-contrast dark mode tailored for developer credibility and infrastructure trust.',
                            'is_selected_choice' => 0
                        ],
                        [
                            'id' => 3,
                            'version' => 'Option 3',
                            'name' => 'Homepage 3 (Editorial Studio)',
                            'file_path' => $plugin_url . 'layouts/agency-v3.html',
                            'badge' => 'Warm & Editorial Luxury',
                            'color' => 'orange',
                            'description' => 'Sophisticated serif typography and warm editorial palette for premium brand presence.',
                            'is_selected_choice' => 0
                        ]
                    ]
                ],
                [
                    'id' => 2,
                    'name' => 'Pricing & Plans',
                    'slug' => 'pricing',
                    'layouts' => [
                        [
                            'id' => 4,
                            'version' => 'Option 1',
                            'name' => 'Pricing 1 (Tiered Matrix)',
                            'file_path' => $plugin_url . 'layouts/saas-v1.html',
                            'badge' => 'Tiered Cards',
                            'color' => 'red',
                            'description' => '3-tier SaaS pricing model with volume slider and enterprise inquiry triggers.',
                            'is_selected_choice' => 1
                        ],
                        [
                            'id' => 5,
                            'version' => 'Option 2',
                            'name' => 'Pricing 2 (Usage-Based API)',
                            'file_path' => $plugin_url . 'layouts/dark-v2.html',
                            'badge' => 'Consumption Model',
                            'color' => 'cyan',
                            'description' => 'Developer-first consumption calculator with volume tier discount breakdowns.',
                            'is_selected_choice' => 0
                        ]
                    ]
                ],
                [
                    'id' => 3,
                    'name' => 'Enterprise Solutions',
                    'slug' => 'enterprise',
                    'layouts' => [
                        [
                            'id' => 6,
                            'version' => 'Option 1',
                            'name' => 'Enterprise 1 (Bento Grid)',
                            'file_path' => $plugin_url . 'layouts/agency-v3.html',
                            'badge' => 'SOC-2 & Custom SLAs',
                            'color' => 'red',
                            'description' => 'High-touch enterprise pitch page with SOC-2, HIPAA, and custom SLA highlights.',
                            'is_selected_choice' => 1
                        ]
                    ]
                ]
            ];

            update_post_meta($proj1_id, '_proto_share_token', 'nexuspay-demo-token-2026');
            update_post_meta($proj1_id, '_proto_client_name', 'Nexus Financial Inc.');
            update_post_meta($proj1_id, '_proto_screens', $screens);
        }

        // 3. Seed Project 2: Lumina Architecture & Living
        $proj2_id = wp_insert_post([
            'post_title'   => 'Lumina Architecture & Living',
            'post_content' => 'Luxury architectural portfolio, residential case studies, and private consultation flow for high-end residential clients.',
            'post_status'  => 'publish',
            'post_type'    => 'proto_project',
            'post_author'  => $admin_id,
        ]);

        if ($proj2_id && !is_wp_error($proj2_id)) {
            if (!is_wp_error($client2)) wp_set_post_terms($proj2_id, [$client2['term_id']], 'proto_client');
            if (!is_wp_error($status_approved)) wp_set_post_terms($proj2_id, [$status_approved['term_id']], 'proto_status');
            if (!is_wp_error($cat_brand)) wp_set_post_terms($proj2_id, [$cat_brand['term_id']], 'proto_category');

            $screens2 = [
                [
                    'id' => 1,
                    'name' => 'Homepage',
                    'slug' => 'home',
                    'layouts' => [
                        [
                            'id' => 1,
                            'version' => 'Option 1',
                            'name' => 'Homepage 1 (Editorial Minimalist)',
                            'file_path' => $plugin_url . 'layouts/agency-v3.html',
                            'badge' => 'Refined Serif',
                            'color' => 'red',
                            'description' => 'Editorial luxury presence with full-width photography frames and subtle typography.',
                            'is_selected_choice' => 1
                        ],
                        [
                            'id' => 2,
                            'version' => 'Option 2',
                            'name' => 'Homepage 2 (Cinema Dark)',
                            'file_path' => $plugin_url . 'layouts/dark-v2.html',
                            'badge' => 'Cinema Dark',
                            'color' => 'cyan',
                            'description' => 'High-drama dark background highlighting architectural lighting and textures.',
                            'is_selected_choice' => 0
                        ]
                    ]
                ],
                [
                    'id' => 2,
                    'name' => 'Selected Works',
                    'slug' => 'portfolio',
                    'layouts' => [
                        [
                            'id' => 3,
                            'version' => 'Option 1',
                            'name' => 'Portfolio 1 (Masonry Gallery)',
                            'file_path' => $plugin_url . 'layouts/agency-v3.html',
                            'badge' => 'Interactive Filter',
                            'color' => 'red',
                            'description' => 'Multi-column filterable architectural portfolio with interactive project detail modals.',
                            'is_selected_choice' => 1
                        ]
                    ]
                ]
            ];

            update_post_meta($proj2_id, '_proto_share_token', 'lumina-demo-token-2026');
            update_post_meta($proj2_id, '_proto_client_name', 'Lumina Design Group');
            update_post_meta($proj2_id, '_proto_screens', $screens2);
        }
    }
}
