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

/**
 * VMO KPI Dashboard System
 * Tracks and displays business KPIs and progress metrics
 */

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

class VMO_KPI_Dashboard {
    
    /**
     * Initialize KPI tracking for a new business
     */
    public function initialize_business_kpis($user_id, $business_intelligence) {
        global $wpdb;
        $table = $wpdb->prefix . 'vmo_business_kpis';
        
        // Create table if needed
        $this->create_kpi_table();
        
        // Initialize baseline KPIs
        $initial_kpis = [
            // Business Setup Status
            ['metric' => 'business_stage', 'value' => 'setup', 'label' => 'Business Stage', 'type' => 'status', 'category' => 'business'],
            ['metric' => 'consultation_completed', 'value' => '1', 'label' => 'Consultation Completed', 'type' => 'boolean', 'category' => 'setup'],
            ['metric' => 'research_completed', 'value' => '1', 'label' => 'Market Research Completed', 'type' => 'boolean', 'category' => 'setup'],
            ['metric' => 'website_generated', 'value' => '1', 'label' => 'Website Generated', 'type' => 'boolean', 'category' => 'setup'],
            ['metric' => 'documents_generated', 'value' => '1', 'label' => 'Business Documents Generated', 'type' => 'boolean', 'category' => 'setup'],
            
            // Website Status
            ['metric' => 'website_status', 'value' => 'draft', 'label' => 'Website Status', 'type' => 'status', 'category' => 'website'],
            ['metric' => 'pages_count', 'value' => '0', 'label' => 'Total Pages', 'type' => 'number', 'category' => 'website'],
            ['metric' => 'website_visitors', 'value' => '0', 'label' => 'Website Visitors', 'type' => 'number', 'category' => 'traffic'],
            ['metric' => 'page_views', 'value' => '0', 'label' => 'Page Views', 'type' => 'number', 'category' => 'traffic'],
            ['metric' => 'cta_clicks', 'value' => '0', 'label' => 'CTA Clicks', 'type' => 'number', 'category' => 'traffic'],
            ['metric' => 'product_views', 'value' => '0', 'label' => 'Product Views', 'type' => 'number', 'category' => 'traffic'],
            ['metric' => 'checkout_starts', 'value' => '0', 'label' => 'Checkout Starts', 'type' => 'number', 'category' => 'traffic'],
            
            // Lead Generation
            ['metric' => 'total_leads', 'value' => '0', 'label' => 'Total Leads', 'type' => 'number', 'category' => 'leads'],
            ['metric' => 'new_leads_today', 'value' => '0', 'label' => 'New Leads Today', 'type' => 'number', 'category' => 'leads'],
            ['metric' => 'new_leads_week', 'value' => '0', 'label' => 'New Leads This Week', 'type' => 'number', 'category' => 'leads'],
            ['metric' => 'form_submissions', 'value' => '0', 'label' => 'Form Submissions', 'type' => 'number', 'category' => 'leads'],
            ['metric' => 'phone_clicks', 'value' => '0', 'label' => 'Phone Clicks', 'type' => 'number', 'category' => 'leads'],
            ['metric' => 'email_clicks', 'value' => '0', 'label' => 'Email Clicks', 'type' => 'number', 'category' => 'leads'],
            ['metric' => 'conversion_events', 'value' => '0', 'label' => 'Conversion Events', 'type' => 'number', 'category' => 'leads'],
            ['metric' => 'conversion_rate', 'value' => '0', 'label' => 'Conversion Rate', 'type' => 'percentage', 'category' => 'leads'],
            
            // Commerce & Operations
            ['metric' => 'orders', 'value' => '0', 'label' => 'Orders', 'type' => 'number', 'category' => 'commerce'],
            ['metric' => 'orders_30d', 'value' => '0', 'label' => 'Orders 30d', 'type' => 'number', 'category' => 'commerce'],
            ['metric' => 'revenue', 'value' => '0', 'label' => 'Revenue', 'type' => 'currency', 'category' => 'commerce'],
            ['metric' => 'revenue_30d', 'value' => '0', 'label' => 'Revenue 30d', 'type' => 'currency', 'category' => 'commerce'],
            ['metric' => 'shipping_status_events', 'value' => '0', 'label' => 'Shipping Events', 'type' => 'number', 'category' => 'commerce'],
            ['metric' => 'seo_status_events', 'value' => '0', 'label' => 'SEO Status Events', 'type' => 'number', 'category' => 'seo'],
            
            // Content & SEO
            ['metric' => 'seo_score', 'value' => '0', 'label' => 'SEO Score', 'type' => 'score', 'category' => 'seo'],
            ['metric' => 'keywords_ranking', 'value' => '0', 'label' => 'Keywords Ranking', 'type' => 'number', 'category' => 'seo'],
            ['metric' => 'blog_posts', 'value' => '0', 'label' => 'Blog Posts Published', 'type' => 'number', 'category' => 'content'],
            ['metric' => 'social_posts', 'value' => '0', 'label' => 'Social Media Posts', 'type' => 'number', 'category' => 'content'],
            
            // Communication
            ['metric' => 'phone_calls_total', 'value' => '0', 'label' => 'Total Phone Calls', 'type' => 'number', 'category' => 'communication'],
            ['metric' => 'phone_calls_today', 'value' => '0', 'label' => 'Calls Today', 'type' => 'number', 'category' => 'communication'],
            ['metric' => 'emails_sent', 'value' => '0', 'label' => 'Emails Sent', 'type' => 'number', 'category' => 'communication'],
            ['metric' => 'messages_total', 'value' => '0', 'label' => 'Total Messages', 'type' => 'number', 'category' => 'communication'],
            
            // Business Info
            ['metric' => 'business_name', 'value' => $business_intelligence['business_name'] ?? '', 'label' => 'Business Name', 'type' => 'text', 'category' => 'business'],
            ['metric' => 'business_type', 'value' => $business_intelligence['business_type'] ?? '', 'label' => 'Business Type', 'type' => 'text', 'category' => 'business'],
            ['metric' => 'industry', 'value' => $business_intelligence['industry'] ?? '', 'label' => 'Industry', 'type' => 'text', 'category' => 'business'],
            
            // Goals & Progress
            ['metric' => 'setup_progress', 'value' => '60', 'label' => 'Setup Progress', 'type' => 'percentage', 'category' => 'progress'],
            ['metric' => 'next_milestone', 'value' => 'Publish Website', 'label' => 'Next Milestone', 'type' => 'text', 'category' => 'progress'],
        ];
        
        // Insert KPIs
        foreach ($initial_kpis as $kpi) {
            $this->set_kpi($user_id, $kpi['metric'], $kpi['value'], $kpi);
        }
        
        error_log('✅ KPI Dashboard: Initial KPIs set for user ' . $user_id);
    }
    
