<?php
/**
 * DBA Master Calendar — Consolidated scheduling dashboard + stagger control
 *
 * Features:
 *   - Monthly calendar grid with color-coded per-bot post counts
 *   - Weekly totals per bot
 *   - 3-month forecast
 *   - Bot schedule cards with next-run cron info
 *   - POST STAGGER CONTROL: set 20–60 min between posts (all bots)
 *
 * @since 2.12.0
 * @package DamalionBlogAI
 */

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

class DBA_Master_Calendar {

    private static $instance = null;

    const BOTS = array(
        'core'    => array( 'label' => 'Core Damalion',  'color' => '#2563eb', 'icon' => '🔵', 'short' => 'Core' ),
        'newsbot' => array( 'label' => 'PE NewsBot',     'color' => '#ea580c', 'icon' => '🟠', 'short' => 'PE' ),
        'geobot'  => array( 'label' => 'GeoBot EU',      'color' => '#16a34a', 'icon' => '🟢', 'short' => 'Geo' ),
        'luxstrat'=> array( 'label' => 'LuxStrat',       'color' => '#9333ea', 'icon' => '🟣', 'short' => 'Lux' ),
        'latam'   => array( 'label' => 'LATAM',          'color' => '#dc2626', 'icon' => '🔴', 'short' => 'LAT' ),
        'eeurope' => array( 'label' => 'Eastern Europe', 'color' => '#0891b2', 'icon' => '🇪🇺', 'short' => 'EEU' ),
        'comfisc' => array( 'label' => 'Comfisc (FR)',   'color' => '#b45309', 'icon' => '🟤', 'short' => 'CFI' ),
    );

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

    private function __construct() {
        add_action( 'admin_menu', array( $this, 'register_menu' ), 12 );
        add_action( 'wp_ajax_dba_save_stagger', array( $this, 'ajax_save_stagger' ) );
    }

    public function register_menu() {
        add_submenu_page(
            'dba-settings',
            'Content Calendar',
            '📅 Master Calendar',
            'manage_options',
            'dba-master-calendar',
            array( $this, 'render_page' )
        );
    }

    /* ═══════════════════════════════════════════════════════════
     *  AJAX: Save stagger setting
     * ═══════════════════════════════════════════════════════════ */

