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

/**
 * VMO Phase Output Manager
 * 
 * Manages structured outputs for each consultation phase according to the
 * Elite Business Consultation Flow specification.
 * 
 * MASTER PRINCIPLE: VMO is not a chatbot. VMO is a Business Execution System.
 * Every phase must answer: What is being determined? What does the AI DO with that information?
 * No phase ends without implementation artifacts.
 * 
 * Phase Outputs:
 * - Phase 1: business foundations / vision_profile / business_structure (NO recommendations)
 * - Phase 2: confirmed_business_blueprint (NO recommendations)
 * - Phase 3: market_inputs, market_research, competitor_analysis (NO recommendations shown)
 * - Phase 4: approved_execution_plan / recommendations (FIRST recommendations)
 * - Phase 5: website_experience_plan / brand_assets
 * - Phase 6: payments_infrastructure, offer_catalog, legal_pack, systems/compliance
 * - Phase 7: business_roadmap, daily_activities_plan
 * - Phase 8: live_business_system, kpi_model, dashboard_modules, launch readiness
 * 
 * @package VMO_AI_Website_Builder
 */

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

class VMO_Phase_Output_Manager {
    
    private static $instance = null;
    private $wpdb;
    
    /**
     * Phase output type definitions with required fields
     */
    private $output_schemas = [
        // Phase 1: Business Foundations Intake
        'vision_profile' => [
            'phase' => 1,
            'required_fields' => ['business_goal', 'success_definition', 'income_intent', 'involvement_level'],
            // NOTE: Timeline is NOT in Phase 1 - it is CALCULATED in Phase 4 from roadmap activities
            'description' => 'Captures why the business exists and what success means to the user'
        ],
        'business_structure' => [
            'phase' => 1,
            'required_fields' => ['business_type', 'operating_model', 'geography', 'naming_status', 'constraints'],
            'description' => 'Defines what kind of business can realistically exist'
        ],
        
        // Phase 2: Executive Blueprint Confirmation
        'confirmed_business_blueprint' => [
            'phase' => 2,
            'required_fields' => ['approved', 'version', 'business_identity', 'vision_summary', 'target_market_summary'],
            'description' => 'Final confirmed business identity - source of truth for all future actions'
        ],
        
        // Phase 3: Deep Research (NO recommendations shown yet)
        'market_inputs' => [
            'phase' => 3,
            'required_fields' => ['customer_description', 'perceived_competitors', 'perceived_value', 'geography_focus'],
            'description' => 'User\'s understanding of their target market'
        ],
        'market_research' => [
            'phase' => 3,
            'required_fields' => ['competitors', 'gaps', 'pricing_norms', 'seo_opportunities', 'legal_flags'],
            'description' => 'AI-generated market intelligence dataset (silent until Phase 4)'
        ],
        'competitor_analysis' => [
            'phase' => 3,
            'required_fields' => ['competitors', 'market_gaps', 'opportunities', 'threats', 'benchmarking_summary'],
            'description' => 'Detailed competitor benchmarking with SWOT analysis'
        ],
        
        // Phase 4: Execution Plan (FIRST TIME recommendations appear)
        'approved_execution_plan' => [
            'phase' => 4,
            'required_fields' => ['website_structure', 'seo_strategy', 'monetization', 'automation_scope', 'compliance_plan', 'approved', 'version'],
            'description' => 'The execution contract - what VMO will build and why'
        ],
        
        // Phase 6: Payments & Commerce (handled inside systems/compliance)
        'payments_infrastructure' => [
            'phase' => 6,
            'required_fields' => ['stripe_account_id', 'pricing_model', 'checkout_logic', 'currency', 'tax_region'],
            'description' => 'How money flows and compliance with financial rules'
        ],
        
        // Phase 6: Product/service catalog readiness
        'offer_catalog' => [
            'phase' => 6,
            'required_fields' => ['products', 'prices', 'fulfillment_rules', 'inventory_config'],
            'description' => 'What is sold, how it\'s packaged, how it\'s fulfilled'
        ],
        
        // Phase 8: Live business system and launch deliverables
        'live_business_system' => [
            'phase' => 8,
            'required_fields' => ['website', 'automations', 'compliance', 'growth_tools', 'phone_system', 'email_system'],
            'description' => 'Complete business assembly including all systems'
        ],
        'brand_assets' => [
            'phase' => 5,
            'required_fields' => ['logo', 'colors', 'fonts', 'imagery_source', 'tone'],
            'description' => 'Brand identity and visual assets'
        ],
        'legal_pack' => [
            'phase' => 6,
            'required_fields' => ['privacy_policy', 'terms_of_service', 'refund_policy', 'cookie_policy', 'compliance_flags'],
            'description' => 'Legal documents and compliance notices'
        ],
        
        // Phase 8: Launch Readiness & Deliverables
        'kpi_model' => [
            'phase' => 8,
            'required_fields' => ['metrics', 'targets', 'measurement_frequency', 'alert_rules'],
            'description' => 'KPI definitions and tracking configuration'
        ],
        'dashboard_modules' => [
            'phase' => 8,
            'required_fields' => ['revenue', 'traffic', 'calls', 'conversions', 'seo', 'crm', 'recommendations'],
            'description' => 'Dashboard module configuration'
        ],
        
        // Phase 7: Roadmap & Daily Execution Model
        'business_roadmap' => [
            'phase' => 7,
            'required_fields' => ['roadmap_version', 'vision_target', 'milestones', 'dependency_graph', 'total_activities'],
            'description' => 'Activity-based execution roadmap from Day 0 to Vision Achieved'
        ],
        'daily_activities_plan' => [
            'phase' => 7,
            'required_fields' => ['total_days', 'activities_per_day', 'current_day', 'schedule_health'],
            'description' => 'Time-bound daily activities derived from roadmap'
        ]
    ];
    
    /**
     * Get singleton instance
     */
    public static function get_instance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Constructor
     */
    private function __construct() {
        global $wpdb;
        $this->wpdb = $wpdb;
    }
    
