get_results( $wpdb->prepare( "SELECT DATE(post_date) as date, COUNT(*) as count FROM {$wpdb->posts} WHERE post_type = 'post' AND post_status = 'publish' AND post_date >= %s AND ID IN ( SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = 'ai_story_maker_generated_via' AND meta_value IN ('master_api', 'openai_api') ) GROUP BY DATE(post_date) ORDER BY date ASC", $three_months_ago ) ); // If no AI-generated posts found, get all published posts if ( empty( $ai_results ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Fallback story data for calendar $results = $wpdb->get_results( $wpdb->prepare( "SELECT DATE(post_date) as date, COUNT(*) as count FROM {$wpdb->posts} WHERE post_type = 'post' AND post_status = 'publish' AND post_date >= %s GROUP BY DATE(post_date) ORDER BY date ASC", $three_months_ago ) ); } else { $results = $ai_results; } $data = array(); foreach ( $results as $row ) { if ( $row && isset( $row->date, $row->count ) ) { $data[ $row->date ] = (int) $row->count; } } return $data; } /** * Generate calendar data */ private static function generate_calendar_data( $story_data ) { $calendar = array(); $month_labels = array(); // Store month labels by exact position $start_date = new DateTime( '-90 days' ); // 3 months ago $end_date = new DateTime( 'now' ); for ( $date = clone $start_date; $date <= $end_date; $date->add( new DateInterval( 'P1D' ) ) ) { $date_str = $date->format( 'Y-m-d' ); $week = $date->format( 'W' ); $day_of_week = $date->format( 'N' ) - 1; // 0-6 (Monday-Sunday) $is_first_day_of_month = $date->format( 'j' ) === '1'; if ( ! isset( $calendar[ $week ] ) ) { $calendar[ $week ] = array_fill( 0, 7, array( 'count' => 0, 'is_first_day' => false ) ); } $calendar[ $week ][ $day_of_week ] = array( 'count' => isset( $story_data[ $date_str ] ) ? $story_data[ $date_str ] : 0, 'is_first_day' => $is_first_day_of_month ); // Store month label for the exact position where first day appears if ( $is_first_day_of_month ) { $position_key = $week . '-' . $day_of_week; $month_labels[ $position_key ] = $date->format( 'M' ); // 3-letter month name } } return array( 'calendar' => $calendar, 'month_labels' => $month_labels ); } /** * Render the dashboard widget * * @param array $args { * @type bool $show_footer Whether to show the View Analytics footer link. Default true. * } */ public static function render_widget( $args = array() ) { $args = wp_parse_args( $args, array( 'show_footer' => true, ) ); $story_data = self::get_story_generation_data(); $calendar_result = self::generate_calendar_data( $story_data ); $calendar_data = $calendar_result['calendar']; $month_labels = $calendar_result['month_labels']; $total_stories = array_sum( $story_data ); ?>