<?php
/**
 * Fired during plugin activation.
 * Creates custom database tables and seeds demo projects.
 */

class Proto_Preview_Activator {

    public static function activate() {
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

        $charset_collate = $wpdb->get_charset_collate();

        // 1. Projects Table
        $table_projects = $wpdb->prefix . 'pp_projects';
        $sql_projects = "CREATE TABLE $table_projects (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            name varchar(150) NOT NULL,
            client_name varchar(150) NOT NULL,
            description text,
            share_token varchar(64) NOT NULL,
            status varchar(30) DEFAULT 'active',
            created_by bigint(20) NOT NULL,
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY  (id),
            UNIQUE KEY share_token (share_token)
        ) $charset_collate;";
        dbDelta($sql_projects);

        // 2. Pages / Screens Table
        $table_pages = $wpdb->prefix . 'pp_pages';
        $sql_pages = "CREATE TABLE $table_pages (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            project_id bigint(20) NOT NULL,
            name varchar(150) NOT NULL,
            slug varchar(100) NOT NULL,
            section_category varchar(100) DEFAULT 'Core Journey',
            page_order int(11) DEFAULT 1,
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY  (id),
            KEY project_id (project_id)
        ) $charset_collate;";
        dbDelta($sql_pages);

        // 3. Layouts / Variations Table
        $table_layouts = $wpdb->prefix . 'pp_layouts';
        $sql_layouts = "CREATE TABLE $table_layouts (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            project_id bigint(20) NOT NULL,
            page_id bigint(20) DEFAULT 1,
            version varchar(50) NOT NULL,
            name varchar(150) NOT NULL,
            file_path varchar(255) NOT NULL,
            thumbnail varchar(255),
            badge varchar(100),
            color varchar(30) DEFAULT 'red',
            description text,
            is_selected_choice int(1) DEFAULT 0,
            selected_by_user_id bigint(20),
            selected_at datetime,
            approval_status varchar(30) DEFAULT 'in_review',
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY  (id),
            KEY project_id (project_id),
            KEY page_id (page_id)
        ) $charset_collate;";
        dbDelta($sql_layouts);

        // 4. Tour Steps Table
        $table_steps = $wpdb->prefix . 'pp_tour_steps';
        $sql_steps = "CREATE TABLE $table_steps (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            layout_id bigint(20) NOT NULL,
            step_order int(11) NOT NULL DEFAULT 1,
            target_selector varchar(150) NOT NULL,
            title varchar(150) NOT NULL,
            content text NOT NULL,
            placement varchar(30) DEFAULT 'bottom',
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY  (id),
            KEY layout_id (layout_id)
        ) $charset_collate;";
        dbDelta($sql_steps);

        // 5. Comments Table
        $table_comments = $wpdb->prefix . 'pp_comments';
        $sql_comments = "CREATE TABLE $table_comments (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            layout_id bigint(20) NOT NULL,
            user_id bigint(20) NOT NULL,
            x_percent double NOT NULL,
            y_percent double NOT NULL,
            text text NOT NULL,
            is_resolved int(1) DEFAULT 0,
            resolved_by bigint(20),
            resolved_at datetime,
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY  (id),
            KEY layout_id (layout_id)
        ) $charset_collate;";
        dbDelta($sql_comments);

        // 6. Comment Replies Table
        $table_replies = $wpdb->prefix . 'pp_comment_replies';
        $sql_replies = "CREATE TABLE $table_replies (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            comment_id bigint(20) NOT NULL,
            user_id bigint(20) NOT NULL,
            text text NOT NULL,
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY  (id),
            KEY comment_id (comment_id)
        ) $charset_collate;";
        dbDelta($sql_replies);

        // 7. Section Approvals Table
        $table_approvals = $wpdb->prefix . 'pp_section_approvals';
        $sql_approvals = "CREATE TABLE $table_approvals (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            layout_id bigint(20) NOT NULL,
            user_id bigint(20) NOT NULL,
            step_order int(11) NOT NULL,
            target_selector varchar(150) NOT NULL,
            status varchar(30) NOT NULL DEFAULT 'approved',
            note text,
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY  (id),
            UNIQUE KEY layout_user_step (layout_id, user_id, step_order)
        ) $charset_collate;";
        dbDelta($sql_approvals);

        // Seed initial data if empty
        self::seed_data();

        // Flush rewrite rules
        flush_rewrite_rules();
    }

    public static function seed_data() {
        global $wpdb;
        $table_projects = $wpdb->prefix . 'pp_projects';

        $count = $wpdb->get_var("SELECT COUNT(*) FROM $table_projects");
        if ((int)$count > 0) {
            return;
        }

        $admin_user = wp_get_current_user();
        $admin_id = ($admin_user && $admin_user->ID) ? $admin_user->ID : 1;

        // 1. Seed Project 1: NexusPay Brand & Web App
        $wpdb->insert($table_projects, [
            'name' => 'NexusPay Brand & Web App',
            'client_name' => 'Nexus Financial Inc.',
            'description' => 'Enterprise payment rails, checkout conversion optimization, and high-trust marketing experience.',
            'share_token' => 'nexuspay-demo-token-2026',
            'status' => 'active',
            'created_by' => $admin_id,
            'created_at' => current_time('mysql')
        ]);
        $proj1_id = $wpdb->insert_id;

        // Pages for Project 1
        $table_pages = $wpdb->prefix . 'pp_pages';
        $wpdb->insert($table_pages, ['project_id' => $proj1_id, 'name' => 'Homepage', 'slug' => 'home', 'section_category' => 'Core Journey', 'page_order' => 1]);
        $p1_home_id = $wpdb->insert_id;

        $wpdb->insert($table_pages, ['project_id' => $proj1_id, 'name' => 'Pricing & Plans', 'slug' => 'pricing', 'section_category' => 'Core Journey', 'page_order' => 2]);
        $p1_pricing_id = $wpdb->insert_id;

        $wpdb->insert($table_pages, ['project_id' => $proj1_id, 'name' => 'Enterprise Solutions', 'slug' => 'enterprise', 'section_category' => 'Enterprise Flow', 'page_order' => 3]);
        $p1_enterprise_id = $wpdb->insert_id;

        // Layouts for Project 1
        $table_layouts = $wpdb->prefix . 'pp_layouts';
        $plugin_url = PROTO_PREVIEW_PLUGIN_URL;

        // Homepage Variations
        $wpdb->insert($table_layouts, [
            'project_id' => $proj1_id,
            'page_id' => $p1_home_id,
            '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,
            'approval_status' => 'approved',
            'created_at' => current_time('mysql')
        ]);
        $layout1_id = $wpdb->insert_id;

        $wpdb->insert($table_layouts, [
            'project_id' => $proj1_id,
            'page_id' => $p1_home_id,
            '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,
            'approval_status' => 'in_review',
            'created_at' => current_time('mysql')
        ]);

        $wpdb->insert($table_layouts, [
            'project_id' => $proj1_id,
            'page_id' => $p1_home_id,
            '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,
            'approval_status' => 'in_review',
            'created_at' => current_time('mysql')
        ]);

        // Pricing Variations
        $wpdb->insert($table_layouts, [
            'project_id' => $proj1_id,
            'page_id' => $p1_pricing_id,
            '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,
            'approval_status' => 'approved',
            'created_at' => current_time('mysql')
        ]);

        $wpdb->insert($table_layouts, [
            'project_id' => $proj1_id,
            'page_id' => $p1_pricing_id,
            '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,
            'approval_status' => 'in_review',
            'created_at' => current_time('mysql')
        ]);

        // Enterprise Variations
        $wpdb->insert($table_layouts, [
            'project_id' => $proj1_id,
            'page_id' => $p1_enterprise_id,
            '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,
            'approval_status' => 'approved',
            'created_at' => current_time('mysql')
        ]);

        // 2. Seed Project 2: Lumina Architecture & Living
        $wpdb->insert($table_projects, [
            'name' => 'Lumina Architecture & Living',
            'client_name' => 'Lumina Design Group',
            'description' => 'Luxury architectural portfolio, residential case studies, and private consultation flow.',
            'share_token' => 'lumina-demo-token-2026',
            'status' => 'active',
            'created_by' => $admin_id,
            'created_at' => current_time('mysql')
        ]);
        $proj2_id = $wpdb->insert_id;

        $wpdb->insert($table_pages, ['project_id' => $proj2_id, 'name' => 'Homepage', 'slug' => 'home', 'section_category' => 'Main Flow', 'page_order' => 1]);
        $p2_home_id = $wpdb->insert_id;

        $wpdb->insert($table_pages, ['project_id' => $proj2_id, 'name' => 'Selected Works', 'slug' => 'portfolio', 'section_category' => 'Main Flow', 'page_order' => 2]);
        $p2_works_id = $wpdb->insert_id;

        $wpdb->insert($table_layouts, [
            'project_id' => $proj2_id,
            'page_id' => $p2_home_id,
            '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,
            'approval_status' => 'approved',
            'created_at' => current_time('mysql')
        ]);

        $wpdb->insert($table_layouts, [
            'project_id' => $proj2_id,
            'page_id' => $p2_works_id,
            '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,
            'approval_status' => 'approved',
            'created_at' => current_time('mysql')
        ]);

        // 3. Tour Steps for Layout 1
        $table_steps = $wpdb->prefix . 'pp_tour_steps';
        $tourSteps = [
            [1, '#site-logo', '1. Brand Identity & Logo Lockup', 'We placed the modernized dynamic lightning emblem here. It includes an integrated version badge so stakeholders always know which live prototype they are reviewing.', 'bottom'],
            [2, '#nav-menu', '2. Streamlined Navigation Menu', 'Organized into four high-impact pillars: Solutions, Developers (with live API version tag), Pricing, and Case Studies for seamless user orientation.', 'bottom'],
            [3, '#header-cta', '3. High-Priority Header CTA', 'The "Book Demo" button features high contrast crimson elevation to ensure high conversion for inbound enterprise traffic.', 'bottom'],
            [4, '#hero-section', '4. Hero Value Proposition', 'Clear headline structure emphasizing modern financial rails with an animated status pill highlighting 2026 infrastructure readiness.', 'bottom'],
            [5, '#hero-cta', '5. Dual Hero Actions & Trust Badges', 'Gives developers an instant sandbox entry while offering business buyers a 2-minute video walkthrough, backed by SOC-2 Type II validation.', 'top'],
            [6, '#features-grid', '6. Core Enterprise Capability Matrix', 'Three core value props (130+ Currencies, AI Radar Fraud, SDKs) highlighted in clean Bento cards with subtle hover micro-interactions.', 'top'],
            [7, '#site-footer', '7. Standard Legal & Site Footer', 'Structured navigation, copyright notices, compliance links, and instant security disclosures.', 'top']
        ];

        foreach ($tourSteps as $step) {
            $wpdb->insert($table_steps, [
                'layout_id' => $layout1_id,
                'step_order' => $step[0],
                'target_selector' => $step[1],
                'title' => $step[2],
                'content' => $step[3],
                'placement' => $step[4],
                'created_at' => current_time('mysql')
            ]);
        }

        // 4. Seed Sample Pin Comments
        $table_comments = $wpdb->prefix . 'pp_comments';
        $wpdb->insert($table_comments, [
            'layout_id' => $layout1_id,
            'user_id' => $admin_id,
            'x_percent' => 64.5,
            'y_percent' => 18.2,
            'text' => 'Love the modern clean styling on this option! Can we make the Book Demo CTA button text slightly bolder?',
            'is_resolved' => 0,
            'created_at' => current_time('mysql')
        ]);
        $comm1_id = $wpdb->insert_id;

        $table_replies = $wpdb->prefix . 'pp_comment_replies';
        $wpdb->insert($table_replies, [
            'comment_id' => $comm1_id,
            'user_id' => $admin_id,
            'text' => 'Great note! We increased the font-weight to 700 and added a subtle hover elevation.',
            'created_at' => current_time('mysql')
        ]);
    }
}