    /**
     * Save a phase output with versioning
     * 
     * @param int $user_id User ID
     * @param string $session_id Session/consultation ID
     * @param int $phase_number Phase number (1-8)
     * @param string $output_type Type of output (vision_profile, market_research, etc.)
     * @param array $output_data The structured data to save
     * @param bool $is_approved Whether user has approved this output
     * @return int|false The output ID or false on failure
     */
    public function save_phase_output($user_id, $session_id, $phase_number, $output_type, $output_data, $is_approved = false) {
        $table = $this->wpdb->prefix . 'vmo_phase_outputs';
        
        // Validate output type
        if (!isset($this->output_schemas[$output_type])) {
            error_log("VMO Phase Output: Unknown output type: {$output_type}");
            return false;
        }
        
        // Get current version
        $current_version = $this->wpdb->get_var($this->wpdb->prepare(
            "SELECT MAX(output_version) FROM {$table} 
             WHERE session_id = %s AND phase_number = %d AND output_type = %s",
            $session_id, $phase_number, $output_type
        ));
        $new_version = ($current_version ?? 0) + 1;
        
        // Deactivate previous versions
        $this->wpdb->update(
            $table,
            ['is_active' => 0],
            [
                'session_id' => $session_id,
                'phase_number' => $phase_number,
                'output_type' => $output_type
            ]
        );
        
        // Insert new version
        $result = $this->wpdb->insert($table, [
            'user_id' => $user_id,
            'session_id' => $session_id,
            'phase_number' => $phase_number,
            'output_type' => $output_type,
            'output_version' => $new_version,
            'output_json' => wp_json_encode($output_data),
            'is_active' => 1,
            'is_approved' => $is_approved ? 1 : 0,
            'approved_at' => $is_approved ? current_time('mysql') : null,
            'created_at' => current_time('mysql'),
            'updated_at' => current_time('mysql')
        ]);
        
        if ($result) {
            $output_id = $this->wpdb->insert_id;
            error_log("VMO Phase Output: Saved {$output_type} v{$new_version} for session {$session_id}");
            return $output_id;
        }
        
        error_log("VMO Phase Output: Failed to save {$output_type} - " . $this->wpdb->last_error);
        return false;
    }
    
    /**
     * Get active phase output
     */
    public function get_phase_output($session_id, $output_type, $phase_number = null) {
        $table = $this->wpdb->prefix . 'vmo_phase_outputs';
        
        $query = "SELECT * FROM {$table} WHERE session_id = %s AND output_type = %s AND is_active = 1";
        $params = [$session_id, $output_type];
        
        if ($phase_number !== null) {
            $query .= " AND phase_number = %d";
            $params[] = $phase_number;
        }
        
        $query .= " ORDER BY output_version DESC LIMIT 1";
        
        $row = $this->wpdb->get_row($this->wpdb->prepare($query, ...$params));
        
        if ($row) {
            $row->output_data = json_decode($row->output_json, true);
        }
        
        return $row;
    }
    
    /**
     * Get all outputs for a phase
     */
    public function get_all_phase_outputs($session_id, $phase_number) {
        $table = $this->wpdb->prefix . 'vmo_phase_outputs';
        
        $results = $this->wpdb->get_results($this->wpdb->prepare(
            "SELECT * FROM {$table} 
             WHERE session_id = %s AND phase_number = %d AND is_active = 1
             ORDER BY output_type ASC",
            $session_id, $phase_number
        ));
        
        foreach ($results as &$row) {
            $row->output_data = json_decode($row->output_json, true);
        }
        
        return $results;
    }
    
    /**
     * Approve a phase output (required for execution plan in Phase 4)
     */
    public function approve_output($session_id, $output_type, $user_notes = '') {
        $table = $this->wpdb->prefix . 'vmo_phase_outputs';
        
        return $this->wpdb->update(
            $table,
            [
                'is_approved' => 1,
                'approved_at' => current_time('mysql'),
                'updated_at' => current_time('mysql')
            ],
            [
                'session_id' => $session_id,
                'output_type' => $output_type,
                'is_active' => 1
            ]
        );
    }
    
    /**
     * Check if a phase is complete (all required outputs exist and are approved where needed)
     */
    public function is_phase_complete($session_id, $phase_number) {
        $required_outputs = array_filter($this->output_schemas, function($schema) use ($phase_number) {
            return $schema['phase'] === $phase_number;
        });
        
        foreach ($required_outputs as $output_type => $schema) {
            $output = $this->get_phase_output($session_id, $output_type, $phase_number);
            if (!$output) {
                return false;
            }
            
            // Phase 4 execution plan must be approved
            if ($output_type === 'approved_execution_plan' && !$output->is_approved) {
                return false;
            }
        }
        
        return true;
    }
    
    /**
     * Get phase completion status
     */
    public function get_phase_status($session_id, $phase_number) {
        $required_outputs = array_filter($this->output_schemas, function($schema) use ($phase_number) {
            return $schema['phase'] === $phase_number;
        });
        
        $status = [
            'phase' => $phase_number,
            'complete' => true,
            'outputs' => []
        ];
        
        foreach ($required_outputs as $output_type => $schema) {
            $output = $this->get_phase_output($session_id, $output_type, $phase_number);
            $output_status = [
                'type' => $output_type,
                'exists' => (bool)$output,
                'version' => $output ? $output->output_version : 0,
                'approved' => $output ? (bool)$output->is_approved : false,
                'required_fields' => $schema['required_fields']
            ];
            
            if (!$output) {
                $status['complete'] = false;
            }
            
            $status['outputs'][$output_type] = $output_status;
        }
        
        return $status;
    }
    
