<?php
/**
 * DBA_LATAM_Calendar
 *
 * Monthly calendar view for the LATAM GeoBot admin panel.
 * Shows every auto-generated LATAM post on the day it was published,
 * with time, country, city, theme, and a direct edit/view link.
 *
 * Renders as a tab inside the LATAM admin page or as a standalone submenu.
 *
 * @since 2.11.0
 */

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

class DBA_LATAM_Calendar {

    private static $instance = null;

    /** Country → emoji flag map */
    const FLAGS = array(
        'brazil'      => '🇧🇷',
        'mexico'      => '🇲🇽',
        'argentina'   => '🇦🇷',
        'chile'       => '🇨🇱',
        'peru'        => '🇵🇪',
        'colombia'    => '🇨🇴',
        'ecuador'     => '🇪🇨',
        'guatemala'   => '🇬🇹',
        'honduras'    => '🇭🇳',
        'el_salvador' => '🇸🇻',
        'nicaragua'   => '🇳🇮',
        'costa_rica'  => '🇨🇷',
        'bolivia'     => '🇧🇴',
        'paraguay'    => '🇵🇾',
        'uruguay'     => '🇺🇾',
    );

    /** Country → color map for badges */
    const COLORS = array(
        'brazil'      => '#009739',
        'mexico'      => '#006847',
        'argentina'   => '#6CACE4',
        'chile'       => '#D52B1E',
        'peru'        => '#D91023',
        'colombia'    => '#FCD116',
        'ecuador'     => '#FFD100',
        'guatemala'   => '#4997D0',
        'honduras'    => '#0073CF',
        'el_salvador' => '#0F47AF',
        'nicaragua'   => '#0067C6',
        'costa_rica'  => '#002B7F',
        'bolivia'     => '#007934',
        'paraguay'    => '#0038A8',
        'uruguay'     => '#001489',
    );

    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, 'add_menu' ), 31 );
        add_action( 'wp_ajax_dba_latam_calendar_data', array( $this, 'ajax_calendar_data' ) );
    }

    /**
     * Add submenu page.
     */
    public function add_menu() {
        add_submenu_page(
            'dba-settings',
            'LATAM Calendar',
            '📅 LATAM Calendar',
            'manage_options',
            'dba-latam-calendar',
            array( $this, 'render_page' )
        );
    }

    /**
     * Compute which day numbers in a given month are scheduled LATAM posting days.
     * Only returns FUTURE days (today or later, with no existing post already).
     *
     * @param int   $year
     * @param int   $month
     * @param array $existing_posts  Keyed by day number (from get_month_posts).
     * @return array  Keyed by day number, value = array with schedule info.
     */
    private function get_scheduled_days( $year, $month, $existing_posts = array() ) {
        $settings      = get_option( 'dba_latam_settings', array() );
        $enabled       = ! empty( $settings['enabled'] );
        $posting_days  = ! empty( $settings['posting_days'] ) ? (array) $settings['posting_days'] : array( 'saturday', 'sunday' );
        $cron_time     = ! empty( $settings['cron_time'] )    ? $settings['cron_time']             : '07:00';
        $posts_per_run = max( 1, absint( $settings['posts_per_run'] ?? 3 ) );

        if ( ! $enabled || empty( $posting_days ) ) return array();

        // Map PHP day names to Mon=0..Sun=6
        $day_to_dow = array(
            'monday' => 0, 'tuesday' => 1, 'wednesday' => 2, 'thursday' => 3,
            'friday' => 4, 'saturday' => 5, 'sunday' => 6,
        );
        $active_dows = array();
        foreach ( $posting_days as $d ) {
            if ( isset( $day_to_dow[ $d ] ) ) $active_dows[] = $day_to_dow[ $d ];
        }

        $days_in    = intval( date( 't', mktime( 0, 0, 0, $month, 1, $year ) ) );
        $first_dow  = intval( date( 'w', mktime( 0, 0, 0, $month, 1, $year ) ) ); // 0=Sun
        $first_dow_mon = ( $first_dow === 0 ) ? 6 : $first_dow - 1; // Mon=0

        $today_y = intval( date( 'Y' ) );
        $today_m = intval( date( 'n' ) );
        $today_d = intval( date( 'j' ) );

        $scheduled = array();

        for ( $d = 1; $d <= $days_in; $d++ ) {
            $cell_dow = ( $first_dow_mon + $d - 1 ) % 7;

            // Skip days that aren't posting days
            if ( ! in_array( $cell_dow, $active_dows, true ) ) continue;

            // Only show future days (skip past days that already ran)
            if ( $year < $today_y ) continue;
            if ( $year === $today_y && $month < $today_m ) continue;
            if ( $year === $today_y && $month === $today_m && $d < $today_d ) continue;

            // Skip days that already have posts
            if ( ! empty( $existing_posts[ $d ] ) ) continue;

            $scheduled[ $d ] = array(
                'time'          => $cron_time,
                'posts_per_run' => $posts_per_run,
            );
        }

        return $scheduled;
    }

    /**
     * Fetch posts for a given month.
     *
     * @param  int $year
     * @param  int $month
     * @return array  Keyed by day number (1–31), each value is array of post data.
     */
    private function get_month_posts( $year, $month ) {
        $start = sprintf( '%04d-%02d-01 00:00:00', $year, $month );
        $end   = gmdate( 'Y-m-t 23:59:59', strtotime( $start ) );

        $query = new WP_Query( array(
            'post_type'      => 'post',
            'post_status'    => array( 'publish', 'draft', 'pending', 'private', 'trash' ),
            'posts_per_page' => 100,
            'meta_query'     => array(
                array( 'key' => '_dba_latam_auto_created', 'compare' => 'EXISTS' ),
            ),
            'date_query'     => array(
                array(
                    'after'     => $start,
                    'before'    => $end,
                    'inclusive' => true,
                ),
            ),
            'orderby'        => 'date',
            'order'          => 'ASC',
        ) );

        $days = array();
        while ( $query->have_posts() ) {
            $query->the_post();
            $id      = get_the_ID();
            $day     = intval( get_the_date( 'j' ) );
            $time    = get_the_date( 'H:i' );
            $country = get_post_meta( $id, '_dba_latam_country', true );
            $city    = get_post_meta( $id, '_dba_latam_city', true );
            $region  = get_post_meta( $id, '_dba_latam_region', true );
            $theme   = get_post_meta( $id, '_dba_latam_theme', true );
            $status  = get_post_status( $id );

            $config = $country ? DBA_LATAM_Registry::get_country( $country ) : null;
            $label  = $config ? $config['label'] : ucfirst( $country );
            $flag   = isset( self::FLAGS[ $country ] ) ? self::FLAGS[ $country ] : '🌎';
            $color  = isset( self::COLORS[ $country ] ) ? self::COLORS[ $country ] : '#1a365d';

            if ( ! isset( $days[ $day ] ) ) {
                $days[ $day ] = array();
            }

            $days[ $day ][] = array(
                'id'      => $id,
                'title'   => get_the_title(),
                'time'    => $time,
                'country' => $country,
                'label'   => $label,
                'flag'    => $flag,
                'color'   => $color,
                'city'    => $city,
                'region'  => $region,
                'theme'   => $theme,
                'status'  => $status,
                'edit'    => get_edit_post_link( $id, 'raw' ),
                'view'    => get_permalink( $id ),
                'yoast_kw'   => get_post_meta( $id, '_yoast_wpseo_focuskw', true ),
                'yoast_desc' => get_post_meta( $id, '_yoast_wpseo_metadesc', true ),
            );
        }
        wp_reset_postdata();

        return $days;
    }

    /**
     * AJAX endpoint for calendar data (supports month navigation without reload).
     */
    public function ajax_calendar_data() {
        check_ajax_referer( 'dba_admin_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( 'Permission denied.' );
        }

        $year  = intval( $_POST['year'] ?? date( 'Y' ) );
        $month = intval( $_POST['month'] ?? date( 'n' ) );

        // Clamp
        if ( $month < 1 )  { $month = 12; $year--; }
        if ( $month > 12 ) { $month = 1;  $year++; }

        $posts = $this->get_month_posts( $year, $month );
        $scheduled = $this->get_scheduled_days( $year, $month, $posts );

        wp_send_json_success( array(
            'year'      => $year,
            'month'     => $month,
            'posts'     => $posts,
            'scheduled' => $scheduled,
            'posts' => $posts,
        ) );
    }

    /**
     * Render the calendar page.
     */
    public function render_page() {
        $year  = intval( $_GET['cal_year']  ?? date( 'Y' ) );
        $month = intval( $_GET['cal_month'] ?? date( 'n' ) );
        if ( $month < 1 )  { $month = 12; $year--; }
        if ( $month > 12 ) { $month = 1;  $year++; }

        $posts     = $this->get_month_posts( $year, $month );
        $month_ts  = mktime( 0, 0, 0, $month, 1, $year );
        $days_in   = intval( date( 't', $month_ts ) );
        $first_dow = intval( date( 'w', $month_ts ) ); // 0=Sun, 1=Mon...
        // Adjust to Monday-first: Mon=0, Sun=6
        $first_dow_mon = ( $first_dow === 0 ) ? 6 : $first_dow - 1;

        $month_label = date( 'F Y', $month_ts );

        $prev_month = $month - 1;
        $prev_year  = $year;
        if ( $prev_month < 1 ) { $prev_month = 12; $prev_year--; }

        $next_month = $month + 1;
        $next_year  = $year;
        if ( $next_month > 12 ) { $next_month = 1; $next_year++; }

        // Stats
        $total_posts = 0;
        $countries_seen = array();
        foreach ( $posts as $day => $day_posts ) {
            $total_posts += count( $day_posts );
            foreach ( $day_posts as $p ) {
                $countries_seen[ $p['country'] ] = $p['label'];
            }
        }

        $today_day = ( intval( date( 'Y' ) ) === $year && intval( date( 'n' ) ) === $month ) ? intval( date( 'j' ) ) : 0;

        // Compute upcoming scheduled posting days (future only, no existing posts)
        $scheduled_days = $this->get_scheduled_days( $year, $month, $posts );
        $next_run_count = count( $scheduled_days );
        ?>
        <div class="wrap" style="max-width:1200px;">
            <h1 style="display:flex;align-items:center;gap:10px;">
                <span style="font-size:32px;">📅</span>
                LATAM GeoBot Calendar
            </h1>

            <!-- ── MONTH NAVIGATION ── -->
            <div style="display:flex;align-items:center;gap:20px;margin:20px 0;background:#fff;padding:16px 24px;border-radius:8px;border:1px solid #e0e0e0;">
                <a href="<?php echo esc_url( add_query_arg( array( 'page' => 'dba-latam-calendar', 'cal_year' => $prev_year, 'cal_month' => $prev_month ), admin_url( 'admin.php' ) ) ); ?>"
                   class="button" style="font-size:18px;padding:4px 14px;">◀</a>

                <h2 style="margin:0;font-size:24px;color:#1a365d;min-width:200px;text-align:center;">
                    <?php echo esc_html( $month_label ); ?>
                </h2>

                <a href="<?php echo esc_url( add_query_arg( array( 'page' => 'dba-latam-calendar', 'cal_year' => $next_year, 'cal_month' => $next_month ), admin_url( 'admin.php' ) ) ); ?>"
                   class="button" style="font-size:18px;padding:4px 14px;">▶</a>

                <!-- Jump to month -->
                <select id="dba-cal-jump-month" style="margin-left:auto;">
                    <?php for ( $m = 1; $m <= 12; $m++ ): ?>
                    <option value="<?php echo $m; ?>" <?php selected( $m, $month ); ?>><?php echo date( 'F', mktime( 0, 0, 0, $m, 1 ) ); ?></option>
                    <?php endfor; ?>
                </select>
                <select id="dba-cal-jump-year">
                    <?php for ( $y = 2025; $y <= 2028; $y++ ): ?>
                    <option value="<?php echo $y; ?>" <?php selected( $y, $year ); ?>><?php echo $y; ?></option>
                    <?php endfor; ?>
                </select>
                <button class="button" id="dba-cal-jump-go">Go</button>
            </div>

            <!-- ── MONTH STATS ── -->
            <div style="display:flex;gap:16px;margin-bottom:20px;">
                <div style="background:#fff;border:1px solid #e0e0e0;border-radius:8px;padding:12px 20px;text-align:center;min-width:120px;">
                    <div style="font-size:28px;font-weight:bold;color:#1a365d;"><?php echo $total_posts; ?></div>
                    <div style="font-size:12px;color:#666;">Posts this month</div>
                </div>
                <div style="background:#fff;border:1px solid #e0e0e0;border-radius:8px;padding:12px 20px;text-align:center;min-width:120px;">
                    <div style="font-size:28px;font-weight:bold;color:#4a7c59;"><?php echo count( $countries_seen ); ?></div>
                    <div style="font-size:12px;color:#666;">Countries covered</div>
                </div>
                <div style="background:#fff;border:1px solid #e0e0e0;border-radius:8px;padding:12px 20px;text-align:center;min-width:120px;">
                    <div style="font-size:28px;font-weight:bold;color:#2d5f8a;"><?php echo $next_run_count; ?></div>
                    <div style="font-size:12px;color:#666;">Upcoming runs</div>
                </div>
                <?php if ( ! empty( $countries_seen ) ): ?>
                <div style="background:#fff;border:1px solid #e0e0e0;border-radius:8px;padding:12px 20px;display:flex;align-items:center;gap:8px;flex-wrap:wrap;">
                    <?php foreach ( $countries_seen as $ck => $cl ): ?>
                    <span style="font-size:12px;background:<?php echo esc_attr( self::COLORS[ $ck ] ?? '#1a365d' ); ?>;color:#fff;padding:2px 8px;border-radius:3px;">
                        <?php echo esc_html( ( self::FLAGS[ $ck ] ?? '' ) . ' ' . $cl ); ?>
                    </span>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>

            <!-- ── CALENDAR GRID ── -->
            <div style="background:#fff;border:1px solid #e0e0e0;border-radius:8px;overflow:hidden;">
                <!-- Header row: day names -->
                <div style="display:grid;grid-template-columns:repeat(7,1fr);background:#1a365d;color:#fff;font-weight:bold;font-size:13px;text-align:center;">
                    <?php foreach ( array( 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ) as $dn ): ?>
                    <div style="padding:10px 4px;<?php echo in_array( $dn, array( 'Sat', 'Sun' ) ) ? 'background:#2d5f8a;' : ''; ?>">
                        <?php echo $dn; ?>
                    </div>
                    <?php endforeach; ?>
                </div>

                <!-- Day cells -->
                <div style="display:grid;grid-template-columns:repeat(7,1fr);border-top:1px solid #e0e0e0;">
                    <?php
                    // Empty cells before first day
                    for ( $e = 0; $e < $first_dow_mon; $e++ ) {
                        echo '<div style="min-height:100px;border-bottom:1px solid #eee;border-right:1px solid #eee;background:#fafafa;"></div>';
                    }

                    // Day cells
                    for ( $d = 1; $d <= $days_in; $d++ ):
                        $cell_dow = ( $first_dow_mon + $d - 1 ) % 7; // 0=Mon, 5=Sat, 6=Sun
                        $is_weekend = ( $cell_dow >= 5 );
                        $is_today   = ( $d === $today_day );
                        $day_posts  = isset( $posts[ $d ] ) ? $posts[ $d ] : array();
                        $has_posts  = ! empty( $day_posts );
                        $is_scheduled = isset( $scheduled_days[ $d ] );

                        $bg = '#fff';
                        if ( $has_posts && $is_weekend )      $bg = '#f0f7ed';
                        elseif ( $has_posts )                  $bg = '#fefcf3';
                        elseif ( $is_scheduled && $is_weekend ) $bg = '#f0f4ff';
                        elseif ( $is_scheduled )               $bg = '#f7f8ff';
                        elseif ( $is_weekend )                 $bg = '#f7fafc';
                    ?>
                    <div style="min-height:100px;border-bottom:1px solid #eee;border-right:1px solid #eee;padding:4px 6px;background:<?php echo $bg; ?>;position:relative;<?php echo $is_today ? 'outline:2px solid #1a365d;outline-offset:-2px;z-index:1;' : ''; ?>">
                        <!-- Day number -->
                        <div style="font-size:13px;font-weight:<?php echo ( $has_posts || $is_scheduled ) ? 'bold' : 'normal'; ?>;color:<?php echo $is_today ? '#1a365d' : ( $is_weekend ? '#2d5f8a' : '#999' ); ?>;margin-bottom:4px;">
                            <?php echo $d; ?>
                            <?php if ( $is_today ): ?>
                            <span style="background:#1a365d;color:#fff;font-size:9px;padding:1px 5px;border-radius:3px;margin-left:4px;">TODAY</span>
                            <?php endif; ?>
                        </div>

                        <!-- Posts for this day -->
                        <?php foreach ( $day_posts as $p ):
                            $status_icon = '';
                            $opacity = '1';
                            if ( $p['status'] === 'draft' )   { $status_icon = '📝'; $opacity = '0.7'; }
                            if ( $p['status'] === 'trash' )   { $status_icon = '🗑'; $opacity = '0.4'; }
                            if ( $p['status'] === 'pending' ) { $status_icon = '⏳'; $opacity = '0.7'; }
                        ?>
                        <a href="<?php echo esc_url( $p['edit'] ); ?>"
                           title="<?php echo esc_attr( $p['title'] ); ?>"
                           style="display:block;background:<?php echo esc_attr( $p['color'] ); ?>;color:#fff;padding:3px 6px;border-radius:4px;margin-bottom:3px;font-size:11px;line-height:1.3;text-decoration:none;opacity:<?php echo $opacity; ?>;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">
                            <span style="font-weight:bold;"><?php echo esc_html( $p['time'] ); ?></span>
                            <?php echo esc_html( $p['flag'] . ' ' . $p['city'] ); ?>
                            <?php echo $status_icon; ?>
                        </a>
                        <?php endforeach; ?>

                        <?php // Scheduled future run indicator (no post yet)
                        if ( $is_scheduled ):
                            $sched = $scheduled_days[ $d ];
                        ?>
                        <div style="display:block;border:2px dashed #2d5f8a;color:#2d5f8a;padding:3px 6px;border-radius:4px;margin-bottom:3px;font-size:11px;line-height:1.3;background:#e8f0fe;">
                            <span style="font-weight:bold;"><?php echo esc_html( $sched['time'] ); ?></span>
                            🌎 ×<?php echo intval( $sched['posts_per_run'] ); ?> scheduled
                        </div>
                        <?php endif; ?>
                    </div>
                    <?php endfor;

                    // Trailing empty cells to complete the grid row
                    $total_cells = $first_dow_mon + $days_in;
                    $remaining   = ( 7 - ( $total_cells % 7 ) ) % 7;
                    for ( $e = 0; $e < $remaining; $e++ ) {
                        echo '<div style="min-height:100px;border-bottom:1px solid #eee;border-right:1px solid #eee;background:#fafafa;"></div>';
                    }
                    ?>
                </div>
            </div>

            <!-- ── LEGEND ── -->
            <div style="margin:16px 0;display:flex;gap:16px;flex-wrap:wrap;font-size:12px;color:#666;">
                <span><span style="display:inline-block;width:14px;height:14px;border:2px dashed #2d5f8a;border-radius:3px;background:#e8f0fe;vertical-align:middle;margin-right:2px;"></span> = Scheduled (not yet generated)</span>
                <span>📝 = Draft</span>
                <span>⏳ = Pending review</span>
                <span>🗑 = Trashed</span>
                <span>Click any post badge to edit</span>
            </div>

            <!-- ── DETAILED LOG TABLE (below calendar) ── -->
            <?php if ( $total_posts > 0 ): ?>
            <h3 style="margin-top:30px;border-bottom:2px solid #1a365d;padding-bottom:8px;">
                Detailed Log — <?php echo esc_html( $month_label ); ?>
                <span style="font-weight:normal;font-size:14px;color:#666;">(<?php echo $total_posts; ?> posts)</span>
            </h3>
            <table class="widefat striped" style="margin-top:10px;">
                <thead>
                    <tr>
                        <th style="width:50px;">#</th>
                        <th style="width:90px;">Date</th>
                        <th style="width:50px;">Time</th>
                        <th style="width:30px;"></th>
                        <th>Country</th>
                        <th>City</th>
                        <th>Theme</th>
                        <th>Title</th>
                        <th style="width:50px;">KW</th>
                        <th style="width:80px;">Status</th>
                        <th style="width:80px;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $row = 1;
                    foreach ( $posts as $day_num => $day_posts ):
                        foreach ( $day_posts as $p ):
                            $theme_label = $p['theme'];
                            // Try to get human-readable theme label
                            $all_themes = DBA_LATAM_Scheduler::get_themes();
                            foreach ( $all_themes as $t ) {
                                if ( $t['key'] === $p['theme'] ) {
                                    $theme_label = $t['label'];
                                    break;
                                }
                            }
                    ?>
                    <tr>
                        <td style="font-weight:bold;color:#999;"><?php echo $row++; ?></td>
                        <td><?php echo esc_html( sprintf( '%s %d', date( 'D', mktime( 0, 0, 0, $month, $day_num, $year ) ), $day_num ) ); ?></td>
                        <td style="font-weight:bold;"><?php echo esc_html( $p['time'] ); ?></td>
                        <td><?php echo esc_html( $p['flag'] ); ?></td>
                        <td><strong><?php echo esc_html( $p['label'] ); ?></strong></td>
                        <td><?php echo esc_html( $p['city'] ); ?></td>
                        <td style="font-size:12px;color:#555;"><?php echo esc_html( $theme_label ); ?></td>
                        <td style="font-size:12px;">
                            <a href="<?php echo esc_url( $p['edit'] ); ?>" style="color:#1a365d;text-decoration:none;">
                                <?php echo esc_html( wp_trim_words( $p['title'], 8 ) ); ?>
                            </a>
                        </td>
                        <td style="font-size:11px;color:#7c3aed;" title="<?php echo esc_attr( $p['yoast_desc'] ?? '' ); ?>">
                            <?php echo esc_html( $p['yoast_kw'] ?? '—' ); ?>
                        </td>
                        <td>
                            <?php
                            $status_colors = array(
                                'publish' => '#48bb78',
                                'draft'   => '#ecc94b',
                                'pending' => '#ed8936',
                                'trash'   => '#fc8181',
                                'private' => '#9f7aea',
                            );
                            $sc = $status_colors[ $p['status'] ] ?? '#999';
                            ?>
                            <span style="background:<?php echo $sc; ?>;color:#fff;padding:2px 8px;border-radius:3px;font-size:11px;">
                                <?php echo esc_html( ucfirst( $p['status'] ) ); ?>
                            </span>
                        </td>
                        <td>
                            <a href="<?php echo esc_url( $p['edit'] ); ?>" style="font-size:12px;">Edit</a>
                            <?php if ( $p['status'] === 'publish' ): ?>
                            | <a href="<?php echo esc_url( $p['view'] ); ?>" target="_blank" style="font-size:12px;">View</a>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; endforeach; ?>
                </tbody>
            </table>
            <?php endif; ?>
        </div>

        <script>
        jQuery(document).ready(function($) {
            $('#dba-cal-jump-go').on('click', function() {
                var m = $('#dba-cal-jump-month').val();
                var y = $('#dba-cal-jump-year').val();
                window.location.href = '<?php echo admin_url( 'admin.php?page=dba-latam-calendar' ); ?>&cal_year=' + y + '&cal_month=' + m;
            });
        });
        </script>
        <?php
    }
}