    /**
     * Get dashboard KPIs for user
     */
    public function get_dashboard_kpis($user_id) {
        global $wpdb;
        $table = $wpdb->prefix . 'vmo_business_kpis';
        
        $kpis = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$table} WHERE user_id = %d ORDER BY category, metric",
            $user_id
        ), ARRAY_A);
        
        // Organize by category
        $organized = [];
        foreach ($kpis as $kpi) {
            $category = $kpi['category'] ?? 'other';
            if (!isset($organized[$category])) {
                $organized[$category] = [];
            }
            $organized[$category][] = $kpi;
        }
        
        return $organized;
    }
    
    /**
     * Get single KPI value
     */
    public function get_kpi($user_id, $metric_name) {
        global $wpdb;
        $table = $wpdb->prefix . 'vmo_business_kpis';
        
        $result = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$table} WHERE user_id = %d AND metric = %s ORDER BY id DESC LIMIT 1",
            $user_id,
            $metric_name
        ), ARRAY_A);
        
        return $result ? $result['value'] : null;
    }
    
    /**
     * Set/Update KPI value
     */
    public function set_kpi($user_id, $metric_name, $value, $metadata = []) {
        global $wpdb;
        $table = $wpdb->prefix . 'vmo_business_kpis';
        
        $this->create_kpi_table();
        
        // Check if KPI exists
        $existing = $wpdb->get_var($wpdb->prepare(
            "SELECT id FROM {$table} WHERE user_id = %d AND metric = %s",
            $user_id,
            $metric_name
        ));
        
        $data = [
            'user_id' => $user_id,
            'metric' => $metric_name,
            'value' => $value,
            'label' => $metadata['label'] ?? ucwords(str_replace('_', ' ', (string) $metric_name)),
            'type' => $metadata['type'] ?? 'text',
            'category' => $metadata['category'] ?? 'other'
        ];
        
        if ($existing) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->update(
                $table,
                $data,
                ['id' => $existing],
                ['%d', '%s', '%s', '%s', '%s', '%s'],
                ['%d']
            );
        } else {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->insert(
                $table,
                $data,
                ['%d', '%s', '%s', '%s', '%s', '%s']
            );
        }
    }
    
    /**
     * Increment a numeric KPI
     */
    public function increment_kpi($user_id, $metric_name, $amount = 1) {
        $current = (int) $this->get_kpi($user_id, $metric_name);
        $new_value = $current + $amount;
        $this->set_kpi($user_id, $metric_name, $new_value);
        return $new_value;
    }
    
    /**
     * Get KPI history/trends
     */
    public function get_kpi_history($user_id, $metric_name, $days = 30) {
        global $wpdb;
        $table = $wpdb->prefix . 'vmo_kpi_history';
        
        // Create history table if needed
        $this->create_kpi_history_table();
        
        return $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$table} 
             WHERE user_id = %d AND metric = %s 
             AND recorded_at >= DATE_SUB(NOW(), INTERVAL %d DAY)
             ORDER BY recorded_at ASC",
            $user_id,
            $metric_name,
            $days
        ), ARRAY_A);
    }
    
    /**
     * Record KPI history for trending
     */
    public function record_kpi_history($user_id, $metric_name, $value) {
        global $wpdb;
        $table = $wpdb->prefix . 'vmo_kpi_history';
        
        $this->create_kpi_history_table();
        
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->insert(
            $table,
            [
                'user_id' => $user_id,
                'metric' => $metric_name,
                'value' => $value,
                'recorded_at' => current_time('mysql')
            ],
            ['%d', '%s', '%s', '%s']
        );
    }
    
    /**
     * Get business progress summary
     */
    public function get_progress_summary($user_id) {
        $kpis = $this->get_dashboard_kpis($user_id);
        
        $setup_complete = isset($kpis['setup']) ? count(array_filter($kpis['setup'], function($k) {
            return $k['type'] === 'boolean' && $k['value'] === '1';
        })) : 0;
        
        $total_setup_steps = isset($kpis['setup']) ? count($kpis['setup']) : 0;
        $setup_percentage = $total_setup_steps > 0 ? round(($setup_complete / $total_setup_steps) * 100) : 0;
        
        return [
            'setup_percentage' => $setup_percentage,
            'setup_complete_count' => $setup_complete,
            'setup_total_count' => $total_setup_steps,
            'website_status' => $this->get_kpi($user_id, 'website_status'),
            'business_stage' => $this->get_kpi($user_id, 'business_stage'),
            'next_milestone' => $this->get_kpi($user_id, 'next_milestone'),
            'total_leads' => (int) $this->get_kpi($user_id, 'total_leads'),
            'total_calls' => (int) $this->get_kpi($user_id, 'phone_calls_total'),
            'website_visitors' => (int) $this->get_kpi($user_id, 'website_visitors')
        ];
    }
    
    /**
     * Get today's activity summary
     */
    public function get_today_summary($user_id) {
        return [
            'new_leads' => (int) $this->get_kpi($user_id, 'new_leads_today'),
            'phone_calls' => (int) $this->get_kpi($user_id, 'phone_calls_today'),
            'website_visitors' => $this->get_todays_visitors($user_id),
            'emails_sent' => $this->get_todays_emails($user_id)
        ];
    }
    
    /**
     * Get this week's summary
     */
    public function get_week_summary($user_id) {
        return [
            'new_leads' => (int) $this->get_kpi($user_id, 'new_leads_week'),
            'phone_calls' => $this->get_weeks_calls($user_id),
            'website_visitors' => $this->get_weeks_visitors($user_id),
            'content_published' => $this->get_weeks_content($user_id)
        ];
    }
    
    /**
     * Helper methods for aggregated data
     */
    private function get_todays_visitors($user_id) {
        $today_start = date('Y-m-d 00:00:00', current_time('timestamp'));
        $visitors = $this->count_visitors_since($user_id, $today_start);

        if ($visitors > 0) {
            return $visitors;
        }

        return (int) $this->get_kpi($user_id, 'website_visitors');
    }
    
    private function get_todays_emails($user_id) {
        return (int) $this->get_kpi($user_id, 'emails_sent');
    }
    
    private function get_weeks_calls($user_id) {
        global $wpdb;
        $calls_table = $wpdb->prefix . 'vmo_phone_calls';
        
        if ($wpdb->get_var("SHOW TABLES LIKE '{$calls_table}'") != $calls_table) {
            return 0;
        }
        
        return (int) $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$calls_table} 
             WHERE user_id = %d 
             AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)",
            $user_id
        ));
    }
    
    private function get_weeks_visitors($user_id) {
        $week_start = date('Y-m-d H:i:s', strtotime('-7 days', current_time('timestamp')));
        $visitors = $this->count_visitors_since($user_id, $week_start);

        if ($visitors > 0) {
            return $visitors;
        }

        return (int) $this->get_kpi($user_id, 'website_visitors');
    }
    
    private function get_weeks_content($user_id) {
        return (int) $this->get_kpi($user_id, 'blog_posts') + (int) $this->get_kpi($user_id, 'social_posts');
    }

    private function count_visitors_since($user_id, $date_from) {
        global $wpdb;

        $interactions_table = $wpdb->prefix . 'vmo_contact_interactions';
        if ($wpdb->get_var("SHOW TABLES LIKE '{$interactions_table}'") !== $interactions_table) {
            return 0;
        }

        return (int) $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(DISTINCT COALESCE(contact_id, id))
             FROM {$interactions_table}
             WHERE user_id = %d
             AND interaction_type IN ('website_visit', 'page_view')
             AND created_at >= %s",
            $user_id,
            $date_from
        ));
    }
    
    /**
     * Create KPI table
     */
    private function create_kpi_table() {
        global $wpdb;
        $table = $wpdb->prefix . 'vmo_business_kpis';
        $charset_collate = $wpdb->get_charset_collate();
        
        $sql = "CREATE TABLE IF NOT EXISTS {$table} (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            user_id bigint(20) NOT NULL,
            metric varchar(100) NOT NULL,
            value text,
            label varchar(255),
            type varchar(50) DEFAULT 'text',
            category varchar(100) DEFAULT 'other',
            updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY  (id),
            KEY user_id (user_id),
            KEY metric (metric),
            KEY category (category)
        ) {$charset_collate};";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }
    
    /**
     * Create KPI history table for trends
     */
    private function create_kpi_history_table() {
        global $wpdb;
        $table = $wpdb->prefix . 'vmo_kpi_history';
        $charset_collate = $wpdb->get_charset_collate();
        
        $sql = "CREATE TABLE IF NOT EXISTS {$table} (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            user_id bigint(20) NOT NULL,
            metric varchar(100) NOT NULL,
            value text,
            recorded_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY  (id),
            KEY user_id (user_id),
            KEY metric (metric),
            KEY recorded_at (recorded_at)
        ) {$charset_collate};";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }

    /* ═══════════════════════════════════════════
     *  KPI Interpretation Layer
     * ═══════════════════════════════════════════ */

    /**
     * Interpret current KPIs and produce human-readable insights.
     * Returns an array of insight strings explaining what changed, why it matters,
     * and what the user should do about it.
     */
    public function interpret_kpis( $user_id ) {
        $kpis = $this->get_dashboard_kpis( $user_id );
        if ( empty( $kpis ) ) {
            return [ 'No KPI data available yet. Complete your business setup to start tracking metrics.' ];
        }

        $insights = [];
        $by_metric = [];
        foreach ( $kpis as $k ) {
            $by_metric[ $k['metric'] ] = $k;
        }

        // Traffic interpretation
        if ( isset( $by_metric['website_visitors'] ) ) {
            $visitors = (int) $by_metric['website_visitors']['value'];
            if ( $visitors === 0 ) {
                $insights[] = 'Your website has no recorded visitors yet. Publish your site and share it on social media to start getting traffic.';
            } elseif ( $visitors < 100 ) {
                $insights[] = "You have {$visitors} visitors — still early. Focus on SEO, social sharing, and content to grow this number.";
            } else {
                $insights[] = "Good traction with {$visitors} visitors. Monitor your conversion rate to turn traffic into leads.";
            }
        }

        // Conversion rate
        if ( isset( $by_metric['conversion_rate'] ) ) {
            $rate = (float) $by_metric['conversion_rate']['value'];
            if ( $rate > 0 && $rate < 2 ) {
                $insights[] = "Conversion rate is {$rate}% — below average. Review your calls-to-action and landing page design.";
            } elseif ( $rate >= 2 && $rate < 5 ) {
                $insights[] = "Conversion rate of {$rate}% is healthy. A/B test headlines and offers to push it higher.";
            } elseif ( $rate >= 5 ) {
                $insights[] = "Excellent conversion rate of {$rate}%! Your messaging resonates well with visitors.";
            }
        }

        // SEO score
        if ( isset( $by_metric['seo_score'] ) ) {
            $score = (int) $by_metric['seo_score']['value'];
            if ( $score < 50 ) {
                $insights[] = "SEO score is {$score}/100 — needs improvement. Run an SEO audit from the SEO tab.";
            } elseif ( $score < 80 ) {
                $insights[] = "SEO score is {$score}/100 — decent but can improve. Focus on meta descriptions and page speed.";
            } else {
                $insights[] = "Strong SEO score of {$score}/100. Maintain content freshness to stay ahead.";
            }
        }

        // Leads
        if ( isset( $by_metric['total_leads'] ) ) {
            $leads = (int) $by_metric['total_leads']['value'];
            $new_week = isset( $by_metric['new_leads_week'] ) ? (int) $by_metric['new_leads_week']['value'] : 0;
            if ( $leads === 0 ) {
                $insights[] = 'No leads captured yet. Ensure your website has visible contact forms and compelling offers.';
            } else {
                $insights[] = "{$leads} total leads, {$new_week} this week. " . ( $new_week > 0 ? 'Your acquisition is active.' : 'No new leads this week — consider outreach.' );
            }
        }

        // Content freshness
        if ( isset( $by_metric['blog_posts'] ) ) {
            $posts = (int) $by_metric['blog_posts']['value'];
            if ( $posts === 0 ) {
                $insights[] = 'No blog posts published. Regular content helps SEO and establishes authority.';
            }
        }

        // Business stage
        if ( isset( $by_metric['business_stage'] ) ) {
            $stage = $by_metric['business_stage']['value'];
            $insights[] = "Business stage: {$stage}. " . ( $stage === 'setup' ? 'Complete all setup tasks to move to launch phase.' : 'Keep building momentum.' );
        }

        return $insights;
    }

    /**
     * Get KPI trend for a specific metric (last 30 days).
     * Returns delta and direction.
     */
    public function get_kpi_trend( $user_id, $metric ) {
        global $wpdb;
        $table = $wpdb->prefix . 'vmo_kpi_history';
        if ( $wpdb->get_var( "SHOW TABLES LIKE '{$table}'" ) !== $table ) {
            return [ 'delta' => 0, 'direction' => 'flat', 'data_points' => 0 ];
        }

        $rows = $wpdb->get_results( $wpdb->prepare(
            "SELECT value, recorded_at FROM {$table} WHERE user_id = %d AND metric = %s AND recorded_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) ORDER BY recorded_at ASC",
            $user_id, $metric
        ) );

        if ( ! $rows || count( $rows ) < 2 ) {
            return [ 'delta' => 0, 'direction' => 'flat', 'data_points' => count( $rows ?: [] ) ];
        }

        $first = (float) $rows[0]->value;
        $last  = (float) end( $rows )->value;
        $delta = $last - $first;
        $direction = $delta > 0 ? 'up' : ( $delta < 0 ? 'down' : 'flat' );

        return [ 'delta' => round( $delta, 2 ), 'direction' => $direction, 'data_points' => count( $rows ) ];
    }

    /**
     * Record current KPI snapshot to history (called by cron or daily report).
     */
    public function snapshot_kpis( $user_id ) {
        global $wpdb;
        $this->create_kpi_history_table();
        $kpis = $this->get_dashboard_kpis( $user_id );
        $table = $wpdb->prefix . 'vmo_kpi_history';
        $now = current_time( 'mysql' );

        foreach ( $kpis as $k ) {
            if ( in_array( $k['type'], [ 'number', 'percentage', 'score' ], true ) ) {
                $wpdb->insert( $table, [
                    'user_id'     => $user_id,
                    'metric'      => $k['metric'],
                    'value'       => $k['value'],
                    'recorded_at' => $now,
                ] );
            }
        }
    }
}