    /**
     * Extract and save vision_profile from conversation
     */
    public function extract_vision_profile($session_id, $user_id, $conversation_data) {
        // NOTE: Timeline is NOT captured here - it is CALCULATED in Phase 4 from roadmap activities
        $vision_profile = [
            'business_goal' => $conversation_data['business_goal'] ?? '',
            'success_definition' => $conversation_data['success_definition'] ?? '',
            'income_intent' => $conversation_data['income_intent'] ?? 'scale_long_term', // replace|supplement|scale_long_term
            'involvement_level' => $conversation_data['involvement_level'] ?? 'active', // hands_off|minimal|active|fully_involved
            // Timeline removed - now calculated from roadmap activities in Phase 4
            'automation_tolerance' => $conversation_data['automation_tolerance'] ?? 'high',
            'risk_tolerance' => $conversation_data['risk_tolerance'] ?? 'moderate',
            'extracted_at' => current_time('mysql')
        ];
        
        return $this->save_phase_output($user_id, $session_id, 1, 'vision_profile', $vision_profile);
    }
    
    /**
     * Extract and save business_structure from conversation
     */
    public function extract_business_structure($session_id, $user_id, $conversation_data) {
        $business_structure = [
            'business_type' => $conversation_data['business_type'] ?? 'service', // product|service|both
            'operating_model' => $conversation_data['operating_model'] ?? 'online', // online|physical|hybrid
            'geography' => $conversation_data['geography'] ?? [],
            'naming_status' => $conversation_data['naming_status'] ?? 'needs_name', // has_name|needs_name
            'business_name' => $conversation_data['business_name'] ?? '',
            'constraints' => $conversation_data['constraints'] ?? [],
            'regulatory_scope' => $conversation_data['regulatory_scope'] ?? 'standard',
            'extracted_at' => current_time('mysql')
        ];
        
        return $this->save_phase_output($user_id, $session_id, 1, 'business_structure', $business_structure);
    }
    
    /**
     * Create confirmed business blueprint (Phase 2)
     */
    public function create_confirmed_blueprint($session_id, $user_id) {
        // Get Phase 1 outputs
        $vision = $this->get_phase_output($session_id, 'vision_profile', 1);
        $structure = $this->get_phase_output($session_id, 'business_structure', 1);
        
        if (!$vision || !$structure) {
            error_log("VMO: Cannot create blueprint - missing Phase 1 outputs");
            return false;
        }
        
        $blueprint = [
            'approved' => false,
            'version' => '1.0',
            'business_identity' => [
                'name' => $structure->output_data['business_name'] ?? 'TBD',
                'type' => $structure->output_data['business_type'],
                'model' => $structure->output_data['operating_model'],
                'geography' => $structure->output_data['geography']
            ],
            'vision_summary' => [
                'goal' => $vision->output_data['business_goal'],
                'success_definition' => $vision->output_data['success_definition'],
                'involvement' => $vision->output_data['involvement_level'],
                // Timeline is calculated from roadmap activities in Phase 4
                'timeline_note' => 'Vision achievement timeline will be calculated from roadmap'
            ],
            'target_market_summary' => [
                'pending_research' => true,
                'initial_hints' => []
            ],
            'created_at' => current_time('mysql')
        ];
        
        return $this->save_phase_output($user_id, $session_id, 2, 'confirmed_business_blueprint', $blueprint);
    }
    
    /**
     * Save market research results (Phase 3 - silent, not shown to user yet)
     */
    public function save_market_research($session_id, $user_id, $research_data) {
        $market_research = [
            'competitors' => $research_data['competitors'] ?? [],
            'gaps' => $research_data['gaps'] ?? [],
            'pricing_norms' => $research_data['pricing_norms'] ?? [],
            'seo_opportunities' => $research_data['seo_opportunities'] ?? [],
            'legal_flags' => $research_data['legal_flags'] ?? [],
            'market_size' => $research_data['market_size'] ?? 'unknown',
            'saturation_level' => $research_data['saturation_level'] ?? 'moderate',
            'research_completed_at' => current_time('mysql')
        ];
        
        return $this->save_phase_output($user_id, $session_id, 3, 'market_research', $market_research);
    }
    
    /**
     * Save competitor analysis (Phase 3)
     */
    public function save_competitor_analysis($session_id, $user_id, $analysis_data) {
        $competitor_analysis = [
            'competitors' => array_map(function($comp) {
                return [
                    'name' => $comp['name'] ?? '',
                    'website' => $comp['website'] ?? '',
                    'type' => $comp['type'] ?? 'direct', // direct|indirect
                    'strengths' => $comp['strengths'] ?? [],
                    'weaknesses' => $comp['weaknesses'] ?? [],
                    'pricing_model' => $comp['pricing_model'] ?? '',
                    'positioning' => $comp['positioning'] ?? '',
                    'seo_summary' => $comp['seo_summary'] ?? '',
                    'ux_score' => $comp['ux_score'] ?? 0,
                    'trust_signals' => $comp['trust_signals'] ?? []
                ];
            }, $analysis_data['competitors'] ?? []),
            'market_gaps' => $analysis_data['market_gaps'] ?? [],
            'opportunities' => $analysis_data['opportunities'] ?? [],
            'threats' => $analysis_data['threats'] ?? [],
            'benchmarking_summary' => [
                'competitors_compared' => count($analysis_data['competitors'] ?? []),
                'key_differences' => $analysis_data['key_differences'] ?? [],
                'chosen_advantages' => $analysis_data['chosen_advantages'] ?? [],
                'risks_avoided' => $analysis_data['risks_avoided'] ?? []
            ],
            'analyzed_at' => current_time('mysql')
        ];
        
        return $this->save_phase_output($user_id, $session_id, 3, 'competitor_analysis', $competitor_analysis);
    }
    