    public function ajax_save_stagger() {
        check_ajax_referer( 'dba_admin_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( 'Forbidden' );

        $minutes = isset( $_POST['stagger_minutes'] ) ? intval( $_POST['stagger_minutes'] ) : 20;
        $minutes = max( 5, min( 60, $minutes ) );
        update_option( 'dba_post_stagger_minutes', $minutes );

        $preview = $this->build_stagger_preview( $minutes );
        wp_send_json_success( array(
            'minutes' => $minutes,
            'preview' => $preview,
            'message' => "Stagger set to {$minutes} minutes between posts for ALL bots.",
        ) );
    }

    private function build_stagger_preview( int $minutes ) {
        $schedules = $this->get_all_schedules();
        $lines = array();
        foreach ( self::BOTS as $bk => $bot ) {
            $sched = $schedules[ $bk ];
            if ( ! $sched['enabled'] ) continue;
            $ppr = $sched['posts_per_run'];
            if ( $ppr <= 1 ) {
                $lines[] = $bot['icon'] . ' ' . $bot['short'] . ': 1 post (no stagger needed)';
                continue;
            }
            $times = array();
            for ( $i = 0; $i < min( $ppr, 8 ); $i++ ) {
                $h = 9 + intdiv( $i * $minutes, 60 );
                $m = ( $i * $minutes ) % 60;
                $times[] = sprintf( '%02d:%02d', $h, $m );
            }
            $span = ( $ppr - 1 ) * $minutes;
            $lines[] = $bot['icon'] . ' ' . $bot['short'] . ": {$ppr} posts => "
                . implode( ', ', $times ) . " ({$span} min span)";
        }
        return implode( "\n", $lines );
    }

    /* ═══════════════════════════════════════════════════════════
     *  SCHEDULE READER
     * ═══════════════════════════════════════════════════════════ */

    private function get_all_schedules() {
        $schedules = array();

        $core_sched    = get_option( 'dba_schedule_settings', array() );
        $core_settings = get_option( 'dba_settings', array() );
        $schedules['core'] = array(
            'enabled'       => ! empty( $core_sched['enabled'] ),
            'posting_days'  => ! empty( $core_sched['posting_days'] ) ? $core_sched['posting_days'] : array( 'monday', 'wednesday', 'saturday' ),
            'posts_per_run' => ! empty( $core_settings['posts_per_run'] ) ? intval( $core_settings['posts_per_run'] ) : 5,
            'timezone'      => ! empty( $core_sched['timezone'] ) ? $core_sched['timezone'] : 'Europe/Luxembourg',
            'time_label'    => '06:00 UTC (07:00 CET)',
        );

        $pe = get_option( 'dba_pe_settings', array() );
        $schedules['newsbot'] = array(
            'enabled'       => ! empty( $pe['enabled'] ),
            'posting_days'  => ! empty( $pe['posting_days'] ) ? $pe['posting_days'] : array( 'monday', 'wednesday', 'friday' ),
            'posts_per_run' => ! empty( $pe['posts_per_day'] ) ? intval( $pe['posts_per_day'] ) + 1 : 7,
            'timezone'      => 'America/New_York',
            'time_label'    => '15:00 UTC (10:00 AM NY)',
        );

        $geo_days = array(); $geo_posts = 0; $geo_enabled = false; $geo_countries = array();
        if ( class_exists( 'DBA_GeoBot_Registry' ) ) {
            foreach ( DBA_GeoBot_Registry::get_countries() as $key => $config ) {
                $s = get_option( $config['settings_option'], array() );
                if ( ! empty( $s['enabled'] ) ) {
                    $geo_enabled = true;
                    $days = ! empty( $s['posting_days'] ) ? $s['posting_days'] : $config['default_posting_days'];
                    foreach ( $days as $d ) { if ( ! in_array( $d, $geo_days, true ) ) $geo_days[] = $d; }
                    $ppr = ! empty( $s['posts_per_run'] ) ? intval( $s['posts_per_run'] ) : $config['default_posts_per_run'];
                    $geo_countries[ $key ] = array( 'label' => $config['label'] ?? ucfirst( $key ), 'posts_per_run' => $ppr, 'posting_days' => $days );
                    $geo_posts += $ppr;
                }
            }
        }
        if ( empty( $geo_days ) ) $geo_days = array( 'saturday', 'sunday' );
        $schedules['geobot'] = array(
            'enabled' => $geo_enabled, 'posting_days' => $geo_days, 'posts_per_run' => $geo_posts,
            'timezone' => 'Europe/Paris', 'time_label' => '07:00-09:00 UTC', 'countries' => $geo_countries,
        );

        $lux = get_option( 'dba_luxstrat_settings', array() );
        $schedules['luxstrat'] = array(
            'enabled' => ! empty( $lux['enabled'] ), 'posting_days' => array( 'sunday' ),
            'posts_per_run' => 1, 'timezone' => 'Europe/Luxembourg', 'time_label' => '05:00 CET (Sunday)',
        );

        $lat = get_option( 'dba_latam_settings', array() );
        $latam_ppr = max( 1, absint( $lat['posts_per_run'] ?? 3 ) );
        $schedules['latam'] = array(
            'enabled' => ! empty( $lat['enabled'] ), 'posting_days' => array( 'saturday', 'sunday' ),
            'posts_per_run' => $latam_ppr, 'timezone' => 'Europe/Luxembourg', 'time_label' => '07:00 CET (Sat/Sun)',
        );

        $ee = get_option( 'dba_eeurope_settings', array() );
        $ee_ppr = max( 1, absint( $ee['posts_per_run'] ?? 3 ) );
        $ee_days = ! empty( $ee['posting_days'] ) ? (array) $ee['posting_days'] : array( 'thursday', 'friday' );
        $ee_hour = isset( $ee['cron_hour'] ) ? intval( $ee['cron_hour'] ) : 9;
        $schedules['eeurope'] = array(
            'enabled' => ! empty( $ee['enabled'] ), 'posting_days' => $ee_days,
            'posts_per_run' => $ee_ppr, 'timezone' => 'Europe/Luxembourg',
            'time_label' => sprintf( '%02d:00 CET (%s)', $ee_hour, implode( '/', array_map( function($d){ return substr(ucfirst($d),0,3); }, $ee_days ) ) ),
        );

        // Comfisc (Comptabilité & Fiscalité — FR)
        $cfi_enabled = false; $cfi_days = array(); $cfi_posts = 0; $cfi_time = '09:00 CET';
        if ( class_exists( 'DBA_Comfisc_Loader' ) ) {
            $cfi_langs = DBA_Comfisc_Loader::get_languages();
            foreach ( $cfi_langs as $lang => $lang_config ) {
                $ls = get_option( 'dba_comfisc_' . $lang . '_settings', array() );
                if ( ! empty( $ls['enabled'] ) ) $cfi_enabled = true;
                $day_map = array( 1 => 'monday', 2 => 'tuesday', 3 => 'wednesday', 4 => 'thursday', 5 => 'friday', 6 => 'saturday', 7 => 'sunday' );
                $sched_days_n = $lang_config['schedule']['days'] ?? array();
                foreach ( $sched_days_n as $dn ) {
                    $dname = $day_map[ $dn ] ?? '';
                    if ( $dname && ! in_array( $dname, $cfi_days, true ) ) $cfi_days[] = $dname;
                }
                $cfi_posts++;
                $sh = $lang_config['schedule']['hour'] ?? 9;
                $cfi_time = sprintf( '%02d:00 CET (%s)', $sh, implode( '/', array_map( function($d){ return substr(ucfirst($d),0,3); }, $cfi_days ) ) );
            }
        }
        if ( empty( $cfi_days ) ) $cfi_days = array( 'monday', 'wednesday', 'friday' );
        $schedules['comfisc'] = array(
            'enabled' => $cfi_enabled, 'posting_days' => $cfi_days,
            'posts_per_run' => max( 1, $cfi_posts ), 'timezone' => 'Europe/Luxembourg',
            'time_label' => $cfi_time,
        );

        return $schedules;
    }

    /* ═══════════════════════════════════════════════════════════
     *  MONTH MAP + TOTALS
     * ═══════════════════════════════════════════════════════════ */

    private function build_month_map( int $year, int $month, array $schedules ) {
        $dim = cal_days_in_month( CAL_GREGORIAN, $month, $year );
        $map = array();
        for ( $d = 1; $d <= $dim; $d++ ) {
            $ds = sprintf( '%04d-%02d-%02d', $year, $month, $d );
            $dn = strtolower( date( 'l', strtotime( $ds ) ) );
            $map[ $ds ] = array();
            foreach ( $schedules as $bk => $sc ) {
                if ( ! $sc['enabled'] ) continue;
                if ( in_array( $dn, $sc['posting_days'], true ) )
                    $map[ $ds ][ $bk ] = $sc['posts_per_run'];
            }
        }
        return $map;
    }

    private function calc_weekly_totals( array $mm ) {
        $weeks = array();
        foreach ( $mm as $ds => $bots ) {
            $wk = 'W' . date( 'W', strtotime( $ds ) );
            if ( ! isset( $weeks[$wk] ) ) {
                $weeks[$wk] = array( '_total' => 0, '_dates' => array() );
                foreach ( array_keys( self::BOTS ) as $bk ) $weeks[$wk][$bk] = 0;
            }
            $weeks[$wk]['_dates'][] = $ds;
            foreach ( $bots as $bk => $c ) { $weeks[$wk][$bk] += $c; $weeks[$wk]['_total'] += $c; }
        }
        return $weeks;
    }

    private function calc_monthly_totals( array $mm ) {
        $t = array( '_total' => 0 );
        foreach ( array_keys( self::BOTS ) as $bk ) $t[$bk] = 0;
        foreach ( $mm as $bots ) {
            foreach ( $bots as $bk => $c ) { $t[$bk] += $c; $t['_total'] += $c; }
        }
        return $t;
    }

    /* ═══════════════════════════════════════════════════════════
     *  RENDER PAGE
     * ═══════════════════════════════════════════════════════════ */

    public function render_page() {
        $schedules   = $this->get_all_schedules();
        $stagger_min = intval( get_option( 'dba_post_stagger_minutes', 20 ) );
        $stagger_preview = $this->build_stagger_preview( $stagger_min );

        $cur_year  = isset( $_GET['cal_year'] )  ? intval( $_GET['cal_year'] )  : intval( date( 'Y' ) );
        $cur_month = isset( $_GET['cal_month'] ) ? intval( $_GET['cal_month'] ) : intval( date( 'n' ) );
        if ( $cur_month < 1 )  { $cur_month = 12; $cur_year--; }
        if ( $cur_month > 12 ) { $cur_month = 1;  $cur_year++; }

        $prev_m = $cur_month - 1; $prev_y = $cur_year;
        if ( $prev_m < 1 ) { $prev_m = 12; $prev_y--; }
        $next_m = $cur_month + 1; $next_y = $cur_year;
        if ( $next_m > 12 ) { $next_m = 1; $next_y++; }

        $month_map     = $this->build_month_map( $cur_year, $cur_month, $schedules );
        $weekly_totals = $this->calc_weekly_totals( $month_map );
        $month_totals  = $this->calc_monthly_totals( $month_map );
        $month_label   = date( 'F Y', mktime( 0, 0, 0, $cur_month, 1, $cur_year ) );
        $base_url      = admin_url( 'admin.php?page=dba-master-calendar' );
        $prev_url      = add_query_arg( array( 'cal_year' => $prev_y, 'cal_month' => $prev_m ), $base_url );
        $next_url      = add_query_arg( array( 'cal_year' => $next_y, 'cal_month' => $next_m ), $base_url );
        $today_str     = date( 'Y-m-d' );
        $first_dow     = ( date( 'w', mktime( 0, 0, 0, $cur_month, 1, $cur_year ) ) + 6 ) % 7;
        $days_in_month = cal_days_in_month( CAL_GREGORIAN, $cur_month, $cur_year );

        // Build JS bot data for preview
        $js_bots = array();
        foreach ( self::BOTS as $bk => $bot ) {
            $sc = $schedules[$bk];
            $js_bots[] = array( 'key' => $bk, 'icon' => $bot['icon'], 'short' => $bot['short'],
                                'ppr' => $sc['posts_per_run'], 'enabled' => $sc['enabled'] );
        }
        ?>
        <div class="wrap">
        <h1 style="display:flex;align-items:center;gap:10px;"><span style="font-size:28px;">📅</span> Master Content Calendar</h1>

        <style>
            .dba-cal-wrap{max-width:1200px}
            .dba-cal-nav{display:flex;align-items:center;justify-content:space-between;margin:20px 0 16px}
            .dba-cal-nav h2{margin:0;font-size:22px;font-weight:600}
            .dba-nav-btn{text-decoration:none;padding:6px 14px;background:#f0f0f0;border-radius:6px;color:#1d2327;font-weight:500;border:1px solid #ddd}
            .dba-nav-btn:hover{background:#e0e0e0}
            .dba-legend{display:flex;flex-wrap:wrap;gap:16px;margin-bottom:18px;padding:12px 16px;background:#f9fafb;border:1px solid #e5e7eb;border-radius:8px}
            .dba-legend-item{display:flex;align-items:center;gap:6px;font-size:13px}
            .dba-legend-dot{width:12px;height:12px;border-radius:3px;display:inline-block}
            .dba-legend-on{font-size:11px;padding:2px 6px;border-radius:3px;font-weight:600;background:#dcfce7;color:#166534}
            .dba-legend-off{font-size:11px;padding:2px 6px;border-radius:3px;font-weight:600;background:#fee2e2;color:#991b1b}
            .dba-cal-grid{display:grid;grid-template-columns:repeat(7,1fr);gap:1px;background:#e5e7eb;border:1px solid #e5e7eb;border-radius:8px;overflow:hidden}
            .dba-cal-header{background:#f3f4f6;padding:8px;text-align:center;font-weight:600;font-size:12px;color:#6b7280;text-transform:uppercase;letter-spacing:.5px}
            .dba-cal-cell{background:#fff;min-height:90px;padding:6px 8px;position:relative}
            .dba-cal-cell.dba-empty{background:#fafafa}
            .dba-cal-cell.dba-today{background:#eff6ff;box-shadow:inset 0 0 0 2px #3b82f6}
            .dba-cal-date{font-size:13px;font-weight:600;color:#374151;margin-bottom:4px}
            .dba-cal-date.dba-today-num{color:#2563eb}
            .dba-cal-date.dba-weekend{color:#9ca3af}
            .dba-cal-pills{display:flex;flex-wrap:wrap;gap:3px}
            .dba-cal-pill{display:inline-flex;align-items:center;gap:3px;padding:2px 6px;border-radius:4px;font-size:10px;font-weight:700;color:#fff;line-height:1.4}
            .dba-cal-pill span.num{font-size:11px}
            .dba-cal-day-total{position:absolute;bottom:4px;right:6px;font-size:10px;color:#9ca3af;font-weight:600}
            .dba-summary-row{display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-top:24px}
            .dba-summary-box{background:#fff;border:1px solid #e5e7eb;border-radius:8px;overflow:hidden}
            .dba-summary-box h3{margin:0;padding:12px 16px;background:#f9fafb;border-bottom:1px solid #e5e7eb;font-size:14px;font-weight:600}
            .dba-summary-table{width:100%;border-collapse:collapse;font-size:13px}
            .dba-summary-table th{text-align:left;padding:8px 12px;font-weight:600;color:#6b7280;border-bottom:1px solid #f3f4f6;font-size:11px;text-transform:uppercase}
            .dba-summary-table td{padding:8px 12px;border-bottom:1px solid #f3f4f6}
            .dba-summary-table tr:last-child td{border-bottom:none}
            .dba-total-row td{font-weight:700;background:#f9fafb;border-top:2px solid #e5e7eb}
            .dba-bot-tag{display:inline-block;padding:2px 8px;border-radius:4px;font-size:11px;font-weight:600;color:#fff}
            .dba-num{text-align:center;font-weight:600;font-variant-numeric:tabular-nums}
            .dba-sched-cards{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:12px;margin-top:24px}
            .dba-sched-card{background:#fff;border:1px solid #e5e7eb;border-radius:8px;padding:14px;border-left:4px solid}
            .dba-sched-card h4{margin:0 0 8px;font-size:14px}
            .dba-sched-card p{margin:3px 0;font-size:12px;color:#6b7280}
            .dba-sched-card .dba-val{color:#111827;font-weight:600}
            .dba-stagger-box{background:#fff;border:2px solid #f59e0b;border-radius:10px;padding:20px;margin-bottom:24px}
            .dba-stagger-box h3{margin:0 0 12px;font-size:16px;color:#92400e}
            .dba-stagger-row{display:flex;align-items:center;gap:16px;flex-wrap:wrap}
            .dba-stagger-buttons{display:flex;gap:6px}
            .dba-stagger-btn{padding:10px 18px;border:2px solid #e5e7eb;border-radius:8px;background:#fff;cursor:pointer;font-size:15px;font-weight:700;color:#374151;transition:all .15s}
            .dba-stagger-btn:hover{border-color:#f59e0b;background:#fffbeb}
            .dba-stagger-btn.active{border-color:#f59e0b;background:#fef3c7;color:#92400e}
            .dba-stagger-save{padding:10px 24px;background:#f59e0b;color:#fff;border:none;border-radius:8px;font-size:14px;font-weight:700;cursor:pointer}
            .dba-stagger-save:hover{background:#d97706}
            .dba-stagger-save:disabled{opacity:.5;cursor:not-allowed}
            .dba-stagger-preview{background:#fefce8;border:1px solid #fde68a;border-radius:8px;padding:12px 16px;margin-top:12px;font-size:12px;font-family:monospace;white-space:pre-line;color:#713f12;line-height:1.6}
            .dba-stagger-result{margin-top:10px;padding:8px 14px;border-radius:6px;font-size:13px;font-weight:600;display:none}
            .dba-stagger-result.ok{display:block;background:#dcfce7;color:#166534}
            .dba-stagger-result.err{display:block;background:#fee2e2;color:#991b1b}
            @media(max-width:900px){.dba-summary-row{grid-template-columns:1fr}}
        </style>

        <div class="dba-cal-wrap">

        <!-- ═══════ STAGGER CONTROL ═══════ -->
        <div class="dba-stagger-box">
            <h3>⏱️ Post Stagger — Time Between Posts in Each Batch</h3>
            <p style="margin:0 0 14px;color:#6b7280;font-size:13px;">
                Controls the <code>post_date</code> gap between posts within every bot's batch.
                Longer gaps look more natural to Google and give DALL-E breathing room.
            </p>
            <div class="dba-stagger-row">
                <div class="dba-stagger-buttons" id="dba-stagger-btns">
                    <?php foreach ( array( 20, 30, 40, 50, 60 ) as $opt ) : ?>
                    <button type="button" class="dba-stagger-btn<?php echo $opt === $stagger_min ? ' active' : ''; ?>" data-val="<?php echo $opt; ?>"><?php echo $opt; ?> min</button>
                    <?php endforeach; ?>
                </div>
                <button type="button" class="dba-stagger-save" id="dba-stagger-save" disabled>Save for All Bots</button>
            </div>
            <div class="dba-stagger-preview" id="dba-stagger-preview"><?php echo esc_html( $stagger_preview ); ?></div>
            <div class="dba-stagger-result" id="dba-stagger-result"></div>
        </div>

        <script>
        (function($){
            var cur=<?php echo $stagger_min;?>, sel=cur;
            var bots=<?php echo wp_json_encode($js_bots);?>;
            $('#dba-stagger-btns').on('click','.dba-stagger-btn',function(){
                sel=parseInt($(this).data('val'));
                $('.dba-stagger-btn').removeClass('active');$(this).addClass('active');
                $('#dba-stagger-save').prop('disabled',sel===cur);
                var lines=[];
                bots.forEach(function(b){
                    if(!b.enabled)return;
                    if(b.ppr<=1){lines.push(b.icon+' '+b.short+': 1 post (no stagger needed)');return;}
                    var t=[];for(var i=0;i<Math.min(b.ppr,8);i++){var h=9+Math.floor(i*sel/60),m=(i*sel)%60;t.push((h<10?'0':'')+h+':'+(m<10?'0':'')+m);}
                    lines.push(b.icon+' '+b.short+': '+b.ppr+' posts => '+t.join(', ')+' ('+(b.ppr-1)*sel+' min span)');
                });
                $('#dba-stagger-preview').text(lines.join('\n'));
            });
            $('#dba-stagger-save').on('click',function(){
                var $b=$(this);$b.prop('disabled',true).text('Saving...');
                $.post(ajaxurl,{action:'dba_save_stagger',nonce:typeof dba_admin!=='undefined'?dba_admin.nonce:'',stagger_minutes:sel},function(r){
                    if(r.success){cur=sel;$('#dba-stagger-result').removeClass('err').addClass('ok').text(r.data.message).show();if(r.data.preview)$('#dba-stagger-preview').text(r.data.preview);}
                    else{$('#dba-stagger-result').removeClass('ok').addClass('err').text('Save failed').show();}
                    $b.text('Save for All Bots');setTimeout(function(){$('#dba-stagger-result').fadeOut();},4000);
                }).fail(function(){$b.prop('disabled',false).text('Save for All Bots');$('#dba-stagger-result').removeClass('ok').addClass('err').text('Network error').show();});
            });
        })(jQuery);
        </script>

        <!-- Legend -->
        <div class="dba-legend">
            <?php foreach ( self::BOTS as $bk => $bot ) : $on = !empty($schedules[$bk]['enabled']); ?>
            <div class="dba-legend-item">
                <span class="dba-legend-dot" style="background:<?php echo esc_attr($bot['color']); ?>;"></span>
                <strong><?php echo esc_html($bot['label']); ?></strong>
                <span class="<?php echo $on?'dba-legend-on':'dba-legend-off'; ?>"><?php echo $on?'ON':'OFF'; ?></span>
            </div>
            <?php endforeach; ?>
        </div>

        <!-- Month nav -->
        <div class="dba-cal-nav">
            <a href="<?php echo esc_url($prev_url); ?>" class="dba-nav-btn">&laquo; Prev</a>
            <div style="display:flex;align-items:center;gap:12px;">
                <h2><?php echo esc_html($month_label); ?></h2>
                <a href="<?php echo esc_url($base_url); ?>" class="dba-nav-btn" style="font-size:12px;">Today</a>
            </div>
            <a href="<?php echo esc_url($next_url); ?>" class="dba-nav-btn">Next &raquo;</a>
        </div>

        <!-- Calendar grid -->
        <div class="dba-cal-grid">
            <?php foreach(array('Mon','Tue','Wed','Thu','Fri','Sat','Sun') as $dn): ?>
            <div class="dba-cal-header"><?php echo $dn; ?></div>
            <?php endforeach; ?>

            <?php for($e=0;$e<$first_dow;$e++): ?><div class="dba-cal-cell dba-empty"></div><?php endfor; ?>

            <?php for($d=1;$d<=$days_in_month;$d++):
                $ds=sprintf('%04d-%02d-%02d',$cur_year,$cur_month,$d);
                $ist=($ds===$today_str);$dow=date('w',strtotime($ds));$iw=($dow==0||$dow==6);
                $db=$month_map[$ds]??array();$dt=array_sum($db);
            ?>
            <div class="dba-cal-cell<?php echo $ist?' dba-today':''; ?>">
                <div class="dba-cal-date<?php echo $ist?' dba-today-num':''; echo $iw?' dba-weekend':''; ?>"><?php echo $d; ?></div>
                <?php if(!empty($db)): ?>
                <div class="dba-cal-pills">
                    <?php foreach($db as $bk=>$c): $b=self::BOTS[$bk]??null;if(!$b)continue; ?>
                    <span class="dba-cal-pill" style="background:<?php echo esc_attr($b['color']); ?>;" title="<?php echo esc_attr($b['label'].': '.$c.' post(s)'); ?>">
                        <?php echo esc_html($b['short']); ?> <span class="num"><?php echo $c; ?></span>
                    </span>
                    <?php endforeach; ?>
                </div>
                <?php if($dt>0): ?><div class="dba-cal-day-total"><?php echo $dt; ?></div><?php endif; endif; ?>
            </div>
            <?php endfor; ?>

            <?php $ld=(date('w',mktime(0,0,0,$cur_month,$days_in_month,$cur_year))+6)%7;
            for($e=$ld+1;$e<7;$e++): ?><div class="dba-cal-cell dba-empty"></div><?php endfor; ?>
        </div>

        <!-- Summary tables -->
        <div class="dba-summary-row">
            <div class="dba-summary-box">
                <h3>📊 Weekly Breakdown — <?php echo esc_html($month_label); ?></h3>
                <table class="dba-summary-table"><thead><tr>
                    <th>Week</th>
                    <?php foreach(self::BOTS as $bk=>$bot): ?><th class="dba-num" style="color:<?php echo esc_attr($bot['color']); ?>"><?php echo esc_html($bot['short']); ?></th><?php endforeach; ?>
                    <th class="dba-num">Total</th>
                </tr></thead><tbody>
                <?php foreach($weekly_totals as $wl=>$wk):
                    $dr='';if(!empty($wk['_dates'])){$dr=' ('.date('j',strtotime(reset($wk['_dates']))).'-'.date('j',strtotime(end($wk['_dates']))).')';}
                ?>
                <tr>
                    <td><strong><?php echo esc_html($wl.$dr); ?></strong></td>
                    <?php foreach(array_keys(self::BOTS) as $bk): ?>
                    <td class="dba-num"><?php echo $wk[$bk]?intval($wk[$bk]):'<span style="color:#d1d5db">-</span>'; ?></td>
                    <?php endforeach; ?>
                    <td class="dba-num"><strong><?php echo $wk['_total']; ?></strong></td>
                </tr>
                <?php endforeach; ?>
                <tr class="dba-total-row">
                    <td>Month Total</td>
                    <?php foreach(array_keys(self::BOTS) as $bk): ?><td class="dba-num"><?php echo intval($month_totals[$bk]); ?></td><?php endforeach; ?>
                    <td class="dba-num"><strong><?php echo $month_totals['_total']; ?></strong></td>
                </tr>
                </tbody></table>
            </div>

            <div class="dba-summary-box">
                <h3>📈 3-Month Forecast</h3>
                <table class="dba-summary-table"><thead><tr>
                    <th>Month</th>
                    <?php foreach(self::BOTS as $bk=>$bot): ?><th class="dba-num" style="color:<?php echo esc_attr($bot['color']); ?>"><?php echo esc_html($bot['short']); ?></th><?php endforeach; ?>
                    <th class="dba-num">Total</th>
                </tr></thead><tbody>
                <?php $fg=0;for($fi=0;$fi<3;$fi++):
                    $fm=$cur_month+$fi;$fy=$cur_year;while($fm>12){$fm-=12;$fy++;}
                    $fmap=$this->build_month_map($fy,$fm,$schedules);$ft=$this->calc_monthly_totals($fmap);$fg+=$ft['_total'];
                ?>
                <tr<?php echo $fi===0?' style="background:#f0f9ff"':''; ?>>
                    <td><strong><?php echo date('M Y',mktime(0,0,0,$fm,1,$fy)); ?></strong><?php echo $fi===0?' &larr;':''; ?></td>
                    <?php foreach(array_keys(self::BOTS) as $bk): ?><td class="dba-num"><?php echo intval($ft[$bk]); ?></td><?php endforeach; ?>
                    <td class="dba-num"><strong><?php echo $ft['_total']; ?></strong></td>
                </tr>
                <?php endfor; ?>
                <tr class="dba-total-row">
                    <td>3-Month Total</td>
                    <td colspan="<?php echo count(self::BOTS); ?>"></td>
                    <td class="dba-num"><strong><?php echo $fg; ?></strong></td>
                </tr>
                </tbody></table>
            </div>
        </div>

        <!-- Bot cards -->
        <h3 style="margin-top:28px;">⚙️ Bot Schedules</h3>
        <div class="dba-sched-cards">
            <?php foreach(self::BOTS as $bk=>$bot): $sc=$schedules[$bk]; ?>
            <div class="dba-sched-card" style="border-left-color:<?php echo esc_attr($bot['color']); ?>;">
                <h4><?php echo esc_html($bot['icon'].' '.$bot['label']); ?></h4>
                <p>Status: <span class="dba-val"><?php echo $sc['enabled']?'&#10003; Active':'&#10007; Disabled'; ?></span></p>
                <p>Days: <span class="dba-val"><?php echo esc_html(implode(', ',array_map('ucfirst',$sc['posting_days']))); ?></span></p>
                <p>Posts/run: <span class="dba-val"><?php echo intval($sc['posts_per_run']); ?></span></p>
                <p>Time: <span class="dba-val"><?php echo esc_html($sc['time_label']); ?></span></p>
                <p>TZ: <span class="dba-val"><?php echo esc_html($sc['timezone']); ?></span></p>
                <?php if($bk==='geobot'&&!empty($sc['countries'])):foreach($sc['countries'] as $cc):
                    echo '<p style="margin:1px 0;font-size:11px;">&bull; '.esc_html($cc['label']).': '.intval($cc['posts_per_run']).'/run</p>';
                endforeach;endif; ?>
            </div>
            <?php endforeach; ?>
        </div>

        <!-- Next runs -->
        <h3 style="margin-top:28px;">🕐 Next Scheduled Runs</h3>
        <div style="background:#fff;border:1px solid #e5e7eb;border-radius:8px;padding:16px;margin-bottom:30px;">
            <table class="dba-summary-table"><thead><tr><th>Bot</th><th>Next Cron Fire</th><th>Hook</th></tr></thead><tbody>
            <?php
            $hks=array('core'=>'dba_daily_generation','newsbot'=>'dba_pe_daily_generation','luxstrat'=>'dba_luxstrat_cron','latam'=>'dba_latam_daily_run','eeurope'=>'dba_eeurope_daily_run','comfisc'=>'dba_comfisc_fr_cron');
            foreach($hks as $bk=>$hk):
                $bot=self::BOTS[$bk];$nx=wp_next_scheduled($hk);
                if(!$nx&&$bk==='latam'){$ns=wp_next_scheduled($hk,array('saturday'));$nu=wp_next_scheduled($hk,array('sunday'));$nx=$ns&&$nu?min($ns,$nu):($ns?:$nu);}
                if(!$nx&&$bk==='eeurope'){$ee_sd=get_option('dba_eeurope_settings',array());$ee_pd=!empty($ee_sd['posting_days'])?(array)$ee_sd['posting_days']:array('thursday','friday');foreach($ee_pd as $eed){$eets=wp_next_scheduled($hk,array($eed));if($eets&&(!$nx||$eets<$nx))$nx=$eets;}}
                $nxs=$nx?date_i18n('D, M j, Y H:i:s',$nx+(get_option('gmt_offset',0)*3600)).' (site time)':'Not scheduled';
            ?>
            <tr>
                <td><span class="dba-bot-tag" style="background:<?php echo esc_attr($bot['color']); ?>"><?php echo esc_html($bot['label']); ?></span></td>
                <td><?php echo esc_html($nxs); ?></td>
                <td><code><?php echo esc_html($hk); ?></code></td>
            </tr>
            <?php endforeach; ?>
            <?php if(class_exists('DBA_GeoBot_Registry')):foreach(DBA_GeoBot_Registry::get_countries() as $gk=>$gc):
                $gn=wp_next_scheduled($gc['cron_hook']);$gns=$gn?date_i18n('D, M j, Y H:i:s',$gn+(get_option('gmt_offset',0)*3600)).' (site time)':'Not scheduled';
            ?>
            <tr>
                <td><span class="dba-bot-tag" style="background:<?php echo esc_attr(self::BOTS['geobot']['color']); ?>">Geo: <?php echo esc_html($gc['label']??ucfirst($gk)); ?></span></td>
                <td><?php echo esc_html($gns); ?></td>
                <td><code><?php echo esc_html($gc['cron_hook']); ?></code></td>
            </tr>
            <?php endforeach;endif; ?>
            </tbody></table>
        </div>

        </div>
        </div>
        <?php
    }
}
