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

/**
 * VMO Continuous Improvement Engine
 * 
 * Runs background scans and generates strategic recommendations to keep
 * the business roadmap and daily activities evolving based on real data.
 *
 * Features:
 * - Competitor monitoring (market shifts, new entrants)
 * - SEO health scans (keyword changes, new opportunities)
 * - Content freshness checks
 * - Lead & conversion trend analysis
 * - Roadmap/daily-activities auto-update recommendations
 * - Strategic report generation fed into Reports tab
 *
 * @package VMO_AI_Website_Builder
 * @since 1.0.0
 */

class VMO_Continuous_Improvement {

    private static $instance = null;

    public static function get_instance() {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Boot — register WP-Cron hooks
     */
    public function init() {
        // Schedule daily scan if not already scheduled
        if ( ! wp_next_scheduled( 'vmo_ci_daily_scan' ) ) {
            wp_schedule_event( time(), 'daily', 'vmo_ci_daily_scan' );
        }
        add_action( 'vmo_ci_daily_scan', [ $this, 'run_daily_scan' ] );

        // AJAX: manual trigger
        add_action( 'wp_ajax_vmo_trigger_ci_scan', [ $this, 'ajax_trigger_scan' ] );
        // AJAX: get latest CI report
        add_action( 'wp_ajax_vmo_get_ci_report', [ $this, 'ajax_get_report' ] );
    }

    /* ───────────────────────────────────
     *  Daily Scan (cron or manual AJAX)
     * ─────────────────────────────────── */

    public function run_daily_scan() {
        $users = get_users( [ 'meta_key' => 'vmo_business_roadmap', 'fields' => 'ID' ] );
        foreach ( $users as $user_id ) {
            // Respect plan policy for background ops
            $plan = get_user_meta( (int) $user_id, 'vmo_plan', true ) ?: 'free';
            if ( class_exists( 'VMO_Plan_Policy' ) ) {
                $policy = VMO_Plan_Policy::get_plan( $plan );
                if ( empty( $policy['background_ops_enabled'] ) ) continue;

                // Check frequency: monthly plans scan once/month, twice-monthly = every 15 days, weekly = weekly
                $last_scan = get_user_meta( (int) $user_id, '_vmo_ci_last_scan', true );
                $freq = $policy['background_ops_frequency'] ?? 'monthly';
                if ( $last_scan ) {
                    $elapsed_days = ( time() - strtotime( $last_scan ) ) / DAY_IN_SECONDS;
                    if ( $freq === 'monthly' && $elapsed_days < 28 ) continue;
                    if ( $freq === 'twice monthly' && $elapsed_days < 14 ) continue;
                    if ( $freq === 'weekly' && $elapsed_days < 6 ) continue;
                }
            }

            $this->scan_for_user( (int) $user_id );
            update_user_meta( (int) $user_id, '_vmo_ci_last_scan', current_time( 'mysql' ) );
        }
    }

    public function scan_for_user( $user_id ) {
        $results = [
            'scanned_at'    => current_time( 'mysql' ),
            'seo'           => $this->scan_seo( $user_id ),
            'competitors'   => $this->scan_competitors( $user_id ),
            'content'       => $this->scan_content_freshness( $user_id ),
            'leads'         => $this->scan_lead_trends( $user_id ),
            'recommendations' => [],
        ];

        // Generate recommendations from scan data
        $results['recommendations'] = $this->generate_recommendations( $user_id, $results );

        // Persist
        update_user_meta( $user_id, 'vmo_ci_latest_report', wp_json_encode( $results ) );

        // Store in activity log
        $this->log_activity( $user_id, 'ci_scan', 'Continuous improvement scan completed: ' . count( $results['recommendations'] ) . ' recommendations' );

        return $results;
    }

    /* ─── Sub-scanners ─── */

    private function scan_seo( $user_id ) {
        $seo_score = 0;
        if ( class_exists( 'VMO_KPI_Dashboard' ) ) {
            $kpi = new VMO_KPI_Dashboard();
            $score = method_exists( $kpi, 'get_kpi' ) ? $kpi->get_kpi( $user_id, 'seo_score' ) : 0;
            $seo_score = (int) $score;
        }
        return [
            'score'   => $seo_score,
            'status'  => $seo_score >= 80 ? 'good' : ( $seo_score >= 50 ? 'needs_work' : 'poor' ),
        ];
    }

    private function scan_competitors( $user_id ) {
        $data = get_user_meta( $user_id, 'vmo_competitors_data', true );
        if ( is_string( $data ) && ! empty( $data ) ) $data = json_decode( $data, true );
        $count = is_array( $data ) ? count( $data ) : 0;
        return [
            'monitored'   => $count,
            'last_update'  => get_user_meta( $user_id, 'vmo_competitors_last_scan', true ) ?: 'never',
        ];
    }

    private function scan_content_freshness( $user_id ) {
        global $wpdb;
        $last_post = $wpdb->get_var( $wpdb->prepare(
            "SELECT MAX(post_date) FROM {$wpdb->posts} WHERE post_author = %d AND post_status = 'publish' AND post_type IN ('post','page')",
            $user_id
        ));
        $days_since = $last_post ? (int) ( ( time() - strtotime( $last_post ) ) / DAY_IN_SECONDS ) : 999;
        return [
            'last_published' => $last_post ?: 'never',
            'days_since'     => $days_since,
            'status'         => $days_since <= 7 ? 'fresh' : ( $days_since <= 30 ? 'aging' : 'stale' ),
        ];
    }

    private function scan_lead_trends( $user_id ) {
        global $wpdb;
        $table = $wpdb->prefix . 'vmo_contacts';
        $week  = 0;
        $month = 0;
        if ( $wpdb->get_var( "SHOW TABLES LIKE '{$table}'" ) === $table ) {
            $week  = (int) $wpdb->get_var( $wpdb->prepare(
                "SELECT COUNT(*) FROM {$table} WHERE user_id = %d AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)", $user_id
            ));
            $month = (int) $wpdb->get_var( $wpdb->prepare(
                "SELECT COUNT(*) FROM {$table} WHERE user_id = %d AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)", $user_id
            ));
        }
        return [ 'leads_7d' => $week, 'leads_30d' => $month ];
    }

    /* ─── Recommendation Engine ─── */

    private function generate_recommendations( $user_id, $scan ) {
        $recs = [];

        // SEO
        if ( $scan['seo']['status'] === 'poor' ) {
            $recs[] = [ 'area' => 'SEO', 'priority' => 'high', 'text' => 'Your SEO score is below 50. Run a full SEO audit and optimize your page titles, meta descriptions, and heading structure.' ];
        } elseif ( $scan['seo']['status'] === 'needs_work' ) {
            $recs[] = [ 'area' => 'SEO', 'priority' => 'medium', 'text' => 'SEO score is ' . $scan['seo']['score'] . '/100. Focus on improving content quality and building backlinks.' ];
        }

        // Content
        if ( $scan['content']['status'] === 'stale' ) {
            $recs[] = [ 'area' => 'Content', 'priority' => 'high', 'text' => 'No new content published in over 30 days. Fresh content improves SEO and engagement. Consider publishing a blog post or updating existing pages.' ];
        } elseif ( $scan['content']['status'] === 'aging' ) {
            $recs[] = [ 'area' => 'Content', 'priority' => 'medium', 'text' => 'Content is aging (last publish ' . $scan['content']['days_since'] . ' days ago). Plan new content this week.' ];
        }

        // Competitors
        if ( $scan['competitors']['monitored'] === 0 ) {
            $recs[] = [ 'area' => 'Competitors', 'priority' => 'medium', 'text' => 'No competitors being monitored. Add competitors to stay informed about market movements.' ];
        }

        // Leads
        if ( $scan['leads']['leads_7d'] === 0 && $scan['leads']['leads_30d'] > 0 ) {
            $recs[] = [ 'area' => 'Leads', 'priority' => 'high', 'text' => 'No new leads this week but ' . $scan['leads']['leads_30d'] . ' last month. Review your acquisition channels.' ];
        } elseif ( $scan['leads']['leads_30d'] === 0 ) {
            $recs[] = [ 'area' => 'Leads', 'priority' => 'high', 'text' => 'No leads in 30 days. Consider running a promotion or improving your calls-to-action.' ];
        }

        // Store recommendations count as KPI
        if ( class_exists( 'VMO_KPI_Dashboard' ) ) {
            $kpi = new VMO_KPI_Dashboard();
            if ( method_exists( $kpi, 'set_kpi' ) ) {
                $kpi->set_kpi( $user_id, 'ci_recommendations', count( $recs ) );
            }
        }

        return $recs;
    }

    /* ─── Activity Logging ─── */

    private function log_activity( $user_id, $type, $description ) {
        global $wpdb;
        $table = $wpdb->prefix . 'vmo_activity_log';
        if ( $wpdb->get_var( "SHOW TABLES LIKE '{$table}'" ) !== $table ) return;
        $wpdb->insert( $table, [
            'user_id'     => $user_id,
            'action_type' => $type,
            'description' => $description,
            'created_at'  => current_time( 'mysql' ),
        ]);
    }

    /* ─── AJAX Handlers ─── */

    public function ajax_trigger_scan() {
        if ( ! current_user_can( 'read' ) ) wp_send_json_error( [ 'message' => 'Unauthorized' ], 403 );
        $result = $this->scan_for_user( get_current_user_id() );
        wp_send_json_success( $result );
    }

    public function ajax_get_report() {
        if ( ! current_user_can( 'read' ) ) wp_send_json_error( [ 'message' => 'Unauthorized' ], 403 );
        $report = get_user_meta( get_current_user_id(), 'vmo_ci_latest_report', true );
        if ( empty( $report ) ) {
            wp_send_json_success( [ 'message' => 'No scans yet. Run your first scan to get recommendations.' ] );
        }
        $decoded = json_decode( $report, true );
        wp_send_json_success( $decoded ?: [ 'raw' => $report ] );
    }

    /**
     * Cleanup on plugin deactivation
     */
    public static function deactivate() {
        wp_clear_scheduled_hook( 'vmo_ci_daily_scan' );
    }
}