    /**
     * Create execution plan (Phase 4 - FIRST TIME recommendations appear)
     */
    public function create_execution_plan($session_id, $user_id, $plan_data) {
        // Get all prior phase outputs
        $blueprint = $this->get_phase_output($session_id, 'confirmed_business_blueprint', 2);
        $market_research = $this->get_phase_output($session_id, 'market_research', 3);
        $competitor_analysis = $this->get_phase_output($session_id, 'competitor_analysis', 3);
        
        $execution_plan = [
            'approved' => false,
            'version' => '1.0',
            'based_on' => [
                'blueprint_version' => $blueprint ? $blueprint->output_version : null,
                'market_research_version' => $market_research ? $market_research->output_version : null,
                'competitor_analysis_version' => $competitor_analysis ? $competitor_analysis->output_version : null
            ],
            'website_structure' => $plan_data['website_structure'] ?? [],
            'seo_strategy' => $plan_data['seo_strategy'] ?? [],
            'monetization' => $plan_data['monetization'] ?? [],
            'automation_scope' => $plan_data['automation_scope'] ?? [],
            'compliance_plan' => $plan_data['compliance_plan'] ?? [],
            'phone_system' => $plan_data['phone_system'] ?? ['enabled' => false],
            'email_system' => $plan_data['email_system'] ?? ['enabled' => true],
            'ecommerce' => $plan_data['ecommerce'] ?? ['enabled' => false],
            'crm' => $plan_data['crm'] ?? ['enabled' => true],
            'analytics' => $plan_data['analytics'] ?? ['enabled' => true],
            'created_at' => current_time('mysql')
        ];
        
        return $this->save_phase_output($user_id, $session_id, 4, 'approved_execution_plan', $execution_plan);
    }
    
    /**
     * Generate business execution roadmap (after Phase 4 approval)
     * 
     * IMPORTANT: Timeline is CALCULATED from roadmap activities, NOT user input.
     * The total_days is determined by how many days are needed to complete all activities.
     */
    public function generate_business_roadmap($session_id, $user_id) {
        // Get execution plan
        $execution_plan = $this->get_phase_output($session_id, 'approved_execution_plan', 4);
        if (!$execution_plan || !$execution_plan->is_approved) {
            error_log("VMO: Cannot generate roadmap - execution plan not approved");
            return false;
        }
        
        $vision = $this->get_phase_output($session_id, 'vision_profile', 1);
        
        // Generate milestones from execution plan - pass null to calculate dynamically
        $milestones = $this->generate_milestones_from_plan($execution_plan->output_data, null);
        
        // CALCULATE total_days from the activities (NOT from user input)
        // Find the maximum day number across all milestone activities
        $calculated_total_days = $this->calculate_total_days_from_milestones($milestones);
        
        // Build dependency graph
        $dependency_graph = $this->build_dependency_graph($milestones);
        
        // Calculate total activities count
        $total_activities = array_sum(array_map(function($m) {
            return count($m['activities'] ?? []);
        }, $milestones));
        
        $roadmap = [
            'roadmap_version' => 1,
            'vision_target' => $vision ? $vision->output_data['business_goal'] : '',
            'total_days' => $calculated_total_days,
            'calculated_total_days' => $calculated_total_days, // Explicitly named to clarify it's AI-calculated
            'milestones' => $milestones,
            'dependency_graph' => $dependency_graph,
            'total_activities' => $total_activities,
            'timeline_calculation' => [
                'method' => 'calculated_from_activities',
                'note' => 'Timeline is determined by the activities needed, not user input',
                'start_date' => date('Y-m-d'),
                'vision_date' => date('Y-m-d', strtotime('+' . $calculated_total_days . ' days')),
                'formatted_duration' => $this->format_days_as_ymd($calculated_total_days)
            ],
            'generated_at' => current_time('mysql'),
            'last_updated' => current_time('mysql')
        ];
        
        $result = $this->save_phase_output($user_id, $session_id, 4, 'business_roadmap', $roadmap);
        
        if ($result) {
            // Also save to dedicated roadmap table for progress tracking
            $this->save_roadmap_to_tracking_table($user_id, $session_id, $roadmap);
        }
        
        return $result;
    }
    
    /**
     * Calculate total days from all milestone activities
     * The timeline is determined by the last activity day, not user preference
     */
    private function calculate_total_days_from_milestones($milestones) {
        $max_day = 0;
        
        foreach ($milestones as $milestone) {
            // Check milestone target day
            if (isset($milestone['target_day']) && $milestone['target_day'] > $max_day) {
                $max_day = $milestone['target_day'];
            }
            
            // Check each activity's day
            if (isset($milestone['activities']) && is_array($milestone['activities'])) {
                foreach ($milestone['activities'] as $activity) {
                    if (isset($activity['day']) && $activity['day'] > $max_day) {
                        $max_day = $activity['day'];
                    }
                }
            }
        }
        
        // Ensure minimum of 90 days (basic business setup)
        return max(90, $max_day);
    }
    
    /**
     * Format days as Year : Month : Day string
     */
    private function format_days_as_ymd($total_days) {
        $years = floor($total_days / 365);
        $remaining = $total_days % 365;
        $months = floor($remaining / 30);
        $days = $remaining % 30;
        
        if ($years > 0) {
            return $years . 'Y : ' . $months . 'M : ' . $days . 'D';
        } elseif ($months > 0) {
            return $months . 'M : ' . $days . 'D';
        } else {
            return $days . ' Days';
        }
    }
    
