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

if (!class_exists('BOOSTIFY_DASHBOARD')):

    class BOOSTIFY_DASHBOARD
    {


        /**
         * Constructor.
         */
        public function __construct()
        {

            add_action('admin_menu', [$this, 'register_dashboard_menu_page']);
            add_action('admin_enqueue_scripts', [$this, 'enqueue_dashboard_admin_scripts']);
            add_action('admin_head', [$this, 'dashboard_admin_head_styles']);
            add_filter('plugin_action_links_' . BOOSTIFY_BLOG_AI_SLUG, [$this, 'dashboard_plugin_settings_link']);
            add_action('wp_ajax_boostify_dashboard_generate_content', [$this, 'dashboard_generate_content']);
            add_action('wp_ajax_boostify_dashboard_run_schedule', [$this, 'dashboard_manual_run']);
            add_action('wp_ajax_boostify_dashboard_get_range_data', [$this, 'dashboard_get_range_data']);
            add_action('wp_ajax_boostify_dashboard_reject_post', [$this, 'dashboard_reject_post']);
            add_action('admin_init', [$this, 'handle_schedule_form_submission']);
        }

        /**
         * Enqueue stylesheet and script for admin
         *
         * @param string $hook Current admin page hook.
         */
        function enqueue_dashboard_admin_scripts($hook)
        {
            // Only enqueue on dashboard pages
            if (strpos($hook, 'boostify-dashboard') === false) {
                return;
            }

            // Enqueue Google Fonts
            wp_enqueue_style(
                'boostify-dashboard-google-fonts',
                'https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap',
                array(),
                null
            );

            // Enqueue Dashboard Styles
            wp_enqueue_style(
                'boostify-dashboard-styles',
                BOOSTIFY_BLOG_AI_ASSETS_DIR_URL . 'boostify-dashboard/css/styles.css',
                array(),
                wp_rand()
            );
            wp_enqueue_style(
                'boostify-dashboard-fullcalendar',
                BOOSTIFY_BLOG_AI_ASSETS_DIR_URL . 'boostify-dashboard/css/fullcalendar.css',
                array(),
                wp_rand()
            );
            
            // Enqueue Cron Notification Styles
            wp_enqueue_style(
                'boostify-cron-notification-styles',
                BOOSTIFY_BLOG_AI_ASSETS_DIR_URL . 'boostify-dashboard/css/cron-notification.css',
                array('boostify-dashboard-styles'),
                wp_rand()
            );

            // Enqueue Chart.js - try local first, fallback to CDN
            $chart_js_url = BOOSTIFY_BLOG_AI_ASSETS_DIR_URL . 'boostify-dashboard/scripts/chart.js';
            wp_enqueue_script(
                'chart-js',
                $chart_js_url,
                array(),
                '4.5.0',
                true
            );
            
            // Add fallback to CDN if local file fails
            wp_add_inline_script('chart-js', "
                if (typeof Chart === 'undefined') {
                    var script = document.createElement('script');
                    script.src = 'https://cdn.jsdelivr.net/npm/chart.js@4.5.0/dist/chart.umd.min.js';
                    script.onload = function() {
                        console.log('Chart.js loaded from CDN');
                    };
                    document.head.appendChild(script);
                }
            ", 'before');

            // Enqueue Dashboard Scripts
            wp_enqueue_script(
                'boostify-dashboard-index',
                BOOSTIFY_BLOG_AI_ASSETS_DIR_URL . 'boostify-dashboard/scripts/index.global.min.js',
                array('jquery'),
                wp_rand(),
                true
            );
            wp_enqueue_script(
                'boostify-dashboard-scripts',
                BOOSTIFY_BLOG_AI_ASSETS_DIR_URL . 'boostify-dashboard/scripts/scripts.js',
                array('jquery', 'chart-js'),
                wp_rand(),
                true
            );
            wp_enqueue_script(
                'boostify-dashboard-charts',
                BOOSTIFY_BLOG_AI_ASSETS_DIR_URL . 'boostify-dashboard/scripts/dashboard-charts.js',
                array('jquery', 'chart-js'),
                wp_rand(),
                true
            );

            // Get dashboard data for localization
            $dashboard_data = $this->get_dashboard_data();
            
            // Localize script with WordPress data
            wp_localize_script(
                'boostify-dashboard-scripts',
                'boostify_blog_ai_dashboard_vars',
                array(
                    'pending_img'  => BOOSTIFY_BLOG_AI_ASSETS_DIR_URL . 'boostify-dashboard/img/pending-img1.png',
                    'ajaxurl'      => admin_url('admin-ajax.php'),
                    'nonce'        => wp_create_nonce('boostify_blog_ai_dashboard_nonce'),
                    'assets_url'   => BOOSTIFY_BLOG_AI_ASSETS_DIR_URL . 'boostify-dashboard/',
                    'plugin_url'   => BOOSTIFY_BLOG_AI_URL,
                    'dashboard_data' => array(
                        'weekStats' => $dashboard_data['week_stats'],
                        'dayStats' => $dashboard_data['day_stats'],
                        'monthStats' => $dashboard_data['month_stats'],
                        'yearStats' => $dashboard_data['year_stats'],
                        'totalPostsWeek' => (int) $dashboard_data['total_posts_week'],
                        'totalPostsYear' => (int) $dashboard_data['total_posts_year'],
                        'pendingPosts' => (int) $dashboard_data['pending_posts_week'],
                    ),
                    'weekStatsData' => isset($dashboard_data['week_stats']['current_week']) ? $dashboard_data['week_stats']['current_week'] : array(),
                    'pendingWeekStatsData' => $this->get_pending_posts_week_statistics(),
                )
            );

            // Add inline script to fix asset paths and handle notifications
            $inline_script = "
            jQuery(document).ready(function($) {
                // Fix all relative asset paths
                var assetsUrl = '" . esc_js(BOOSTIFY_BLOG_AI_ASSETS_DIR_URL . 'boostify-dashboard/') . "';
                $('img[src^=\"./assets/\"]').each(function() {
                    var src = $(this).attr('src');
                    var newSrc = src.replace('./assets/', assetsUrl);
                    $(this).attr('src', newSrc);
                });
                
                // Handle cron notification dismissal
                var cronNotification = $('#boostify-cron-notification');
                if (cronNotification.length) {
                    // Manual dismiss button
                    $('#boostify-cron-notification-close').on('click', function() {
                        cronNotification.fadeOut(300, function() {
                            $(this).remove();
                        });
                    });
                    
                    // Auto-dismiss cron notification after 1 minute
                    setTimeout(function() {
                        if (cronNotification.length) {
                            cronNotification.fadeOut(300, function() {
                                $(this).remove();
                            });
                        }
                    }, 60000); // 60 seconds = 1 minute
                }
                
                // Wait for Chart.js to be available, then initialize charts
                function initCharts() {
                    if (typeof Chart === 'undefined') {
                        console.log('Waiting for Chart.js to load...');
                        setTimeout(initCharts, 100);
                        return;
                    }
                    
                    console.log('Chart.js loaded, initializing charts...');
                    
                    // Initialize mini chart for Total Posts This Week
                    var miniChartCanvas = document.getElementById('total-posts-week-chart');
                    if (!miniChartCanvas) {
                        console.error('Canvas element #total-posts-week-chart not found');
                        return;
                    }
                    
                    if (typeof Chart !== 'undefined') {
                    // Set canvas dimensions first (before using chartHeight)
                    var chartHeight = 200;
                    var chartWidth = 100;
                    if (miniChartCanvas.parentElement && miniChartCanvas.parentElement.offsetWidth > 0) {
                        chartWidth = miniChartCanvas.parentElement.offsetWidth;
                    } else {
                        // Fallback: try to get computed width or use default
                        var computedWidth = window.getComputedStyle(miniChartCanvas).width;
                        if (computedWidth && computedWidth !== 'auto') {
                            chartWidth = parseInt(computedWidth) || 100;
                        }
                    }
                    miniChartCanvas.width = chartWidth;
                    miniChartCanvas.height = chartHeight;
                    console.log('Canvas dimensions set:', chartWidth, 'x', chartHeight);
                    
                    var weekData = boostify_blog_ai_dashboard_vars.weekStatsData || [];
                    var chartData = [];
                    
                    if (weekData.length > 0) {
                        chartData = weekData.map(function(stat) { return stat.posts || 0; });
                        console.log('Week data loaded:', chartData);
                    } else {
                        // Default data pattern if no data available - create wavy pattern
                        chartData = [2, 8, 3, 6, 4, 5, 3];
                        console.log('Using default chart data:', chartData);
                    }
                    
                    // Normalize data to create smooth wavy pattern within chart bounds
                    var maxValue = Math.max.apply(Math, chartData);
                    var minValue = Math.min.apply(Math, chartData);
                    var range = maxValue - minValue;
                    var totalSum = chartData.reduce(function(a, b) { return a + b; }, 0);
                    
                    // Handle cases where all values are the same or very similar
                    var normalizedData;
                    if (range === 0 || range < 0.1) {
                        // If all values are the same, create a subtle wavy pattern centered around the value
                        var baseY = chartHeight / 2; // Center of chart
                        normalizedData = chartData.map(function(val, index) {
                            // Create subtle wave: slight variation based on index
                            var waveOffset = Math.sin((index / chartData.length) * Math.PI * 2) * 15;
                            return baseY + waveOffset;
                        });
                    } else if (totalSum > 0 && maxValue > 0) {
                        // Scale data to fit nicely in the chart height
                        // Higher values should appear higher on chart (lower Y coordinate)
                        // Baseline for zeros: near bottom (chartHeight - 20)
                        // Peak for max value: near top (20)
                        var baseline = chartHeight - 20;
                        var peak = 20;
                        normalizedData = chartData.map(function(val) {
                            if (val === 0) {
                                return baseline; // Baseline near bottom
                            }
                            // Normalize: 0 to 1, then scale to peak-baseline range
                            var normalized = (val - minValue) / range;
                            // Higher normalized value = higher on chart = lower Y coordinate
                            return baseline - (normalized * (baseline - peak)); // Scale from baseline (bottom) to peak (top)
                        });
                    } else {
                        // All zeros - show flat line near bottom
                        normalizedData = chartData.map(function() { return chartHeight - 20; });
                    }
                    
                    var ctx = miniChartCanvas.getContext('2d');
                    
                    // Set dark background
                    ctx.fillStyle = '#16141a';
                    ctx.fillRect(0, 0, miniChartCanvas.width, miniChartCanvas.height);
                    
                    // Create gradient for filled area - darker translucent green
                    var gradientFill = ctx.createLinearGradient(0, 0, 0, chartHeight);
                    gradientFill.addColorStop(0, 'rgba(8, 184, 58, 0.3)');
                    gradientFill.addColorStop(0.5, 'rgba(8, 184, 58, 0.2)');
                    gradientFill.addColorStop(1, 'rgba(8, 184, 58, 0)');
                    
                    console.log('Creating chart with normalized data:', normalizedData);
                    
                    try {
                        new Chart(ctx, {
                            type: 'line',
                            data: {
                                labels: ['', '', '', '', '', '', ''],
                                datasets: [{
                                    data: normalizedData,
                                    borderColor: '#0ACA45',
                                    backgroundColor: gradientFill,
                                    borderWidth: 2.5,
                                    fill: true,
                                    tension: 0.5,
                                    pointRadius: 0,
                                    pointHoverRadius: 0,
                                    pointBorderWidth: 0,
                                }]
                            },
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            layout: {
                                padding: 0
                            },
                            plugins: {
                                legend: { display: false },
                                tooltip: { enabled: false }
                            },
                            scales: {
                                x: {
                                    display: false,
                                    grid: { display: false },
                                    ticks: { display: false }
                                },
                                y: {
                                    display: false,
                                    grid: { display: false },
                                    ticks: { display: false },
                                    min: 0,
                                    max: chartHeight
                                }
                            },
                            elements: {
                                line: {
                                    borderCapStyle: 'round',
                                    borderJoinStyle: 'round',
                                    tension: 0.5
                                },
                                point: {
                                    radius: 0
                                }
                            },
                            interaction: {
                                intersect: false,
                                mode: 'index'
                            }
                        }
                        });
                        console.log('Total posts chart created successfully');
                    } catch (error) {
                        console.error('Error creating total posts chart:', error);
                    }
                } else {
                    console.error('Chart.js not available');
                }
                
                // Initialize mini chart for Pending Posts This Week
                var pendingChartCanvas = document.getElementById('pending-posts-week-chart');
                if (!pendingChartCanvas) {
                    console.error('Canvas element #pending-posts-week-chart not found');
                    return;
                }
                
                if (typeof Chart !== 'undefined') {
                    // Set canvas dimensions first (before using pendingChartHeight)
                    var pendingChartHeight = 200;
                    var pendingChartWidth = 100;
                    if (pendingChartCanvas.parentElement && pendingChartCanvas.parentElement.offsetWidth > 0) {
                        pendingChartWidth = pendingChartCanvas.parentElement.offsetWidth;
                    } else {
                        // Fallback: try to get computed width or use default
                        var computedWidth = window.getComputedStyle(pendingChartCanvas).width;
                        if (computedWidth && computedWidth !== 'auto') {
                            pendingChartWidth = parseInt(computedWidth) || 100;
                        }
                    }
                    pendingChartCanvas.width = pendingChartWidth;
                    pendingChartCanvas.height = pendingChartHeight;
                    console.log('Pending canvas dimensions set:', pendingChartWidth, 'x', pendingChartHeight);
                    
                    var pendingWeekData = boostify_blog_ai_dashboard_vars.pendingWeekStatsData || [];
                    var pendingChartData = [];
                    
                    if (pendingWeekData.length > 0) {
                        pendingChartData = pendingWeekData.map(function(stat) { return stat.posts || 0; });
                    } else {
                        // Default data pattern if no data available - create wavy pattern
                        pendingChartData = [1, 5, 2, 4, 3, 4, 2];
                    }
                    
                    // Normalize data to create smooth wavy pattern within chart bounds
                    var pendingMaxValue = Math.max.apply(Math, pendingChartData);
                    var pendingMinValue = Math.min.apply(Math, pendingChartData);
                    var pendingRange = pendingMaxValue - pendingMinValue;
                    var pendingTotalSum = pendingChartData.reduce(function(a, b) { return a + b; }, 0);
                    
                    // Handle cases where all values are the same or very similar
                    var pendingNormalizedData;
                    if (pendingRange === 0 || pendingRange < 0.1) {
                        // If all values are the same, create a subtle wavy pattern centered around the value
                        var pendingBaseY = pendingChartHeight / 2; // Center of chart
                        pendingNormalizedData = pendingChartData.map(function(val, index) {
                            // Create subtle wave: slight variation based on index
                            var waveOffset = Math.sin((index / pendingChartData.length) * Math.PI * 2) * 15;
                            return pendingBaseY + waveOffset;
                        });
                    } else if (pendingTotalSum > 0 && pendingMaxValue > 0) {
                        // Scale data to fit nicely in the chart height
                        // Higher values should appear higher on chart (lower Y coordinate)
                        // Baseline for zeros: near bottom (pendingChartHeight - 20)
                        // Peak for max value: near top (20)
                        var pendingBaseline = pendingChartHeight - 20;
                        var pendingPeak = 20;
                        pendingNormalizedData = pendingChartData.map(function(val) {
                            if (val === 0) {
                                return pendingBaseline; // Baseline near bottom
                            }
                            // Normalize: 0 to 1, then scale to peak-baseline range
                            var normalized = (val - pendingMinValue) / pendingRange;
                            // Higher normalized value = higher on chart = lower Y coordinate
                            return pendingBaseline - (normalized * (pendingBaseline - pendingPeak)); // Scale from baseline (bottom) to peak (top)
                        });
                    } else {
                        // All zeros - show flat line near bottom
                        pendingNormalizedData = pendingChartData.map(function() { return pendingChartHeight - 20; });
                    }
                    
                    var pendingCtx = pendingChartCanvas.getContext('2d');
                    
                    // Set dark background
                    pendingCtx.fillStyle = '#16141a';
                    pendingCtx.fillRect(0, 0, pendingChartCanvas.width, pendingChartCanvas.height);
                    
                    // Create gradient for filled area - yellow/amber color scheme
                    var pendingGradientFill = pendingCtx.createLinearGradient(0, 0, 0, pendingChartHeight);
                    pendingGradientFill.addColorStop(0, 'rgba(242, 203, 4, 0.3)');
                    pendingGradientFill.addColorStop(0.5, 'rgba(242, 203, 4, 0.2)');
                    pendingGradientFill.addColorStop(1, 'rgba(242, 203, 4, 0)');
                    
                    console.log('Creating pending chart with normalized data:', pendingNormalizedData);
                    
                    try {
                        new Chart(pendingCtx, {
                            type: 'line',
                            data: {
                                labels: ['', '', '', '', '', '', ''],
                                datasets: [{
                                    data: pendingNormalizedData,
                                    borderColor: '#F2CB04',
                                    backgroundColor: pendingGradientFill,
                                    borderWidth: 2.5,
                                    fill: true,
                                    tension: 0.5,
                                    pointRadius: 0,
                                    pointHoverRadius: 0,
                                    pointBorderWidth: 0,
                                }]
                            },
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            layout: {
                                padding: 0
                            },
                            plugins: {
                                legend: { display: false },
                                tooltip: { enabled: false }
                            },
                            scales: {
                                x: {
                                    display: false,
                                    grid: { display: false },
                                    ticks: { display: false }
                                },
                                y: {
                                    display: false,
                                    grid: { display: false },
                                    ticks: { display: false },
                                    min: 0,
                                    max: pendingChartHeight
                                }
                            },
                            elements: {
                                line: {
                                    borderCapStyle: 'round',
                                    borderJoinStyle: 'round',
                                    tension: 0.5
                                },
                                point: {
                                    radius: 0
                                }
                            },
                            interaction: {
                                intersect: false,
                                mode: 'index'
                            }
                        }
                        });
                        console.log('Pending posts chart created successfully');
                    } catch (error) {
                        console.error('Error creating pending posts chart:', error);
                    }
                } else {
                    console.error('Chart.js not available for pending chart');
                }
                }
                
                // Initialize charts
                initCharts();
            });
            ";
            wp_add_inline_script('boostify-dashboard-scripts', $inline_script);
        }

        /**
         * Add custom styles for dashboard in admin head (minimal styles only)
         */
        function dashboard_admin_head_styles()
        {
            $screen = get_current_screen();
            if (strpos($screen->id, 'boostify-dashboard') === false) {
                return;
            }

            // Only critical WordPress admin overrides that need to be inline
            $inline_css = '
                /* Critical WordPress admin integration */
                .wrap > h1:first-child { 
                    margin: 0 !important; 
                }
                body.wp-admin { 
                    background: #010101 !important; 
                }
            ';
            
            wp_add_inline_style('boostify-dashboard-styles', $inline_css);
        }

        /**
         * Add plugin action links.
         * @param array  $links array of plugin actions.
         * 
         * return array
         */
        function dashboard_plugin_settings_link($links)
        {

            $url = esc_url(add_query_arg(
                'page',
                'boostify-dashboard',
                get_admin_url() . 'admin.php'
            ));
            $settings_link = "<a href='$url'>" . __('Dashboard', 'boostify-blog-ai') . '</a>';

            $new_links = [];
            $new_links[] = $settings_link;

            $links = array_merge($new_links, $links);
            return $links;
        }


        /**
         * Register Boostify Dashboard menu .
         */
        function register_dashboard_menu_page()
        {

            add_menu_page(__('Boostify', 'boostify-blog-ai'), 'Boostify', 'manage_options', 'boostify-dashboard', [$this, 'boostify_dashboard_page'], 'dashicons-dashboard', 85);
            //  add_submenu_page( 'boostify-dashboard', __( 'Add New Scheduled Post', 'boostify-blog-ai' ), __( 'Add New', 'boostify-blog-ai' ), 'manage_options', 'boostify-new-post', [ $this, 'dashboard_new_post_page']);
            add_submenu_page('boostify-dashboard', __('Schedule', 'boostify-blog-ai'), __('Schedule', 'boostify-blog-ai'), 'manage_options', 'boostify-dashboard-schedule', [$this, 'dashboard_schedule_page']);
        }

        /**
         * Display Boostify Dashboard menu page
         */
        function boostify_dashboard_page()
        {
            // Prepare data for the dashboard
            $dashboard_data = $this->get_dashboard_data();
            include BOOSTIFY_BLOG_AI_DIR . '/templates/boostify-dashboard-view.php';
        }

        /**
         * 
         */
        function dashboard_schedule_page()
        {

            $defaults = [
                'topics'  => '',
                'keywords'  => '',
                'quantity' => '',
                'duration' => '',
                'trust_ai' => false,
                'image' => false,
                'image_position' => ''

            ];
            $setting = get_option('boostify_blog_ai_schedule_settings', $defaults);

            include BOOSTIFY_BLOG_AI_DIR . '/templates/boostify-schedule-view.php';
        }

        function dashboard_new_post_page()
        {

            include BOOSTIFY_BLOG_AI_DIR . '/templates/add-new.php';
        }


        function dashboard_generate_content()
        {

            if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce(sanitize_text_field( wp_unslash ($_POST['nonce'])), 'boostify_blog_ai_dashboard_nonce')) {
                wp_die();
            }

            $data = array_map('sanitize_text_field', $_POST['data']);


            $api_key = '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';
            $boostify_api = new BOOSTIFY_BLOG_API($api_key);
            $content = $boostify_api->generate_content($data['topic'], $data['max_word_count'], $data['number_of_posts'], $data['keywords'], $data['meta_tags']);

            //  $content = "";

            if (!$content) {
                wp_send_json_error();
            }

            // $content = "";
            $number_of_posts = $data['number_of_posts'];
            $post_content = [];

            $posts = [];
            for ($i = 1; $i <= $number_of_posts; $i++) {
                $j = $i + 1;
                if ($j <= $number_of_posts) {
                    $post_content[] = $this->dashboard_get_string_between($content, "**Post $i:**",  "**Post $j:**");
                } else {
                    $ini = strpos($content, "**Post $i:**");
                    if ($ini !== false) {
                        $ini += strlen("**Post $i:**");
                    }

                    $post_content[] = trim(substr($content, $ini));
                }
            }
            foreach ($post_content as $i => $content) {

                $title = $this->dashboard_get_title($content);

                $meta  =  [];
                if ($data['meta_tags']  != 'false') {
                    $meta =  $this->dashboard_get_meta_tags($content);
                }
                $meta['boostify_post'] = 1;

                $post_content = $this->dashboard_clean_up_string($content); //trim( trim( $content,'---'));
                $post_content = str_replace('Content:**', '', $post_content);
                $post_content = str_replace('---', '', $post_content);



                $postID = $this->dashboard_create_post($title, $post_content, $data['post_date'], $meta);
                if ($postID) {
                    $posts[] = [
                        'title' => $title,
                        'link'  => get_edit_post_link($postID)
                    ];
                }
            }
            /*
            $posts = [
                [
                    'title' => 'Fluffy Felines: The Ultimate Comfort Companions',
                    'link'  => 'http://localhost/wordpress/wp-admin/post.php?post=114&amp;action=edit'
                ],
                [
                    'title' => 'The Allure of Luxurious Cat Fur',
                    'link'  => 'http://localhost/wordpress/wp-admin/post.php?post=115&amp;action=edit'
                ]
            ];
            */
            wp_send_json([
                'message' => 'Post Created',
                'posts' =>  $posts
            ]);
            wp_die();
        }

        function dashboard_get_string_between($string, $start, $end)
        {
            $string = ' ' . $string;
            $ini = strpos($string, $start);
            if ($ini == 0) return '';
            $ini += strlen($start);
            $len = strpos($string, $end, $ini) - $ini;
            return trim(substr($string, $ini, $len));
        }

        function dashboard_create_post($title, $content, $date, $status = 'published', $meta = [])
        {

            $post = [
                'post_title' => $title,
                'post_content' => $content,
                'post_status' => $status,
                'post_date' => $date,
                'meta_input' => $meta
            ];
            $post_id = wp_insert_post($post);


            if (!is_wp_error($post_id)) {
                return $post_id;
            } else {
                echo esc_html( $post_id->get_error_message() );
            }

            return false;
        }

        function dashboard_get_title(&$content)
        {
            $title_end = strpos($content, "\n");
            $title_line = substr($content, 0, $title_end);


            //     $title_line = trim(str_replace( "Title:",  '', $title_line ));
            $title = trim(trim(str_replace('Title:', '', $title_line), '*'));
            $content = str_replace($title_line, '', $content);

            return $this->dashboard_clean_up_string($title);
        }

        function dashboard_get_meta_tags(&$content)
        {

            $metas = [];

            $content = $this->dashboard_clean_up_string($content);
            $meta_start = strpos($content, "**Meta Tags:**");

            if ($meta_start  ==  false && strpos($content, "**Meta Tags**")) {

                $meta_start = strpos($content, "**Meta Tags**");
            } elseif (strpos($content, "Meta Tags:") !==  false) {
                $meta_start = strpos($content, "Meta Tags:");
            }

            if ($meta_start !== false) {
               

                $meta_content_end = null;
                if (strpos($content, '---') !==  false) {
                    $meta_content_end =  strpos($content, "---");
                }

                if (strpos($content, '**Content:**') !==  false) {
                    $meta_content_end = strpos($content, "**Content:**");
                }

                $meta_content = substr($content, $meta_start, $meta_content_end);

                // pre_print($meta_content_end);
                //   pre_print($meta_content);
                $content = str_replace($meta_content, '', $content);

                $meta_content = trim(str_replace("**Meta Tags:**",  '', $meta_content));
                $meta_content = trim(str_replace("*Meta Tags:*",  '', $meta_content));
                $meta_content = trim(str_replace("Meta Tags:",  '', $meta_content));


                $meta_title =  $this->dashboard_get_meta_title($meta_content);

                if ($meta_title) {
                    $metas['meta_title'] = $meta_title;
                }

                $meta_desc =  $this->dashboard_get_meta_desc($meta_content);
                if ($meta_desc) {
                    $metas['meta_description'] = $meta_desc;
                }
                /*
                $meta_content = trim(str_replace( "- **Meta Title:** ",  '', $meta_content ));
                $meta_content = trim(str_replace( " **Meta Title:** ",  '', $meta_content ));
                $meta_content = trim(str_replace( "- Title:",  '', $meta_content ));
                $meta_content = trim(str_replace( "- Meta Title:",  '', $meta_content ));
                $meta_content = trim(str_replace( "**Title:**",  '', $meta_content ));
                */
                /* $meta_desc_end = strpos($meta_content, "\n");
                $meta_desc_line = substr($meta_content, 0, $meta_desc_end );
            
                $meta_desc = str_replace( '- Meta Description: ','', $meta_desc_line );
                $meta_desc = str_replace( '**Meta Description:** ','', $meta_desc_line );
                $meta_desc = str_replace( '** Meta Description:** ','', $meta_desc_line );
                $meta_desc = str_replace( '- Description:','', $meta_desc_line );
                $meta_content = trim(str_replace( "- Meta Description:",  '', $meta_content ));
                $metas['meta_description'] = $meta_desc;

                $meta_content = trim(str_replace( $meta_desc_line,  '', $meta_content ));
                
                $meta_keywords_line = substr($meta_content, 0 );
                $meta_keywords = str_replace( '- Meta Keywords: ','', $meta_keywords_line );
                $metas[ 'meta_keywords'] = trim(trim($meta_keywords,'---'));
                */

                $meta_keywords =  $this->dashboard_get_meta_keywords($meta_content);
                if ($meta_keywords) {
                    $metas['meta_keywords'] = $meta_keywords;
                }
            } else {

                $meta_content_end = null;
                if (strpos($content, '---') !==  false) {
                    $meta_content_end =  strpos($content, "---");
                    $meta_content = substr($content, 0, $meta_content_end);
                    $content = str_replace($meta_content, '', $content);

                    $meta_title =  $this->dashboard_get_meta_title($meta_content);
                    if ($meta_title) {
                        $metas['meta_title'] = $meta_title;
                    }

                    $meta_desc =  $this->dashboard_get_meta_desc($meta_content);
                    if ($meta_desc) {
                        $metas['meta_description'] = $meta_desc;
                    }


                    $meta_keywords =  $this->dashboard_get_meta_keywords($meta_content);
                    if ($meta_keywords) {
                        $metas['meta_keywords'] = $meta_keywords;
                    }
                } else {
                    $meta_title =  $this->dashboard_get_meta_title($content);
                    if ($meta_title) {
                        $metas['meta_title'] = $meta_title;
                    }

                    $meta_desc =  $this->dashboard_get_meta_desc($content);
                    if ($meta_desc) {
                        $metas['meta_description'] = $meta_desc;
                    }


                    $meta_keywords =  $this->dashboard_get_meta_keywords($content);
                    if ($meta_keywords) {
                        $metas['meta_keywords'] = $meta_keywords;
                    }
                }


                // Description
                ///if(){}




            }
            return $metas;
        }

        function dashboard_clean_up_string($string)
        {
            $string = trim(trim(trim($string, '*'), '"'));

            return $string;
        }

        function dashboard_get_meta_title(&$content)
        {

            $meta_title_start = false;
            $meta_title_end = false;

            $content = $this->dashboard_clean_up_string($content);

            if (strpos($content, '- **Meta Title:**') !==  false) {
                $meta_title_start =  strpos($content, '- **Meta Title:**');
                $meta_title_end = strpos($content, "\n");
            }
            if (strpos($content, '- *Meta Title:*') !==  false) {
                $meta_title_start =  strpos($content, '- *Meta Title:*');
                $meta_title_end = strpos($content, "\n");
            } else if (strpos($content, "**Meta Title:**") !==  false) {
                $meta_title_start =  strpos($content, "**Meta Title:**");
                $meta_title_end = strpos($content, "\n");
            } else if (strpos($content, "- Title:") !==  false) {
                $meta_title_start =  strpos($content, "- Title:");
                $meta_title_end = strpos($content, "\n");
            } else if (strpos($content, "- Meta Title:") !==  false) {
                $meta_title_start =  strpos($content, "- Meta Title:");
                $meta_title_end = strpos($content, "\n");
            } else if (strpos($content, "**Title:**") !==  false) {
                $meta_title_start =  strpos($content, "**Title:**");
                $meta_title_end = strpos($content, "\n");
            } else if (strpos($content, "- **Title:**") !==  false) {
                $meta_title_start =  strpos($content, "**Title:**");
                $meta_title_end = strpos($content, "\n");
            } else if (strpos($content, "- *Title Tag:*") !==  false) {
                $meta_title_start =  strpos($content, "- *Title Tag:*");
                $meta_title_end = strpos($content, "\n");
            } else if (strpos($content, "- *Title:*") !==  false) {
                $meta_title_start =  strpos($content, "- *Title:*");
                $meta_title_end = strpos($content, "\n");
            } elseif (strpos($content, "- **Title Tag:**") !==  false) {
                $meta_title_start =  strpos($content, "- **Title Tag:**");
                $meta_title_end = strpos($content, "\n");
            }


            if ($meta_title_end < $meta_title_start) {
                $meta_title_end = strpos($content, "\n", $meta_title_start);
            }
            if ($meta_title_start !== false) {


                $meta_title_content = substr($content, $meta_title_start,  $meta_title_end - $meta_title_start);
                $content = str_replace($meta_title_content, '', $content);

                $meta_title_content = trim(str_replace("- **Meta Title:**",  '', $meta_title_content));
                $meta_title_content = trim(str_replace("**Meta Title:**",  '', $meta_title_content));
                $meta_title_content = trim(str_replace("*Meta Title:*",  '', $meta_title_content));
                $meta_title_content = trim(str_replace("- Title:",  '', $meta_title_content));
                $meta_title_content = trim(str_replace("- Meta Title:",  '', $meta_title_content));
                $meta_title_content = trim(str_replace("**Title:**",  '', $meta_title_content));
                $meta_title_content = trim(str_replace("- **Title:**",  '', $meta_title_content));
                $meta_title_content = trim(str_replace("- *Title Tag:*",  '', $meta_title_content));
                $meta_title_content = trim(str_replace("- **Title Tag:**",  '', $meta_title_content));
                $meta_title_content = trim(str_replace("- *Title:*",  '', $meta_title_content));


                return $meta_title_content;
            }
        }

        function dashboard_get_meta_desc(&$content)
        {

            $meta_desc_start = false;
            $meta_desc_end = false;
            $content = $this->dashboard_clean_up_string($content);

            if (strpos($content, '- Meta Description: ') !==  false) {
                $meta_desc_start =  strpos($content, '- Meta Description: ');
                $meta_desc_end = strpos($content, "\n");
            } else if (strpos($content, "**Meta Description:**") !==  false) {

                $meta_desc_start =  strpos($content, "**Meta Description:**");
                $meta_desc_end = strpos($content, "\n");
            } elseif (strpos($content, "** Meta Description:**") !==  false) {
                $meta_desc_start =  strpos($content, "** Meta Description:**");
                $meta_desc_end = strpos($content, "\n");
            } else if (strpos($content, "- Description:") !==  false) {
                $meta_desc_start =  strpos($content, "- Description:");
                $meta_desc_end = strpos($content, "\n");
            } else if (strpos($content, "- Meta Description:") !==  false) {
                $meta_desc_start =  strpos($content, "- Meta Description:");
                $meta_desc_end = strpos($content, "\n");
            } else if (strpos($content, "- **Description:**") !==  false) {
                $meta_desc_start =  strpos($content, "- **Description:**");
                $meta_desc_end = strpos($content, "\n");
            } else if (strpos($content, "- *Meta Description:*") !==  false) {
                $meta_desc_start =  strpos($content, "- *Meta Description:*");
                $meta_desc_end = strpos($content, "\n");
            } elseif (strpos($content, "- *Description:*") !==  false) {
                $meta_desc_start =  strpos($content, "- *Description:*");
                $meta_desc_end = strpos($content, "\n");
            }

            if (strpos($content, '---') !==  false) {
                $meta_desc_end =  strpos($content, "---");
            }


            if ($meta_desc_end < $meta_desc_start) {
                $meta_desc_end = false;
            }

            if ($meta_desc_start !== false) {
                $meta_desc_content = substr($content, $meta_desc_start, ($meta_desc_end === false) ? null : ($meta_desc_end - $meta_desc_start));



                $content = str_replace($meta_desc_content, '', $content);

                $meta_desc_content = trim(str_replace("- Meta Description:",  '', $meta_desc_content));
                $meta_desc_content = trim(str_replace("**Meta Description:**",  '', $meta_desc_content));
                $meta_desc_content = trim(str_replace("** Meta Description:**",  '', $meta_desc_content));
                $meta_desc_content = trim(str_replace("- Meta Description:",  '', $meta_desc_content));
                $meta_desc_content = trim(str_replace("- Description:",  '', $meta_desc_content));
                $meta_desc_content = trim(str_replace("- **Description:**",  '', $meta_desc_content));
                $meta_desc_content = trim(str_replace("- *Meta Description:*",  '', $meta_desc_content));
                $meta_desc_content = trim(str_replace("- *Description:*",  '', $meta_desc_content));

                return $meta_desc_content;
            }
        }

        function dashboard_get_meta_keywords(&$content)
        {
            $meta_keywords_start = false;
            if (strpos($content, '- Meta Keywords:') !==  false) {
                $meta_keywords_start =  strpos($content, '- Meta Keywords:');
                $meta_keywords_end = strpos($content, "\n");
            } elseif (strpos($content, '- *Keywords:*') !==  false) {
                $meta_keywords_start =  strpos($content, '- *Keywords:*');
                $meta_keywords_end = strpos($content, "\n");
            } elseif (strpos($content, '- Keywords') !==  false) {
                $meta_keywords_start =  strpos($content, '- Keywords');
                $meta_keywords_end = strpos($content, "\n");
            }
            if ($meta_keywords_start !== false) {
                $meta_keywords_content = substr($content, $meta_keywords_start, ($meta_keywords_end - $meta_keywords_start));
                $content = str_replace($meta_keywords_content, '', $content);

                $meta_keywords_content = trim(str_replace("- *Keywords:*",  '', $meta_keywords_content));
                $meta_keywords_content = trim(str_replace("- Meta Keywords:",  '', $meta_keywords_content));
                $meta_keywords_content = trim(str_replace("- Keywords",  '', $meta_keywords_content));

                return $meta_keywords_content;
            }
        }


        /**
         * Get all dashboard data
         */
        function get_dashboard_data()
        {
            return [
                'total_posts_week' => $this->get_posts_this_week(),
                'pending_posts_week' => $this->get_pending_posts_this_week(),
                'total_posts_year' => $this->get_total_posts_this_year(),
                'recent_posts' => $this->get_recent_boostify_posts(7),
                'pending_posts' => $this->get_pending_posts_for_approval(),
                'popular_topics' => $this->get_popular_topics_this_month(),
                'week_stats' => $this->get_week_statistics_with_comparison(),
                'day_stats' => $this->get_day_statistics_with_comparison(),
                'month_stats' => $this->get_month_statistics_with_comparison(),
                'year_stats' => $this->get_year_statistics_with_comparison(),
                'post_analytics' => $this->get_post_analytics_this_week()
            ];
        }

        /**
         * Get posts created this week
         */
        function get_posts_this_week()
        {
            $start_week = date('Y-m-d', strtotime('monday this week'));
            $end_week = date('Y-m-d', strtotime('sunday this week'));

            $args = [
                'post_type' => 'post',
                'post_status' => 'publish',
                'meta_key' => 'boostify_post',
                'meta_value' => '1',
                'date_query' => [
                    [
                        'after' => $start_week,
                        'before' => $end_week,
                        'inclusive' => true
                    ]
                ],
                'fields' => 'ids'
            ];

            $query = new WP_Query($args);
            return $query->found_posts;
        }

        /**
         * Get pending posts this week
         */
        function get_pending_posts_this_week()
        {
            $start_week = date('Y-m-d', strtotime('monday this week'));
            $end_week = date('Y-m-d', strtotime('sunday this week'));

            $args = [
                'post_type' => 'post',
                'post_status' => 'pending',
                'meta_key' => 'boostify_post',
                'meta_value' => '1',
                'date_query' => [
                    [
                        'after' => $start_week,
                        'before' => $end_week,
                        'inclusive' => true
                    ]
                ],
                'fields' => 'ids'
            ];

            $query = new WP_Query($args);
            return $query->found_posts;
        }

        /**
         * Get pending posts statistics per day for the week
         */
        function get_pending_posts_week_statistics()
        {
            $stats = [];
            for ($i = 6; $i >= 0; $i--) {
                $date = date('Y-m-d', strtotime("-$i days"));
                $day_name = date('D', strtotime("-$i days"));
                $day_num = date('d', strtotime("-$i days"));

                $args = [
                    'post_type' => 'post',
                    'post_status' => 'pending',
                    'meta_key' => 'boostify_post',
                    'meta_value' => '1',
                    'date_query' => [
                        [
                            'year' => date('Y', strtotime($date)),
                            'month' => date('m', strtotime($date)),
                            'day' => date('d', strtotime($date))
                        ]
                    ],
                    'fields' => 'ids'
                ];

                $query = new WP_Query($args);
                
                $stats[] = [
                    'day' => $day_num,
                    'day_name' => $day_name,
                    'posts' => $query->found_posts,
                    'date' => $date
                ];
            }

            return $stats;
        }

        /**
         * Get total posts this year
         */
        function get_total_posts_this_year()
        {
            $start_year = date('Y-01-01');
            $end_year = date('Y-12-31');

            $args = [
                'post_type' => 'post',
                'post_status' => 'publish',
                'meta_key' => 'boostify_post',
                'meta_value' => '1',
                'date_query' => [
                    [
                        'after' => $start_year,
                        'before' => $end_year,
                        'inclusive' => true
                    ]
                ],
                'fields' => 'ids'
            ];

            $query = new WP_Query($args);
            return $query->found_posts;
        }

        /**
         * Get recent boostify posts
         */
        function get_recent_boostify_posts($limit = 5)
        {
            $args = [
                'post_type' => 'post',
                'post_status' => 'publish',
                'meta_key' => 'boostify_post',
                'meta_value' => '1',
                'numberposts' => $limit,
                'orderby' => 'date',
                'order' => 'DESC'
            ];

            return get_posts($args);
        }

        /**
         * Get pending posts for approval
         */
        function get_pending_posts_for_approval($limit = 6)
        {
            $args = [
                'post_type' => 'post',
                'post_status' => 'pending',
                'meta_key' => 'boostify_post',
                'meta_value' => '1',
                'numberposts' => $limit,
                'orderby' => 'date',
                'order' => 'DESC'
            ];

            return get_posts($args);
        }

        /**
         * Get popular topics this month
         */
        function get_popular_topics_this_month()
        {
            $start_month = date('Y-m-01');
            $end_month = date('Y-m-t');

            // Get all posts from this month
            $args = [
                'post_type' => 'post',
                'post_status' => 'publish',
                'meta_key' => 'boostify_post',
                'meta_value' => '1',
                'date_query' => [
                    [
                        'after' => $start_month,
                        'before' => $end_month,
                        'inclusive' => true
                    ]
                ],
                'numberposts' => -1
            ];

            $posts = get_posts($args);
            $topics = [];

            // Extract topics/categories
            foreach ($posts as $post) {
                $categories = get_the_category($post->ID);
                foreach ($categories as $category) {
                    if (!isset($topics[$category->name])) {
                        $topics[$category->name] = [
                            'name' => $category->name,
                            'count' => 0,
                            'views' => 0
                        ];
                    }
                    $topics[$category->name]['count']++;

                    // Get post views if available
                    if (function_exists('boostify_blog_ai_get_post_views')) {
                        $topics[$category->name]['views'] += boostify_blog_ai_get_post_views($post->ID);
                    }
                }
            }

            // Sort by count and return top 5
            uasort($topics, function ($a, $b) {
                return $b['count'] - $a['count'];
            });

            return array_slice($topics, 0, 5);
        }

        /**
         * Get week statistics for chart
         */
        function get_week_statistics()
        {
            $stats = [];
            for ($i = 6; $i >= 0; $i--) {
                $date = date('Y-m-d', strtotime("-$i days"));
                $day_name = date('D', strtotime("-$i days"));
                $day_num = date('d', strtotime("-$i days"));

                $args = [
                    'post_type' => 'post',
                    'post_status' => 'publish',
                    'meta_key' => 'boostify_post',
                    'meta_value' => '1',
                    'date_query' => [
                        [
                            'year' => date('Y', strtotime($date)),
                            'month' => date('m', strtotime($date)),
                            'day' => date('d', strtotime($date))
                        ]
                    ]
                ];

                $query = new WP_Query($args);
                $posts = $query->posts;
                
                // Calculate total views for this day's posts
                $views = 0;
                if (function_exists('boostify_blog_ai_get_post_views')) {
                    foreach ($posts as $post) {
                        $views += boostify_blog_ai_get_post_views($post->ID);
                    }
                }

                $stats[] = [
                    'day' => $day_num,
                    'day_name' => $day_name,
                    'posts' => $query->found_posts,
                    'views' => $views,
                    'date' => $date
                ];
            }

            return $stats;
        }

        /**
         * Get week statistics with comparison - detailed breakdown
         */
        function get_week_statistics_with_comparison()
        {
            $current_week_stats = $this->get_week_statistics();
            $previous_week_stats = $this->get_previous_week_statistics();
            
            return [
                'current_week' => $current_week_stats,
                'previous_week' => $previous_week_stats,
                'type' => 'detailed'
            ];
        }

        /**
         * Get previous week statistics (7 days)
         */
        function get_previous_week_statistics()
        {
            $stats = [];
            for ($i = 13; $i >= 7; $i--) {
                $date = date('Y-m-d', strtotime("-$i days"));
                $day_name = date('D', strtotime("-$i days"));
                $day_num = date('d', strtotime("-$i days"));

                $args = [
                    'post_type' => 'post',
                    'post_status' => 'publish',
                    'meta_key' => 'boostify_post',
                    'meta_value' => '1',
                    'date_query' => [
                        [
                            'year' => date('Y', strtotime($date)),
                            'month' => date('m', strtotime($date)),
                            'day' => date('d', strtotime($date))
                        ]
                    ]
                ];

                $query = new WP_Query($args);
                $posts = $query->posts;
                
                // Calculate total views for this day's posts
                $views = 0;
                if (function_exists('boostify_blog_ai_get_post_views')) {
                    foreach ($posts as $post) {
                        $views += boostify_blog_ai_get_post_views($post->ID);
                    }
                }

                $stats[] = [
                    'day' => $day_num,
                    'day_name' => $day_name,
                    'posts' => $query->found_posts,
                    'views' => $views,
                    'date' => $date
                ];
            }

            return $stats;
        }

        /**
         * Get month statistics with comparison - detailed breakdown
         */
        function get_month_statistics_with_comparison()
        {
            $current_month_stats = $this->get_month_statistics_detailed();
            $previous_month_stats = $this->get_previous_month_statistics_detailed();
            
            return [
                'current_month' => $current_month_stats,
                'previous_month' => $previous_month_stats,
                'type' => 'detailed'
            ];
        }

        /**
         * Get detailed month statistics - every other day for compact display
         */
        function get_month_statistics_detailed()
        {
            $stats = [];
            $current_month_start = date('Y-m-01');
            $days_in_month = date('t');

            for ($day = 1; $day <= $days_in_month; $day += 2) { // Skip every other day for compact display
                $date = date('Y-m-d', strtotime($current_month_start . ' +' . ($day - 1) . ' days'));
                $day_name = date('D', strtotime($date));
                $day_num = date('d', strtotime($date));

                $args = [
                    'post_type' => 'post',
                    'post_status' => 'publish',
                    'meta_key' => 'boostify_post',
                    'meta_value' => '1',
                    'date_query' => [
                        [
                            'year' => date('Y', strtotime($date)),
                            'month' => date('m', strtotime($date)),
                            'day' => date('d', strtotime($date))
                        ]
                    ]
                ];

                $query = new WP_Query($args);
                $posts = $query->posts;
                
                $views = 0;
                if (function_exists('boostify_blog_ai_get_post_views')) {
                    foreach ($posts as $post) {
                        $views += boostify_blog_ai_get_post_views($post->ID);
                    }
                }

                $stats[] = [
                    'day' => $day_num,
                    'day_name' => $day_name,
                    'posts' => $query->found_posts,
                    'views' => $views,
                    'date' => $date
                ];
            }

            return $stats;
        }

        /**
         * Get previous month statistics - every other day for compact display
         */
        function get_previous_month_statistics_detailed()
        {
            $stats = [];
            $previous_month_start = date('Y-m-01', strtotime('-1 month'));
            $days_in_month = date('t', strtotime('-1 month'));

            for ($day = 1; $day <= $days_in_month; $day += 2) { // Skip every other day for compact display
                $date = date('Y-m-d', strtotime($previous_month_start . ' +' . ($day - 1) . ' days'));
                $day_name = date('D', strtotime($date));
                $day_num = date('d', strtotime($date));

                $args = [
                    'post_type' => 'post',
                    'post_status' => 'publish',
                    'meta_key' => 'boostify_post',
                    'meta_value' => '1',
                    'date_query' => [
                        [
                            'year' => date('Y', strtotime($date)),
                            'month' => date('m', strtotime($date)),
                            'day' => date('d', strtotime($date))
                        ]
                    ]
                ];

                $query = new WP_Query($args);
                $posts = $query->posts;
                
                $views = 0;
                if (function_exists('boostify_blog_ai_get_post_views')) {
                    foreach ($posts as $post) {
                        $views += boostify_blog_ai_get_post_views($post->ID);
                    }
                }

                $stats[] = [
                    'day' => $day_num,
                    'day_name' => $day_name,
                    'posts' => $query->found_posts,
                    'views' => $views,
                    'date' => $date
                ];
            }

            return $stats;
        }

        /**
         * Get year statistics with comparison - detailed breakdown
         */
        function get_year_statistics_with_comparison()
        {
            $current_year_stats = $this->get_year_statistics_detailed();
            $previous_year_stats = $this->get_previous_year_statistics_detailed();
            
            return [
                'current_year' => $current_year_stats,
                'previous_year' => $previous_year_stats,
                'type' => 'detailed'
            ];
        }

        /**
         * Get detailed year statistics - all 12 months
         */
        function get_year_statistics_detailed()
        {
            $stats = [];
            $current_year = date('Y');

            for ($month = 1; $month <= 12; $month++) {
                $month_start = date('Y-m-01', strtotime($current_year . '-' . $month . '-01'));
                $month_end = date('Y-m-t', strtotime($current_year . '-' . $month . '-01'));
                $month_name = date('M', strtotime($month_start));

                $args = [
                    'post_type' => 'post',
                    'post_status' => 'publish',
                    'meta_key' => 'boostify_post',
                    'meta_value' => '1',
                    'date_query' => [
                        [
                            'year' => $current_year,
                            'month' => $month
                        ]
                    ]
                ];

                $query = new WP_Query($args);
                $posts = $query->posts;
                
                $views = 0;
                if (function_exists('boostify_blog_ai_get_post_views')) {
                    foreach ($posts as $post) {
                        $views += boostify_blog_ai_get_post_views($post->ID);
                    }
                }

                $stats[] = [
                    'month' => $month,
                    'month_name' => $month_name,
                    'posts' => $query->found_posts,
                    'views' => $views,
                    'date' => $month_start
                ];
            }

            return $stats;
        }

        /**
         * Get previous year statistics - all 12 months
         */
        function get_previous_year_statistics_detailed()
        {
            $stats = [];
            $previous_year = date('Y', strtotime('-1 year'));

            for ($month = 1; $month <= 12; $month++) {
                $month_start = date('Y-m-01', strtotime($previous_year . '-' . $month . '-01'));
                $month_end = date('Y-m-t', strtotime($previous_year . '-' . $month . '-01'));
                $month_name = date('M', strtotime($month_start));

                $args = [
                    'post_type' => 'post',
                    'post_status' => 'publish',
                    'meta_key' => 'boostify_post',
                    'meta_value' => '1',
                    'date_query' => [
                        [
                            'year' => $previous_year,
                            'month' => $month
                        ]
                    ]
                ];

                $query = new WP_Query($args);
                $posts = $query->posts;
                
                $views = 0;
                if (function_exists('boostify_blog_ai_get_post_views')) {
                    foreach ($posts as $post) {
                        $views += boostify_blog_ai_get_post_views($post->ID);
                    }
                }

                $stats[] = [
                    'month' => $month,
                    'month_name' => $month_name,
                    'posts' => $query->found_posts,
                    'views' => $views,
                    'date' => $month_start
                ];
            }

            return $stats;
        }

        /**
         * Get day statistics with comparison - detailed breakdown
         */
        function get_day_statistics_with_comparison()
        {
            $current_day_stats = $this->get_day_statistics_detailed();
            $previous_day_stats = $this->get_previous_day_statistics_detailed();
            
            return [
                'current_day' => $current_day_stats,
                'previous_day' => $previous_day_stats,
                'type' => 'detailed'
            ];
        }

        /**
         * Get detailed day statistics - every 2 hours for compact display
         */
        function get_day_statistics_detailed()
        {
            $stats = [];
            $today = date('Y-m-d');

            for ($hour = 0; $hour < 24; $hour += 2) { // Every 2 hours for compact display
                $hour_start = $today . ' ' . sprintf('%02d:00:00', $hour);
                $hour_end = $today . ' ' . sprintf('%02d:59:59', $hour + 1);
                $hour_label = sprintf('%02d:00', $hour);

                $args = [
                    'post_type' => 'post',
                    'post_status' => 'publish',
                    'meta_key' => 'boostify_post',
                    'meta_value' => '1',
                    'date_query' => [
                        [
                            'after' => $hour_start,
                            'before' => $hour_end,
                            'inclusive' => true
                        ]
                    ]
                ];

                $query = new WP_Query($args);
                $posts = $query->posts;
                
                $views = 0;
                if (function_exists('boostify_blog_ai_get_post_views')) {
                    foreach ($posts as $post) {
                        $views += boostify_blog_ai_get_post_views($post->ID);
                    }
                }

                $stats[] = [
                    'hour' => $hour,
                    'hour_label' => $hour_label,
                    'posts' => $query->found_posts,
                    'views' => $views,
                    'date' => $hour_start
                ];
            }

            return $stats;
        }

        /**
         * Get previous day statistics - every 2 hours for compact display
         */
        function get_previous_day_statistics_detailed()
        {
            $stats = [];
            $yesterday = date('Y-m-d', strtotime('-1 day'));

            for ($hour = 0; $hour < 24; $hour += 2) { // Every 2 hours for compact display
                $hour_start = $yesterday . ' ' . sprintf('%02d:00:00', $hour);
                $hour_end = $yesterday . ' ' . sprintf('%02d:59:59', $hour + 1);
                $hour_label = sprintf('%02d:00', $hour);

                $args = [
                    'post_type' => 'post',
                    'post_status' => 'publish',
                    'meta_key' => 'boostify_post',
                    'meta_value' => '1',
                    'date_query' => [
                        [
                            'after' => $hour_start,
                            'before' => $hour_end,
                            'inclusive' => true
                        ]
                    ]
                ];

                $query = new WP_Query($args);
                $posts = $query->posts;
                
                $views = 0;
                if (function_exists('boostify_blog_ai_get_post_views')) {
                    foreach ($posts as $post) {
                        $views += boostify_blog_ai_get_post_views($post->ID);
                    }
                }

                $stats[] = [
                    'hour' => $hour,
                    'hour_label' => $hour_label,
                    'posts' => $query->found_posts,
                    'views' => $views,
                    'date' => $hour_start
                ];
            }

            return $stats;
        }

        /**
         * Get post analytics for this week
         */
        function get_post_analytics_this_week()
        {
            $start_week = date('Y-m-d', strtotime('monday this week'));
            $end_week = date('Y-m-d', strtotime('sunday this week'));

            $args = [
                'post_type' => 'post',
                'post_status' => 'publish',
                'meta_key' => 'boostify_post',
                'meta_value' => '1',
                'date_query' => [
                    [
                        'after' => $start_week,
                        'before' => $end_week,
                        'inclusive' => true
                    ]
                ],
                'numberposts' => 10,
                'orderby' => 'date',
                'order' => 'DESC'
            ];

            $posts = get_posts($args);
            $analytics = [];

            foreach ($posts as $post) {
                $views = 0;
                if (function_exists('boostify_blog_ai_get_post_views')) {
                    $views = boostify_blog_ai_get_post_views($post->ID);
                }

                $categories = get_the_category($post->ID);
                $category_names = array_map(function ($cat) {
                    return $cat->name;
                }, $categories);

                $analytics[] = [
                    'title' => $post->post_title,
                    'categories' => implode(', ', $category_names),
                    'views' => $views,
                    'date' => get_the_date('j M Y', $post->ID),
                    'edit_link' => get_edit_post_link($post->ID),
                    'trend' => $views > 100 ? 'up' : 'down' // Simple trend logic
                ];
            }

            return $analytics;
        }

        /**
         * Get Total number of boostify posts
         */
        function dashboard_get_total_bootisfy_posts()
        {

            $args = [
                'post_type'  => 'post',
                'meta_key'   => 'boostify_post',
                'meta_value' => '1',
                'fields'     => 'ids'
            ];
            $boostify_posts = new WP_Query($args);

            return $boostify_posts->found_posts;
        }


        /**
         * Retrieve last post by boostify.
         */
        function dashboard_get_last_post()
        {

            $last_posts = get_posts([
                'post_type'  => 'post',
                'post_status' => 'any',
                'meta_key'    => 'boostify_post',
                'meta_value'  => '1',
                'numberposts' =>  1,
                'orderby'     => 'date',
                'order'       => 'DESC',
            ]);

            if (count($last_posts) > 0) {
                return $last_posts[0];
            }

            return false;

            pre_print($last_post);
        }

        /**
         * Execute Manual Run
         */
        function dashboard_manual_run()
        {

            if ( ! isset( $_POST['nonce'] ) ||  !wp_verify_nonce( sanitize_text_field( wp_unslash ($_POST['nonce']) ), 'boostify_blog_ai_dashboard_nonce')) {
                wp_die();
            }

            $setting = boostify_blog_ai_get_schedule();

            if (!$setting['quantity']) {
                wp_send_json_error();
            }


            $topics = explode(',', $setting['topics']);
            if (count($topics) > 0) {
                $topic_index = rand(0, array_key_last($topics));
            } else {
                wp_send_json_error();
            }

            $api_key = boostify_blog_ai_openai_api_key();
            $boostify_api = new BOOSTIFY_BLOG_API($api_key);

            $topic = $topics[$topic_index];

            $max_word_count = apply_filters('boostify_blog_ai_post_word_count_max', 1000);
            $meta_tags = apply_filters('boostify_blog_ai_post_meta_tags', 'false');
            $keywords =  apply_filters('boostify_blog_ai_post_keywords', $setting['keywords']);
            $content = $boostify_api->generate_content($topic, $max_word_count, 1, $keywords, $meta_tags,  $setting['image'],  $setting['image_position']);


            if (!$content) {
                boostify_blog_ai_log('Content not generated', 'boostify_');
                return;
            }

            $post_status = 'pending';
            if (!$setting['trust_ai']) {
                $post_status = 'pending';
            }

            $title = boostify_blog_ai_get_title($content);

            $meta  =  [];
            if ($meta_tags != 'false') {
                $meta =  boostify_blog_ai_get_meta_tags($content);
            }
            $meta['boostify_post'] = 1;

            $post_content = boostify_blog_ai_clean_up_string($content);
            $post_content = str_replace('Content:**', '', $post_content);
            $post_content = str_replace('---', '', $post_content);


            if ( ! empty( $setting['image'] ) ) {
                $post_content = boostify_blog_ai_strip_placeholder_images( $post_content );
            }

            $postID = $this->dashboard_create_post( $title, $post_content, date( 'Y-m-d H:i:s' ), $post_status, $meta );

            if ( $postID && ! empty( $setting['image'] ) ) {
                $image_position = ! empty( $setting['image_position'] ) ? $setting['image_position'] : 'below';
                $image_prompt = ! empty( $title ) ? $title : $topic;
                $ai_image_url = $boostify_api->generate_image( $image_prompt );
                if ( $ai_image_url ) {
                    require_once ABSPATH . 'wp-admin/includes/media.php';
                    require_once ABSPATH . 'wp-admin/includes/file.php';
                    require_once ABSPATH . 'wp-admin/includes/image.php';
                    $tmp = download_url( $ai_image_url );
                    if ( ! is_wp_error( $tmp ) ) {
                        $ext = pathinfo( wp_parse_url( $ai_image_url, PHP_URL_PATH ), PATHINFO_EXTENSION );
                        $name = 'boostify-ai-' . $postID . ( $ext ? '.' . $ext : '.png' );
                        $file_array = array( 'name' => $name, 'tmp_name' => $tmp );
                        $attachment_id = media_handle_sideload( $file_array, $postID );
                        if ( ! is_wp_error( $attachment_id ) ) {
                            set_post_thumbnail( $postID, $attachment_id );
                            $local_url = wp_get_attachment_image_url( $attachment_id, 'full' );
                            if ( $local_url ) {
                                $image_html = '<figure><img src="' . esc_url( $local_url ) . '" alt="' . esc_attr( $title ) . '" /></figure>';
                                $post_content = boostify_blog_ai_insert_image_into_content( $post_content, $image_html, $image_position );
                                wp_update_post( array( 'ID' => $postID, 'post_content' => $post_content ) );
                            }
                        }
                        if ( file_exists( $tmp ) ) {
                            wp_delete_file( $tmp );
                        }
                    }
                }
            }

            if ($postID) {
                wp_send_json([
                    'message' => sprintf('<a href="%1$s" >Post</a> Created',  get_edit_post_link($postID)),
                    'post' =>  $postID,
                    'title' => $title,
                    'link'  => get_edit_post_link($postID),

                ]);
            }

            wp_die();
        }

        /**
         * Get statistics for a day split into 3-hour ranges
         */
        function get_day_time_range_statistics($date = null)
        {
            global $wpdb;
            if (!$date) {
                $date = date('Y-m-d');
            }
            $ranges = [
                ['00:00:00', '02:59:59'],
                ['03:00:00', '05:59:59'],
                ['06:00:00', '08:59:59'],
                ['09:00:00', '11:59:59'],
                ['12:00:00', '14:59:59'],
                ['15:00:00', '17:59:59'],
                ['18:00:00', '20:59:59'],
                ['21:00:00', '23:59:59'],
            ];
            $labels = [
                '00:00-03:00', '03:00-06:00', '06:00-09:00', '09:00-12:00',
                '12:00-15:00', '15:00-18:00', '18:00-21:00', '21:00-24:00'
            ];
            $result = [];
            // Get all post IDs for the day
            $args = [
                'post_type' => 'post',
                'post_status' => 'publish',
                'meta_key' => 'boostify_post',
                'meta_value' => '1',
                'date_query' => [
                    [
                        'year' => date('Y', strtotime($date)),
                        'month' => date('m', strtotime($date)),
                        'day' => date('d', strtotime($date))
                    ]
                ],
                'fields' => 'ids',
                'posts_per_page' => -1
            ];
            $post_ids = get_posts($args);
            $post_ids = array_map('intval', $post_ids);
            $post_ids_in = $post_ids ? implode(',', $post_ids) : '0';
            for ($i = 0; $i < count($ranges); $i++) {
                $start = $date . ' ' . $ranges[$i][0];
                $end = $date . ' ' . $ranges[$i][1];
                // Count posts published in this range
                $posts_in_range = get_posts([
                    'post_type' => 'post',
                    'post_status' => 'publish',
                    'meta_key' => 'boostify_post',
                    'meta_value' => '1',
                    'date_query' => [
                        [
                            'year' => date('Y', strtotime($date)),
                            'month' => date('m', strtotime($date)),
                            'day' => date('d', strtotime($date)),
                            'after' => $start,
                            'before' => $end,
                            'inclusive' => true
                        ]
                    ],
                    'fields' => 'ids',
                    'posts_per_page' => -1
                ]);
                $post_count = count($posts_in_range);
                // Count views in this range (by created_at)
                $views = 0;
         
                if ( !empty($post_ids) ) {
                    $post_ids_in    = implode( ', ', array_fill( 0, count( $post_ids ), '%d' ) );
                    $prepare_values = array_merge( array(  $start, $end ), $post_ids );
                  
                    $views = (int) $wpdb->get_var($wpdb->prepare(
                        "SELECT SUM(count) FROM {$wpdb->prefix}boostify_blog_ai_post_views WHERE post_id IN ($post_ids_in) AND created_at >= %s AND created_at <= %s",
                       $prepare_values
                    ));
                }
                $result[] = [
                    'label' => $labels[$i],
                    'posts' => $post_count,
                    'views' => $views
                ];
            }
            return $result;
        }

        function dashboard_get_range_data()
        {
            if ( ! isset( $_POST['nonce'] ) ||  !wp_verify_nonce( sanitize_text_field( wp_unslash ($_POST['nonce'])), 'boostify_blog_ai_dashboard_nonce')) {
                wp_die();
            }

            $range = sanitize_text_field( wp_unslash( $_POST['range'] ) );
            $data = [];

            // Support for time-range stats if a specific day is requested
            if ($range === 'single_day_time_range' && !empty($_POST['date'])) {
                $data = $this->get_day_time_range_statistics(sanitize_text_field( wp_unslash( $_POST['date'] ) ));
                wp_send_json_success($data);
            }

            // Support for grouped month ranges (for year view single month click)
            if ($range === 'month_grouped' && !empty($_POST['month']) && !empty($_POST['year'])) {
                $month = intval( sanitize_text_field( wp_unslash( $_POST['month'] ) ) );
                $year = intval( sanitize_text_field( wp_unslash( $_POST['year'] ) ) );
                $days = [];
                $days_in_month = date('t', strtotime("$year-$month-01"));
                for ($i = 1; $i <= $days_in_month; $i++) {
                    $date = sprintf('%04d-%02d-%02d', $year, $month, $i);
                    $days[] = $date;
                }
                $ranges = array_chunk($days, 6);
                $stats = [];
                foreach ($ranges as $range_days) {
                    $start = $range_days[0];
                    $end = end($range_days);
                    $args = [
                        'post_type' => 'post',
                        'post_status' => 'publish',
                        'meta_key' => 'boostify_post',
                        'meta_value' => '1',
                        'date_query' => [
                            [
                                'after' => $start . ' 00:00:00',
                                'before' => $end . ' 23:59:59',
                                'inclusive' => true
                            ]
                        ]
                    ];
                    $query = new WP_Query($args);
                    $posts = $query->posts;
                    $views = 0;
                    if (function_exists('boostify_blog_ai_get_post_views')) {
                        foreach ($posts as $post) {
                            $views += boostify_blog_ai_get_post_views($post->ID);
                        }
                    }
                    $stats[] = [
                        'label' => date('d M', strtotime($start)) . ' - ' . date('d M', strtotime($end)),
                        'posts' => $query->found_posts,
                        'views' => $views,
                        'start_date' => $start,
                        'end_date' => $end
                    ];
                }
                wp_send_json_success($stats);
            }

            switch ($range) {
                case 'day':
                    $data = $this->get_day_statistics();
                    break;
                case 'week':
                    $data = $this->get_week_statistics();
                    break;
                case 'month':
                    $data = $this->get_month_statistics();
                    break;
                case 'year':
                    $data = $this->get_year_statistics();
                    break;
                default:
                    $data = $this->get_week_statistics();
            }

            wp_send_json_success($data);
        }

        /**
         * Reject a pending post
         */
        function dashboard_reject_post()
        {
            if (  ! isset( $_POST['nonce'] ) || !wp_verify_nonce( sanitize_text_field( wp_unslash ( $_POST['nonce'] )), 'boostify_blog_ai_dashboard_nonce')) {
                wp_die();
            }

            $post_id = intval( sanitize_text_field( wp_unslash( $_POST['post_id'] ) ) );

            if (!$post_id || !current_user_can('delete_post', $post_id)) {
                wp_send_json_error('Permission denied');
            }

            // Move post to trash
            $result = wp_trash_post($post_id);

            if ($result) {
                wp_send_json_success([
                    'message' => 'Post moved to trash successfully',
                    'post_id' => $post_id
                ]);
            } else {
                wp_send_json_error('Failed to reject post');
            }
        }

        /**
         * Get day statistics
         */
        function get_day_statistics()
        {
            $today = date('Y-m-d');
            $yesterday = date('Y-m-d', strtotime('-1 day'));
            
            // Current day stats
            $current_args = [
                'post_type' => 'post',
                'post_status' => 'publish',
                'meta_key' => 'boostify_post',
                'meta_value' => '1',
                'date_query' => [
                    [
                        'year' => date('Y', strtotime($today)),
                        'month' => date('m', strtotime($today)),
                        'day' => date('d', strtotime($today))
                    ]
                ]
            ];

            $current_query = new WP_Query($current_args);
            $current_posts = $current_query->posts;
            $current_views = 0;
            if (function_exists('boostify_blog_ai_get_post_views')) {
                foreach ($current_posts as $post) {
                    $current_views += boostify_blog_ai_get_post_views($post->ID);
                }
            }

            // Previous day stats
            $previous_args = [
                'post_type' => 'post',
                'post_status' => 'publish',
                'meta_key' => 'boostify_post',
                'meta_value' => '1',
                'date_query' => [
                    [
                        'year' => date('Y', strtotime($yesterday)),
                        'month' => date('m', strtotime($yesterday)),
                        'day' => date('d', strtotime($yesterday))
                    ]
                ]
            ];

            $previous_query = new WP_Query($previous_args);
            $previous_posts = $previous_query->posts;
            $previous_views = 0;
            if (function_exists('boostify_blog_ai_get_post_views')) {
                foreach ($previous_posts as $post) {
                    $previous_views += boostify_blog_ai_get_post_views($post->ID);
                }
            }

            return [
                'current_period' => [
                    'label' => 'Today',
                    'posts' => $current_query->found_posts,
                    'views' => $current_views
                ],
                'previous_period' => [
                    'label' => 'Yesterday',
                    'posts' => $previous_query->found_posts,
                    'views' => $previous_views
                ]
            ];
        }

        /**
         * Get month statistics: current month vs previous month
         */
        function get_month_statistics()
        {
            $current_month_start = date('Y-m-01');
            $current_month_end = date('Y-m-t');
            $previous_month_start = date('Y-m-01', strtotime('-1 month'));
            $previous_month_end = date('Y-m-t', strtotime('-1 month'));

            // Current month stats
            $current_args = [
                'post_type' => 'post',
                'post_status' => 'publish',
                'meta_key' => 'boostify_post',
                'meta_value' => '1',
                'date_query' => [
                    [
                        'after' => $current_month_start . ' 00:00:00',
                        'before' => $current_month_end . ' 23:59:59',
                        'inclusive' => true
                    ]
                ]
            ];

            $current_query = new WP_Query($current_args);
            $current_posts = $current_query->posts;
            $current_views = 0;
            if (function_exists('boostify_blog_ai_get_post_views')) {
                foreach ($current_posts as $post) {
                    $current_views += boostify_blog_ai_get_post_views($post->ID);
                }
            }

            // Previous month stats
            $previous_args = [
                'post_type' => 'post',
                'post_status' => 'publish',
                'meta_key' => 'boostify_post',
                'meta_value' => '1',
                'date_query' => [
                    [
                        'after' => $previous_month_start . ' 00:00:00',
                        'before' => $previous_month_end . ' 23:59:59',
                        'inclusive' => true
                    ]
                ]
            ];

            $previous_query = new WP_Query($previous_args);
            $previous_posts = $previous_query->posts;
            $previous_views = 0;
            if (function_exists('boostify_blog_ai_get_post_views')) {
                foreach ($previous_posts as $post) {
                    $previous_views += boostify_blog_ai_get_post_views($post->ID);
                }
            }

            return [
                'current_period' => [
                    'label' => date('M Y', strtotime($current_month_start)),
                    'posts' => $current_query->found_posts,
                    'views' => $current_views
                ],
                'previous_period' => [
                    'label' => date('M Y', strtotime($previous_month_start)),
                    'posts' => $previous_query->found_posts,
                    'views' => $previous_views
                ]
            ];
        }

        /**
         * Get year statistics: current year vs previous year
         */
        function get_year_statistics()
        {
            $current_year_start = date('Y-01-01');
            $current_year_end = date('Y-12-31');
            $previous_year_start = date('Y-01-01', strtotime('-1 year'));
            $previous_year_end = date('Y-12-31', strtotime('-1 year'));

            // Current year stats
            $current_args = [
                'post_type' => 'post',
                'post_status' => 'publish',
                'meta_key' => 'boostify_post',
                'meta_value' => '1',
                'date_query' => [
                    [
                        'after' => $current_year_start,
                        'before' => $current_year_end,
                        'inclusive' => true
                    ]
                ]
            ];

            $current_query = new WP_Query($current_args);
            $current_posts = $current_query->posts;
            $current_views = 0;
            if (function_exists('boostify_blog_ai_get_post_views')) {
                foreach ($current_posts as $post) {
                    $current_views += boostify_blog_ai_get_post_views($post->ID);
                }
            }

            // Previous year stats
            $previous_args = [
                'post_type' => 'post',
                'post_status' => 'publish',
                'meta_key' => 'boostify_post',
                'meta_value' => '1',
                'date_query' => [
                    [
                        'after' => $previous_year_start,
                        'before' => $previous_year_end,
                        'inclusive' => true
                    ]
                ]
            ];

            $previous_query = new WP_Query($previous_args);
            $previous_posts = $previous_query->posts;
            $previous_views = 0;
            if (function_exists('boostify_blog_ai_get_post_views')) {
                foreach ($previous_posts as $post) {
                    $previous_views += boostify_blog_ai_get_post_views($post->ID);
                }
            }

            return [
                'current_period' => [
                    'label' => date('Y', strtotime($current_year_start)),
                    'posts' => $current_query->found_posts,
                    'views' => $current_views
                ],
                'previous_period' => [
                    'label' => date('Y', strtotime($previous_year_start)),
                    'posts' => $previous_query->found_posts,
                    'views' => $previous_views
                ]
            ];
        }

        /**
         * Handle schedule form submission via admin_init
         */
        function handle_schedule_form_submission()
        {
            // Check if we're on the schedule page and form was submitted
            if (isset($_GET['page']) && $_GET['page'] === 'boostify-dashboard-schedule' && 
                isset($_POST['save-changes']) && isset( $_POST['boostify_dashboard_nonce']) && wp_verify_nonce( sanitize_text_field( wp_unslash ($_POST['boostify_dashboard_nonce'])), 'boostify_dashboard_nonce')) {
                $settings = [
                    'topics'         => sanitize_text_field( wp_unslash( $_POST['topics'] ?? '' ) ),
                    'keywords'       => sanitize_text_field( wp_unslash( $_POST['keywords'] ?? '' ) ),
                    'quantity'       => sanitize_text_field( wp_unslash( $_POST['no-of-posts'] ?? '' ) ),
                    'duration'       => sanitize_text_field( wp_unslash( $_POST['per-post'] ?? '' ) ),
                    'trust_ai'       => !empty($_POST['trust-ai']),
                    'image'          => !empty($_POST['include-image']),
                    'image_position' => sanitize_text_field( wp_unslash( $_POST['image-position'] ?? '' ) )
                ];

                update_option('boostify_blog_ai_schedule_settings', $settings);
                
                // Redirect to prevent form resubmission
                wp_safe_redirect(add_query_arg('settings-updated', 'true', admin_url('admin.php?page=boostify-dashboard-schedule')));
                exit;
            }
        }
    }

endif;
