<?php
/**
 * ═══════════════════════════════════════════════════════════════════════
 *  DBA CONFLICT CENTER — INTEGRATION GUIDE
 * ═══════════════════════════════════════════════════════════════════════
 *
 *  HOW TO PATCH EACH SCHEDULER (copy-paste the lines marked with >>>)
 *
 *  After patching, your Saturday 06:00 UTC scenario goes from:
 *    BEFORE: Core + LATAM both start → 8 simultaneous OpenAI batches → crash risk
 *    AFTER:  Core starts first → LATAM waits → retries at 06:10 → zero overlap
 *
 * ═══════════════════════════════════════════════════════════════════════
 */


// ─────────────────────────────────────────────────────────────────────
//  1. MAIN PLUGIN FILE (damalion-blog-ai.php) — Load the class
// ─────────────────────────────────────────────────────────────────────
//
//  Add this line near the other require_once statements:
//
//  >>> require_once DBA_PLUGIN_DIR . 'includes/class-conflict-center.php';
//


// ─────────────────────────────────────────────────────────────────────
//  2. CORE SCHEDULER (class-scheduler.php) — Currently checks NOTHING
// ─────────────────────────────────────────────────────────────────────
//
//  In run_daily_generation(), add these 2 lines AFTER the posting-day check
//  and BEFORE the DBA_Post_Creator call:
//
//  >>> if ( ! DBA_Conflict_Center::acquire( 'core', 'dba_daily_generation' ) ) return;
//
//  And at the END of the method (after update_option):
//
//  >>> DBA_Conflict_Center::release( 'core' );
//

// EXAMPLE — patched run_daily_generation():
function EXAMPLE_run_daily_generation_PATCHED() {
    $schedule = get_option('dba_schedule_settings', array());
    if (empty($schedule['enabled'])) return;

    // ... posting day check ...

    // >>> NEW: Global conflict lock
    if ( ! DBA_Conflict_Center::acquire( 'core', 'dba_daily_generation' ) ) return;

    @set_time_limit(600);
    @ini_set('memory_limit', '512M');

    try {
        $creator = DBA_Post_Creator::get_instance();
        $results = $creator->create_daily_batch();

        update_option('dba_last_run', array(
            'time'    => current_time('mysql'),
            'day'     => 'example',
            'results' => $results,
        ));
    } catch ( \Throwable $e ) {
        error_log( 'DBA Scheduler FATAL: ' . $e->getMessage() );
    }

    // >>> NEW: Release lock
    DBA_Conflict_Center::release( 'core' );
}


// ─────────────────────────────────────────────────────────────────────
//  3. PE NEWSBOT (class-newsbot-scheduler.php)
//     Currently checks: Core only (via is_core_batch_running)
//     Patch: Replace the is_core_batch_running() check
// ─────────────────────────────────────────────────────────────────────
//
//  In run_pe_generation(), REPLACE the safety interlock block with:
//
//  >>> if ( ! DBA_Conflict_Center::acquire( 'pe_newsbot', self::CRON_HOOK ) ) return;
//
//  At the END of the method:
//
//  >>> DBA_Conflict_Center::release( 'pe_newsbot' );
//


// ─────────────────────────────────────────────────────────────────────
//  4. GEOBOT (class-geobot-scheduler.php)
//     Currently checks: Core only (via is_core_running)
//     Patch: Replace the is_core_running() check
// ─────────────────────────────────────────────────────────────────────
//
//  In run_generation(), REPLACE the safety interlock block with:
//
//  >>> if ( ! DBA_Conflict_Center::acquire( 'geo_' . $country_key, $config['cron_hook'] ) ) {
//  >>>     delete_transient( $lock_key ); // Clear daily lock so retry works
//  >>>     return;
//  >>> }
//
//  At the END of the method:
//
//  >>> DBA_Conflict_Center::release( 'geo_' . $country_key );
//


// ─────────────────────────────────────────────────────────────────────
//  5. LATAM (class-latam-scheduler.php)
//     Currently checks: Core + PE (via wait_for_other_bots)
//     Patch: Replace wait_for_other_bots() entirely
// ─────────────────────────────────────────────────────────────────────
//
//  In run(), REPLACE the wait_for_other_bots() call with:
//
//  >>> if ( ! DBA_Conflict_Center::acquire( 'latam', self::CRON_HOOK ) ) {
//  >>>     delete_transient( self::LOCK_KEY );
//  >>>     return;
//  >>> }
//
//  At the END of run() (before delete_transient( self::LOCK_KEY )):
//
//  >>> DBA_Conflict_Center::release( 'latam' );
//


// ─────────────────────────────────────────────────────────────────────
//  6. LUXSTRAT EN (class-luxstrat-scheduler.php) — Currently checks NOTHING
// ─────────────────────────────────────────────────────────────────────
//
//  In run(), AFTER the set_transient() lock and BEFORE the generator call:
//
//  >>> if ( ! DBA_Conflict_Center::acquire( 'luxstrat', self::CRON_HOOK ) ) {
//  >>>     delete_transient( $lock_key ); // Let catch-up retry
//  >>>     return;
//  >>> }
//
//  After the generator completes:
//
//  >>> DBA_Conflict_Center::release( 'luxstrat' );
//