    /**
     * Generate milestones from execution plan
     * @param array $plan The approved execution plan
     * @param int|null $total_days If null, milestones will include all phases and days are calculated
     */
    private function generate_milestones_from_plan($plan, $total_days = null) {
        $milestones = [];
        $milestone_id = 1;
        
        // Phase 1: Foundation (Days 1-7)
        $milestones[] = [
            'milestone_id' => 'm_' . $milestone_id++,
            'name' => 'Business Foundation Complete',
            'description' => 'Website live, branding finalized, core systems operational',
            'phase' => 'foundation',
            'target_day' => 7,
            'prerequisite_milestones' => [],
            'activities' => [
                ['id' => 'a_1', 'title' => 'Website design finalized', 'type' => 'ai_executed', 'day' => 1],
                ['id' => 'a_2', 'title' => 'Logo and branding applied', 'type' => 'ai_executed', 'day' => 2],
                ['id' => 'a_3', 'title' => 'Core pages published', 'type' => 'ai_executed', 'day' => 3],
                ['id' => 'a_4', 'title' => 'SEO foundation set', 'type' => 'ai_executed', 'day' => 4],
                ['id' => 'a_5', 'title' => 'Contact forms configured', 'type' => 'ai_executed', 'day' => 5],
                ['id' => 'a_6', 'title' => 'Analytics installed', 'type' => 'ai_executed', 'day' => 6],
                ['id' => 'a_7', 'title' => 'Website launch review', 'type' => 'user_approval', 'day' => 7]
            ],
            'completion_criteria' => 'Website accessible, all core pages live'
        ];
        
        // Phase 2: Operations Setup (Days 8-21)
        $milestones[] = [
            'milestone_id' => 'm_' . $milestone_id++,
            'name' => 'Operations Fully Configured',
            'description' => 'Payment processing, CRM, email, and phone systems operational',
            'phase' => 'operations',
            'target_day' => 21,
            'prerequisite_milestones' => ['m_1'],
            'activities' => $this->generate_operations_activities($plan, 8),
            'completion_criteria' => 'All business systems accepting transactions/leads'
        ];
        
        // Phase 3: Marketing Launch (Days 22-45)
        $milestones[] = [
            'milestone_id' => 'm_' . $milestone_id++,
            'name' => 'Marketing Engine Running',
            'description' => 'SEO campaign active, content calendar set, lead generation started',
            'phase' => 'marketing',
            'target_day' => 45,
            'prerequisite_milestones' => ['m_2'],
            'activities' => $this->generate_marketing_activities($plan, 22),
            'completion_criteria' => 'First leads generated, SEO ranking for target keywords'
        ];
        
        // Phase 4: Growth Optimization (Days 46-90)
        $milestones[] = [
            'milestone_id' => 'm_' . $milestone_id++,
            'name' => 'Growth Phase Active',
            'description' => 'Revenue generation, customer acquisition, system optimization',
            'phase' => 'growth',
            'target_day' => 90,
            'prerequisite_milestones' => ['m_3'],
            'activities' => $this->generate_growth_activities($plan, 46),
            'completion_criteria' => 'Consistent revenue, optimized conversion rates'
        ];
        
        // Phase 5: Scale & Maturity (Days 91+) - ALWAYS included
        // The total_days is CALCULATED from activities, not user input
        // We generate maturity activities based on business complexity and vision goals
        $maturity_activities = $this->generate_maturity_activities($plan, 91, null);
        
        // Calculate the last day from the maturity activities
        $final_day = 90; // Start from end of growth phase
        if (!empty($maturity_activities)) {
            foreach ($maturity_activities as $activity) {
                if (isset($activity['day']) && $activity['day'] > $final_day) {
                    $final_day = $activity['day'];
                }
            }
        } else {
            // If no specific maturity activities, estimate based on business type
            $final_day = $this->estimate_vision_achievement_days($plan);
        }
        
        $milestones[] = [
            'milestone_id' => 'm_' . $milestone_id++,
            'name' => 'Business Vision Achieved',
            'description' => 'Full business objectives met, sustainable growth established',
            'phase' => 'maturity',
            'target_day' => $final_day,
            'prerequisite_milestones' => ['m_4'],
            'activities' => $maturity_activities,
            'completion_criteria' => 'Business vision metrics achieved'
        ];
        
        return $milestones;
    }
    
    /**
     * Estimate total days needed to achieve business vision based on plan complexity
     * This is used when specific activities don't provide enough data
     */
    private function estimate_vision_achievement_days($plan) {
        $base_days = 90; // Foundation, operations, marketing, growth
        
        // Add days based on business complexity
        $complexity_factors = 0;
        
        // E-commerce adds complexity
        if (!empty($plan['ecommerce']['enabled'])) {
            $complexity_factors += 60; // 2 months extra for e-commerce maturity
        }
        
        // Multiple products/services add complexity
        if (!empty($plan['products']) && count($plan['products']) > 3) {
            $complexity_factors += 30;
        }
        
        // Advanced marketing adds time
        if (!empty($plan['seo_strategy']) && !empty($plan['content_marketing'])) {
            $complexity_factors += 90; // SEO takes time to mature
        }
        
        // Automation scope
        if (!empty($plan['automation_scope']) && $plan['automation_scope'] === 'full') {
            $complexity_factors += 30;
        }
        
        // Geographic expansion
        if (!empty($plan['geography']) && $plan['geography'] === 'international') {
            $complexity_factors += 60;
        }
        
        // Minimum 180 days for any business to achieve sustainable growth
        // Maximum reasonable estimate is 730 days (2 years) for complex businesses
        return min(730, max(180, $base_days + $complexity_factors));
    }
    
    /**
     * Generate operations activities
     */
    private function generate_operations_activities($plan, $start_day) {
        $activities = [];
        $day = $start_day;
        $id = 10;
        
        // Payment system
        if (!empty($plan['monetization']) || !empty($plan['ecommerce']['enabled'])) {
            $activities[] = ['id' => 'a_' . $id++, 'title' => 'VMO Pay setup initiated', 'type' => 'user_action', 'day' => $day++];
            $activities[] = ['id' => 'a_' . $id++, 'title' => 'Payment processing configured', 'type' => 'ai_executed', 'day' => $day++];
            $activities[] = ['id' => 'a_' . $id++, 'title' => 'Checkout flow tested', 'type' => 'user_approval', 'day' => $day++];
        }
        
        // CRM setup
        if (!empty($plan['crm']['enabled'])) {
            $activities[] = ['id' => 'a_' . $id++, 'title' => 'CRM database initialized', 'type' => 'ai_executed', 'day' => $day++];
            $activities[] = ['id' => 'a_' . $id++, 'title' => 'Lead capture forms connected', 'type' => 'ai_executed', 'day' => $day++];
        }
        
        // Email system
        if (!empty($plan['email_system']['enabled'])) {
            $activities[] = ['id' => 'a_' . $id++, 'title' => 'Email domain verified', 'type' => 'user_action', 'day' => $day++];
            $activities[] = ['id' => 'a_' . $id++, 'title' => 'Email templates created', 'type' => 'ai_executed', 'day' => $day++];
            $activities[] = ['id' => 'a_' . $id++, 'title' => 'Welcome sequence configured', 'type' => 'ai_executed', 'day' => $day++];
        }
        
        // Phone system
        if (!empty($plan['phone_system']['enabled'])) {
            $activities[] = ['id' => 'a_' . $id++, 'title' => 'Business phone number provisioned', 'type' => 'ai_executed', 'day' => $day++];
            $activities[] = ['id' => 'a_' . $id++, 'title' => 'AI receptionist configured', 'type' => 'ai_executed', 'day' => $day++];
            $activities[] = ['id' => 'a_' . $id++, 'title' => 'Call routing tested', 'type' => 'user_approval', 'day' => $day++];
        }
        
        return $activities;
    }
    
    /**
     * Generate marketing activities
     */
    private function generate_marketing_activities($plan, $start_day) {
        $activities = [];
        $day = $start_day;
        $id = 30;
        
        // SEO activities
        $activities[] = ['id' => 'a_' . $id++, 'title' => 'SEO audit completed', 'type' => 'ai_executed', 'day' => $day++];
        $activities[] = ['id' => 'a_' . $id++, 'title' => 'Target keywords finalized', 'type' => 'user_approval', 'day' => $day++];
        $activities[] = ['id' => 'a_' . $id++, 'title' => 'Meta tags optimized', 'type' => 'ai_executed', 'day' => $day++];
        $activities[] = ['id' => 'a_' . $id++, 'title' => 'First blog post published', 'type' => 'ai_executed', 'day' => $day + 3];
        $activities[] = ['id' => 'a_' . $id++, 'title' => 'Content calendar created', 'type' => 'ai_executed', 'day' => $day + 5];
        
        // Weekly content (every 7 days)
        for ($week = 1; $week <= 3; $week++) {
            $activities[] = [
                'id' => 'a_' . $id++,
                'title' => "Week {$week} blog content published",
                'type' => 'ai_executed',
                'day' => $day + ($week * 7)
            ];
        }
        
        // Lead generation
        $activities[] = ['id' => 'a_' . $id++, 'title' => 'Lead magnet created', 'type' => 'ai_executed', 'day' => $day + 10];
        $activities[] = ['id' => 'a_' . $id++, 'title' => 'Email nurture sequence launched', 'type' => 'ai_executed', 'day' => $day + 14];
        
        return $activities;
    }
    
    /**
     * Generate growth activities
     */
    private function generate_growth_activities($plan, $start_day) {
        $activities = [];
        $day = $start_day;
        $id = 50;
        
        // Weekly optimization activities
        for ($week = 1; $week <= 6; $week++) {
            $activities[] = [
                'id' => 'a_' . $id++,
                'title' => "Week {$week} SEO scan & optimization",
                'type' => 'ai_executed',
                'day' => $day + (($week - 1) * 7)
            ];
            $activities[] = [
                'id' => 'a_' . $id++,
                'title' => "Week {$week} performance review",
                'type' => 'user_approval',
                'day' => $day + (($week - 1) * 7) + 1
            ];
        }
        
        // Monthly milestones
        $activities[] = ['id' => 'a_' . $id++, 'title' => 'Month 2 KPI review', 'type' => 'user_approval', 'day' => $start_day + 30];
        $activities[] = ['id' => 'a_' . $id++, 'title' => 'Conversion rate optimization', 'type' => 'ai_executed', 'day' => $start_day + 35];
        $activities[] = ['id' => 'a_' . $id++, 'title' => 'Customer feedback analysis', 'type' => 'ai_executed', 'day' => $start_day + 40];
        
        return $activities;
    }
    
    /**
     * Generate maturity activities
     * @param array $plan The execution plan
     * @param int $start_day The first day of maturity phase
     * @param int|null $total_days If null, activities will determine their own end point
     */
    private function generate_maturity_activities($plan, $start_day, $total_days = null) {
        $activities = [];
        $id = 80;
        
        // If total_days is null, we estimate based on business complexity
        // The AI calculates this, not the user
        if ($total_days === null) {
            $total_days = $this->estimate_vision_achievement_days($plan);
        }
        
        $remaining_days = max(1, $total_days - $start_day);
        $weeks = floor($remaining_days / 7);
        
        // Weekly deep research scans (up to 52 weeks / 1 year)
        for ($week = 1; $week <= min($weeks, 52); $week++) {
            $activities[] = [
                'id' => 'a_' . $id++,
                'title' => "Week {$week} market scan & recommendations",
                'type' => 'ai_executed',
                'day' => $start_day + (($week - 1) * 7),
                'recurring' => true
            ];
        }
        
        // Monthly performance reviews for longer roadmaps
        $months = floor($remaining_days / 30);
        for ($month = 1; $month <= min($months, 24); $month++) {
            $activities[] = [
                'id' => 'a_' . $id++,
                'title' => "Month {$month} performance review",
                'type' => 'user_approval',
                'day' => $start_day + ($month * 30)
            ];
        }
        
        // Quarterly reviews
        $quarters = floor($remaining_days / 90);
        for ($quarter = 1; $quarter <= min($quarters, 8); $quarter++) {
            $activities[] = [
                'id' => 'a_' . $id++,
                'title' => "Q{$quarter} business review & strategy adjustment",
                'type' => 'user_approval',
                'day' => $start_day + ($quarter * 90)
            ];
        }
        
        // Vision achievement check (final activity)
        $activities[] = [
            'id' => 'a_' . $id++,
            'title' => 'Business vision achievement assessment',
            'type' => 'user_approval',
            'day' => $total_days
        ];
        
        return $activities;
    }
    
    /**
     * Build dependency graph from milestones
     */
    private function build_dependency_graph($milestones) {
        $graph = [];
        
        foreach ($milestones as $milestone) {
            $graph[$milestone['milestone_id']] = [
                'depends_on' => $milestone['prerequisite_milestones'],
                'target_day' => $milestone['target_day'],
                'phase' => $milestone['phase']
            ];
        }
        
        return $graph;
    }
    