// ─────────────────────────────────────────────────────────────────────
//  7. LUXSTRAT INTL (class-luxstrat-intl-scheduler.php) — Checks NOTHING
// ─────────────────────────────────────────────────────────────────────
//
//  In run(), AFTER set_transient() and BEFORE the generator call:
//
//  >>> $hook = 'dba_luxstrat_' . $lang . '_cron';
//  >>> if ( ! DBA_Conflict_Center::acquire( 'luxstrat_' . $lang, $hook ) ) {
//  >>>     delete_transient( $lock_key );
//  >>>     return;
//  >>> }
//
//  After generator completes:
//
//  >>> DBA_Conflict_Center::release( 'luxstrat_' . $lang );
//


// ─────────────────────────────────────────────────────────────────────
//  8. LIVE SPORTS AI — Low priority, optional patch
// ─────────────────────────────────────────────────────────────────────
//
//  In the enrichment method (cron_enrich_pending_posts):
//
//  >>> if ( DBA_Conflict_Center::is_any_running() ) {
//  >>>     error_log( 'LSA Enrichment: Damalion generation running — skipping this cycle' );
//  >>>     return;
//  >>> }
//
//  (No acquire/release needed — just skip if busy. Next 5-min cycle will retry.)
//


// ═══════════════════════════════════════════════════════════════════════
//  ADMIN PAGE — Add to your main admin page (e.g., in the render method)
// ═══════════════════════════════════════════════════════════════════════

function EXAMPLE_render_conflict_center_widget() {
    if ( ! class_exists( 'DBA_Conflict_Center' ) ) return;

    $data = DBA_Conflict_Center::get_dashboard_data();
    $status = $data['status'];
    $collisions = $data['collisions'];
    $history = $data['history'];
    $map = $data['timing_map'];

    echo '<div class="postbox">';
    echo '<h2>🚦 Conflict Center</h2>';
    echo '<div class="inside">';

    // Current status
    echo '<p><strong>Status:</strong> ' . esc_html( DBA_Conflict_Center::get_status_badge() ) . '</p>';

    // Collision warnings
    if ( ! empty( $collisions ) ) {
        echo '<h3>⚠️ Timing Collisions</h3>';
        echo '<table class="widefat striped"><thead><tr>';
        echo '<th>Day</th><th>Severity</th><th>Issue</th>';
        echo '</tr></thead><tbody>';
        foreach ( $collisions as $w ) {
            $color = ( $w['severity'] ?? '' ) === 'critical' ? '#dc3232' : '#ffb900';
            echo '<tr>';
            echo '<td>' . esc_html( $w['day'] ?? '' ) . '</td>';
            echo '<td style="color:' . $color . '"><strong>' . esc_html( strtoupper( $w['severity'] ?? '' ) ) . '</strong></td>';
            echo '<td>' . esc_html( $w['message'] ?? '' ) . '</td>';
            echo '</tr>';
        }
        echo '</tbody></table>';
    }

    // Timing map
    echo '<h3>📅 Module Timing Map (UTC)</h3>';
    echo '<table class="widefat striped"><thead><tr>';
    echo '<th>Module</th><th>UTC Time</th><th>Days</th><th>Posts</th><th>API Calls</th><th>Status</th><th>Lock?</th>';
    echo '</tr></thead><tbody>';
    foreach ( $map as $id => $info ) {
        $status_icon = $info['enabled'] ? '✅' : '⏸';
        $lock_icon = $info['has_lock'] ? '🔒' : '❌';
        echo '<tr>';
        echo '<td><strong>' . esc_html( $info['label'] ) . '</strong></td>';
        echo '<td>' . esc_html( $info['cron_utc'] ) . '</td>';
        echo '<td>' . esc_html( implode( ', ', array_map( function($d) { return substr(ucfirst($d),0,3); }, $info['days'] ) ) ) . '</td>';
        echo '<td>' . esc_html( $info['posts'] ) . '</td>';
        echo '<td>' . esc_html( $info['api_calls'] ) . '</td>';
        echo '<td>' . $status_icon . '</td>';
        echo '<td>' . $lock_icon . '</td>';
        echo '</tr>';
    }
    echo '</tbody></table>';

    // Recent history
    if ( ! empty( $history ) ) {
        echo '<h3>📜 Recent Lock Events</h3>';
        echo '<table class="widefat striped"><thead><tr>';
        echo '<th>Time</th><th>Module</th><th>Event</th><th>Detail</th>';
        echo '</tr></thead><tbody>';
        foreach ( array_slice( $history, 0, 15 ) as $h ) {
            echo '<tr>';
            echo '<td><code>' . esc_html( $h['time'] ) . '</code></td>';
            echo '<td>' . esc_html( $h['label'] ?? $h['module'] ) . '</td>';
            echo '<td>' . esc_html( $h['event'] ) . '</td>';
            echo '<td>' . esc_html( $h['detail'] ) . '</td>';
            echo '</tr>';
        }
        echo '</tbody></table>';
    }

    // Emergency release button
    echo '<p><button class="button" onclick="if(confirm(\'Force-release the global lock?\')) { /* AJAX call */ }">🔓 Force Release Lock</button></p>';

    echo '</div></div>';
}