    /**
     * Save roadmap to tracking table
     */
    private function save_roadmap_to_tracking_table($user_id, $session_id, $roadmap) {
        $table = $this->wpdb->prefix . 'vmo_business_roadmaps';
        $roadmap_id = 'roadmap_' . uniqid();
        
        $this->wpdb->insert($table, [
            'roadmap_id' => $roadmap_id,
            'user_id' => $user_id,
            'session_id' => $session_id,
            'business_vision' => $roadmap['vision_target'],
            'roadmap_version' => $roadmap['roadmap_version'],
            'roadmap_data' => wp_json_encode($roadmap),
            'total_milestones' => count($roadmap['milestones']),
            'total_activities' => $roadmap['total_activities'],
            'total_duration_days' => $roadmap['total_days'],
            'roadmap_start_date' => date('Y-m-d'),
            'vision_target_date' => date('Y-m-d', strtotime('+' . $roadmap['total_days'] . ' days')),
            'current_day_number' => 1,
            'status' => 'active',
            'is_active' => 1,
            'created_at' => current_time('mysql'),
            'updated_at' => current_time('mysql')
        ]);
        
        // Generate daily activities
        $this->generate_daily_activities_from_roadmap($user_id, $roadmap_id, $roadmap);
        
        return $roadmap_id;
    }
    
    /**
     * Generate daily activities from roadmap
     */
    public function generate_daily_activities_from_roadmap($user_id, $roadmap_id, $roadmap) {
        $table = $this->wpdb->prefix . 'vmo_daily_activities';
        $start_date = date('Y-m-d');
        
        foreach ($roadmap['milestones'] as $milestone) {
            foreach ($milestone['activities'] as $activity) {
                $activity_date = date('Y-m-d', strtotime($start_date . ' + ' . ($activity['day'] - 1) . ' days'));
                
                $this->wpdb->insert($table, [
                    'activity_id' => $activity['id'] . '_' . uniqid(),
                    'roadmap_id' => $roadmap_id,
                    'milestone_id' => $milestone['milestone_id'],
                    'user_id' => $user_id,
                    'day_number' => $activity['day'],
                    'activity_date' => $activity_date,
                    'activity_title' => $activity['title'],
                    'activity_description' => '',
                    'activity_type' => $activity['type'],
                    'estimated_duration_minutes' => 60,
                    'priority' => $activity['type'] === 'user_action' ? 1 : ($activity['type'] === 'user_approval' ? 2 : 3),
                    'status' => 'pending',
                    'expected_complete_by' => $activity_date . ' 17:00:00',
                    'ai_generated' => 1,
                    'recurring' => $activity['recurring'] ?? 0,
                    'created_at' => current_time('mysql'),
                    'updated_at' => current_time('mysql')
                ]);
            }
        }
    }
    
    /**
     * Calculate progress for a roadmap
     */
    public function calculate_progress($roadmap_id, $user_id) {
        $activities_table = $this->wpdb->prefix . 'vmo_daily_activities';
        $roadmaps_table = $this->wpdb->prefix . 'vmo_business_roadmaps';
        $tracking_table = $this->wpdb->prefix . 'vmo_progress_tracking';
        
        // Get roadmap
        $roadmap = $this->wpdb->get_row($this->wpdb->prepare(
            "SELECT * FROM {$roadmaps_table} WHERE roadmap_id = %s",
            $roadmap_id
        ));
        
        if (!$roadmap) {
            return null;
        }
        
        // Calculate current day number
        $start_date = new DateTime($roadmap->roadmap_start_date);
        $today = new DateTime(date('Y-m-d'));
        $current_day = $today->diff($start_date)->days + 1;
        
        // Get expected activities by today
        $expected = $this->wpdb->get_var($this->wpdb->prepare(
            "SELECT COUNT(*) FROM {$activities_table} 
             WHERE roadmap_id = %s AND day_number <= %d",
            $roadmap_id, $current_day
        ));
        
        // Get actual completed
        $actual = $this->wpdb->get_var($this->wpdb->prepare(
            "SELECT COUNT(*) FROM {$activities_table} 
             WHERE roadmap_id = %s AND status = 'completed'",
            $roadmap_id
        ));
        
        // Get total activities
        $total = $this->wpdb->get_var($this->wpdb->prepare(
            "SELECT COUNT(*) FROM {$activities_table} WHERE roadmap_id = %s",
            $roadmap_id
        ));
        
        // Calculate percentages
        $progress_percentage = $total > 0 ? round(($actual / $total) * 100, 2) : 0;
        $expected_percentage = $total > 0 ? round(($expected / $total) * 100, 2) : 0;
        
        // Determine schedule health
        $diff = $actual - $expected;
        if ($diff >= 2) {
            $schedule_health = 'ahead';
        } elseif ($diff >= -1) {
            $schedule_health = 'on_track';
        } elseif ($diff >= -5) {
            $schedule_health = 'behind';
        } else {
            $schedule_health = 'critical';
        }
        
        // Calculate days ahead/behind
        // Find the day when we should have completed $actual activities
        $expected_day_for_actual = $this->wpdb->get_var($this->wpdb->prepare(
            "SELECT MAX(day_number) FROM (
                SELECT day_number FROM {$activities_table} 
                WHERE roadmap_id = %s 
                ORDER BY day_number ASC 
                LIMIT %d
            ) sub",
            $roadmap_id, max(1, $actual)
        ));
        
        $days_ahead_behind = $expected_day_for_actual ? ($expected_day_for_actual - $current_day) : 0;
        
        // Save tracking record
        // Calculate milestone progress from roadmap data
        $expected_milestones = 0;
        $actual_milestones = 0;
        $roadmap_row = $this->wpdb->get_row($this->wpdb->prepare(
            "SELECT roadmap_data, total_milestones FROM {$roadmaps_table} WHERE roadmap_id = %s",
            $roadmap_id
        ));
        if ($roadmap_row && $roadmap_row->roadmap_data) {
            $roadmap_data = json_decode($roadmap_row->roadmap_data, true);
            if (!empty($roadmap_data['milestones'])) {
                foreach ($roadmap_data['milestones'] as $ms) {
                    $ms_target = intval($ms['target_day'] ?? PHP_INT_MAX);
                    if ($ms_target <= $current_day) {
                        $expected_milestones++;
                        // A milestone is completed when ALL its activities are completed
                        $ms_activities = $ms['activities'] ?? [];
                        if (!empty($ms_activities)) {
                            $ms_first_day = PHP_INT_MAX;
                            $ms_last_day = 0;
                            foreach ($ms_activities as $act) {
                                $d = intval($act['day_number'] ?? $act['day'] ?? 0);
                                if ($d < $ms_first_day) $ms_first_day = $d;
                                if ($d > $ms_last_day) $ms_last_day = $d;
                            }
                            $ms_total = count($ms_activities);
                            $ms_completed = (int) $this->wpdb->get_var($this->wpdb->prepare(
                                "SELECT COUNT(*) FROM {$activities_table} WHERE roadmap_id = %s AND day_number BETWEEN %d AND %d AND status = 'completed'",
                                $roadmap_id, $ms_first_day, $ms_last_day
                            ));
                            if ($ms_completed >= $ms_total) {
                                $actual_milestones++;
                            }
                        }
                    }
                }
            }
        }

        $this->wpdb->replace($tracking_table, [
            'user_id' => $user_id,
            'roadmap_id' => $roadmap_id,
            'tracking_date' => date('Y-m-d'),
            'day_number' => $current_day,
            'expected_activities' => $expected,
            'actual_completed' => $actual,
            'expected_milestones' => $expected_milestones,
            'actual_milestones' => $actual_milestones,
            'progress_percentage' => $progress_percentage,
            'expected_percentage' => $expected_percentage,
            'schedule_health' => $schedule_health,
            'days_ahead_behind' => $days_ahead_behind,
            'weekly_velocity' => $this->calculate_weekly_velocity($roadmap_id),
            'created_at' => current_time('mysql')
        ]);
        
        // Update roadmap current day
        $this->wpdb->update(
            $roadmaps_table,
            ['current_day_number' => $current_day, 'updated_at' => current_time('mysql')],
            ['roadmap_id' => $roadmap_id]
        );
        
        return [
            'roadmap_id' => $roadmap_id,
            'current_day' => $current_day,
            'total_days' => $roadmap->total_duration_days,
            'expected_activities' => $expected,
            'actual_completed' => $actual,
            'total_activities' => $total,
            'progress_percentage' => $progress_percentage,
            'expected_percentage' => $expected_percentage,
            'schedule_health' => $schedule_health,
            'days_ahead_behind' => $days_ahead_behind,
            'velocity' => $this->calculate_weekly_velocity($roadmap_id)
        ];
    }
    
    /**
     * Calculate weekly velocity (activities per week average)
     */
    private function calculate_weekly_velocity($roadmap_id) {
        $table = $this->wpdb->prefix . 'vmo_daily_activities';
        
        // Get completed activities in last 7 days
        $completed_this_week = $this->wpdb->get_var($this->wpdb->prepare(
            "SELECT COUNT(*) FROM {$table} 
             WHERE roadmap_id = %s 
             AND status = 'completed' 
             AND actual_completed_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)",
            $roadmap_id
        ));
        
        return floatval($completed_this_week);
    }
    
    /**
     * Mark activity as completed
     */
    public function complete_activity($activity_id, $notes = '') {
        $table = $this->wpdb->prefix . 'vmo_daily_activities';
        
        return $this->wpdb->update(
            $table,
            [
                'status' => 'completed',
                'actual_completed_at' => current_time('mysql'),
                'completion_notes' => $notes,
                'updated_at' => current_time('mysql')
            ],
            ['activity_id' => $activity_id]
        );
    }
    
    /**
     * Get today's activities
     */
    public function get_todays_activities($user_id) {
        $table = $this->wpdb->prefix . 'vmo_daily_activities';
        
        return $this->wpdb->get_results($this->wpdb->prepare(
            "SELECT * FROM {$table} 
             WHERE user_id = %d 
             AND activity_date = %s 
             ORDER BY priority ASC, activity_type ASC",
            $user_id, date('Y-m-d')
        ));
    }
    
    /**
     * Get upcoming activities
     */
    public function get_upcoming_activities($user_id, $days = 7) {
        $table = $this->wpdb->prefix . 'vmo_daily_activities';
        
        return $this->wpdb->get_results($this->wpdb->prepare(
            "SELECT * FROM {$table} 
             WHERE user_id = %d 
             AND activity_date BETWEEN %s AND %s
             AND status = 'pending'
             ORDER BY activity_date ASC, priority ASC",
            $user_id, date('Y-m-d'), date('Y-m-d', strtotime('+' . $days . ' days'))
        ));
    }
    
    /**
     * Recalculate daily activities when market changes
     */
    public function recalculate_activities($roadmap_id, $new_activities = [], $remove_activity_ids = []) {
        $table = $this->wpdb->prefix . 'vmo_daily_activities';
        
        // Remove obsolete activities
        if (!empty($remove_activity_ids)) {
            $ids_placeholder = implode(',', array_fill(0, count($remove_activity_ids), '%s'));
            $this->wpdb->query($this->wpdb->prepare(
                "DELETE FROM {$table} WHERE activity_id IN ({$ids_placeholder})",
                ...$remove_activity_ids
            ));
        }
        
        // Add new activities
        foreach ($new_activities as $activity) {
            $this->wpdb->insert($table, [
                'activity_id' => 'a_new_' . uniqid(),
                'roadmap_id' => $roadmap_id,
                'milestone_id' => $activity['milestone_id'] ?? null,
                'user_id' => $activity['user_id'],
                'day_number' => $activity['day_number'],
                'activity_date' => $activity['activity_date'],
                'activity_title' => $activity['title'],
                'activity_description' => $activity['description'] ?? '',
                'activity_type' => $activity['type'] ?? 'task',
                'estimated_duration_minutes' => $activity['duration'] ?? 60,
                'priority' => $activity['priority'] ?? 3,
                'status' => 'pending',
                'ai_generated' => 1,
                'created_at' => current_time('mysql'),
                'updated_at' => current_time('mysql')
            ]);
        }
        
        return true;
    }
}

// Initialize singleton
VMO_Phase_Output_Manager::get_instance();
