<?php
/**
 * DBA_LATAM_Anti_Orphan — Hub linking, cross-linking, government authority links
 *
 * 1. Links new post FROM hub page (appends to city list)
 * 2. Injects backlinks FROM 3 related LATAM posts → new post
 * 3. Appends "Related LATAM Cities" block to new post → 2-3 existing posts
 * 4. Injects GOVERNMENT AUTHORITY outbound links per country/city
 * 5. 30-min verification cron + weekly audit across all 15 countries
 *
 * ALL LATAM-specific: _dba_latam_* meta, DBA_LATAM_* class.
 * Drop into /latam/ folder.
 *
 * @since 2.17.0
 */
if ( ! defined( 'ABSPATH' ) ) exit;

class DBA_LATAM_Anti_Orphan {

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

    const HUB_MARKER = '<!-- LATAM_CITY_LIST -->';
    const RELATED_CLASS = 'dba-latam-related';
    const GOV_LINK_CLASS = 'dba-latam-gov-link';
    const VERIFY_HOOK = 'dba_latam_verify_link';
    const AUDIT_HOOK  = 'dba_latam_weekly_orphan_audit';

    /* ══════════════════════════════════════════════════════════════════
     *  GOVERNMENT AUTHORITY URLs — per country & city
     *  Used as outbound authority links in articles
     * ══════════════════════════════════════════════════════════════════ */
    private static $gov_urls = array(
        'brazil' => array(
            'country' => 'https://www.gov.br',
            'cities'  => array(
                'São Paulo'      => 'https://www.capital.sp.gov.br',
                'Rio de Janeiro' => 'https://www.rio.rj.gov.br',
                'Brasília'       => 'https://www.df.gov.br',
                'Salvador'       => 'https://www.salvador.ba.gov.br',
                'Fortaleza'      => 'https://www.fortaleza.ce.gov.br',
            ),
        ),
        'mexico' => array(
            'country' => 'https://www.gob.mx',
            'cities'  => array(
                'Mexico City'  => 'https://www.cdmx.gob.mx',
                'Guadalajara'  => 'https://www.guadalajara.gob.mx',
                'Monterrey'    => 'https://www.monterrey.gob.mx',
                'Puebla'       => 'https://www.pueblacapital.gob.mx',
                'Tijuana'      => 'https://www.tijuana.gob.mx',
            ),
        ),
        'argentina' => array(
            'country' => 'https://www.argentina.gob.ar',
            'cities'  => array(
                'Buenos Aires' => 'https://www.buenosaires.gob.ar',
                'Córdoba'      => 'https://www.cordoba.gob.ar',
                'Rosario'      => 'https://www.rosario.gob.ar',
                'Mendoza'      => 'https://ciudaddemendoza.gob.ar',
                'La Plata'     => 'https://www.laplata.gob.ar',
            ),
        ),
        'chile' => array(
            'country' => '',
            'cities'  => array(
                'Santiago'     => 'https://www.munistgo.cl',
                'Valparaíso'  => 'https://www.municipalidaddevalparaiso.cl',
                'Concepción'  => 'https://www.concepcion.cl',
                'Antofagasta'  => 'https://www.municipalidaddeantofagasta.cl',
                'Temuco'       => 'https://www.temuco.cl',
            ),
        ),
        'peru' => array(
            'country' => 'https://www.gob.pe',
            'cities'  => array(
                'Arequipa' => 'https://www.muniarequipa.gob.pe',
                'Chiclayo' => 'https://www.munichiclayo.gob.pe',
            ),
        ),
        'colombia' => array(
            'country' => 'https://www.gov.co',
            'cities'  => array(
                'Bogotá'       => 'https://www.bogota.gov.co',
                'Medellín'     => 'https://www.medellin.gov.co',
                'Cali'         => 'https://www.cali.gov.co',
                'Barranquilla' => 'https://www.barranquilla.gov.co',
                'Cartagena'    => 'https://www.cartagena.gov.co',
            ),
        ),
        'ecuador' => array(
            'country' => 'https://www.gob.ec',
            'cities'  => array(
                'Guayaquil'    => 'https://www.guayaquil.gob.ec',
                'Quito'        => 'https://www.quito.gob.ec',
                'Cuenca'       => 'https://www.cuenca.gob.ec',
                'Machala'      => 'https://www.machala.gob.ec',
            ),
        ),
        'guatemala' => array(
            'country' => 'https://guatemala.gob.gt',
            'cities'  => array(
                'Villa Nueva'      => 'https://www.villanueva.gob.gt',
                'Quetzaltenango'   => 'https://munixela.laip.gt',
                'Escuintla'        => 'https://muniescuintla.gob.gt',
            ),
        ),
        'honduras' => array(
            'country' => '',
            'cities'  => array(
                'Tegucigalpa'    => 'https://amdc.hn',
                'San Pedro Sula' => 'https://www.sanpedrosula.hn',
                'Choloma'        => 'https://www.choloma.hn',
                'El Progreso'    => 'https://www.munielprogreso.hn',
            ),
        ),
        'el_salvador' => array(
            'country' => 'https://www.presidencia.gob.sv',
            'cities'  => array(
                'San Salvador' => 'https://www.sansalvador.gob.sv',
                'San Miguel'   => 'https://www.sanmiguel.gob.sv',
                'Santa Ana'    => 'https://www.santaana.gob.sv',
                'Apopa'        => 'https://alcaldiasansalvadoroeste.com',
            ),
        ),
        'nicaragua' => array(
            'country' => '',
            'cities'  => array(
                'Managua' => 'https://www.managua.gob.ni',
            ),
        ),
        'costa_rica' => array(
            'country' => 'https://www.presidencia.go.cr',
            'cities'  => array(
                'Alajuela' => 'https://www.munialajuela.go.cr',
                'Heredia'  => 'https://www.heredia.go.cr',
                'Cartago'  => 'https://www.muni-carta.go.cr',
            ),
        ),
        'bolivia' => array(
            'country' => 'https://www.gob.bo',
            'cities'  => array(
                'Santa Cruz de la Sierra' => 'https://www.santacruz.gob.bo',
                'El Alto'                 => 'https://www.elalto.gob.bo',
                'La Paz'                  => 'https://www.lapaz.bo',
                'Cochabamba'              => 'https://www.cochabamba.bo',
                'Sucre'                   => 'https://www.sucre.bo',
            ),
        ),
        'paraguay' => array(
            'country' => 'https://www.paraguay.gov.py',
            'cities'  => array(
                'Asunción'        => 'https://www.asuncion.gov.py',
                'Ciudad del Este' => 'https://www.mcde.gov.py',
                'San Lorenzo'     => 'https://www.sanlo.gov.py',
                'Luque'           => 'https://www.luque.gov.py',
                'Capiatá'         => 'https://municipalidadcapiata.gov.py',
            ),
        ),
        'uruguay' => array(
            'country' => 'https://www.gub.uy',
            'cities'  => array(
                'Montevideo' => 'https://www.montevideo.gub.uy',
                'Salto'      => 'https://www.salto.gub.uy',
                'Paysandú'   => 'https://www.paysandu.gub.uy',
                'Maldonado'  => 'https://www.maldonado.gub.uy',
                'Rivera'     => 'https://www.rivera.gub.uy',
            ),
        ),
    );

    private function __construct() {
        add_action( self::VERIFY_HOOK, array( $this, 'verify_link' ), 10, 2 );
        add_action( self::AUDIT_HOOK,  array( $this, 'run_weekly_audit' ) );
        if ( ! wp_next_scheduled( self::AUDIT_HOOK ) ) {
            wp_schedule_event( time() + WEEK_IN_SECONDS, 'weekly', self::AUDIT_HOOK );
        }
    }

    /* ══════════════════════════════════════════════════════════════════
     *  PUBLIC: GET GOVERNMENT URLS for a country/city
     * ══════════════════════════════════════════════════════════════════ */
    public static function get_gov_urls( $country_key, $city_name = '' ) {
        $data = self::$gov_urls[ $country_key ] ?? array();
        if ( empty( $data ) ) return array();
        $urls = array();
        if ( ! empty( $data['country'] ) ) {
            $urls['country'] = $data['country'];
        }
        if ( $city_name && ! empty( $data['cities'][ $city_name ] ) ) {
            $urls['city'] = $data['cities'][ $city_name ];
        }
        return $urls;
    }

    /* ══════════════════════════════════════════════════════════════════
     *  INJECT GOVERNMENT AUTHORITY LINKS into article content
     *  Called from scheduler after content generation
     * ══════════════════════════════════════════════════════════════════ */
    public static function inject_gov_links( $content, $country_key, $city_name, $country_label ) {
        $urls = self::get_gov_urls( $country_key, $city_name );
        if ( empty( $urls ) ) return $content;

        $injected = 0;

        // City government link — find first mention of city name in a <p> tag
        if ( ! empty( $urls['city'] ) && $injected < 2 ) {
            $city_esc = preg_quote( $city_name, '/' );
            // Only link the FIRST unlinked occurrence in a text node
            $content = preg_replace_callback(
                '/(<p[^>]*>)((?:(?!<\/p>).)*?)(\b' . $city_esc . '\b)((?:(?!<\/p>).)*?)(<\/p>)/siu',
                function( $m ) use ( $urls, $city_name, &$injected ) {
                    if ( $injected >= 1 ) return $m[0]; // already injected city link
                    // Don't link if already inside an <a> tag
                    if ( preg_match( '/<a\s/i', $m[2] . $m[3] ) ) return $m[0];
                    $injected++;
                    $link = '<a href="' . esc_url( $urls['city'] ) . '" target="_blank" rel="noopener noreferrer" class="' . self::GOV_LINK_CLASS . '" title="' . esc_attr( $city_name ) . ' Official Government Portal">' . $m[3] . '</a>';
                    return $m[1] . $m[2] . $link . $m[4] . $m[5];
                },
                $content,
                1 // only first match
            );
        }

        // Country government link — find first mention of country label
        if ( ! empty( $urls['country'] ) && $injected < 2 ) {
            $country_esc = preg_quote( $country_label, '/' );
            $content = preg_replace_callback(
                '/(<p[^>]*>)((?:(?!<\/p>).)*?)(\b' . $country_esc . '\b)((?:(?!<\/p>).)*?)(<\/p>)/siu',
                function( $m ) use ( $urls, $country_label, &$injected ) {
                    if ( $injected >= 2 ) return $m[0];
                    if ( preg_match( '/<a\s/i', $m[2] . $m[3] ) ) return $m[0];
                    $injected++;
                    $link = '<a href="' . esc_url( $urls['country'] ) . '" target="_blank" rel="noopener noreferrer" class="' . self::GOV_LINK_CLASS . '" title="' . esc_attr( $country_label ) . ' Official Government Portal">' . $m[3] . '</a>';
                    return $m[1] . $m[2] . $link . $m[4] . $m[5];
                },
                $content,
                1
            );
        }

        return $content;
    }

    /* ══════════════════════════════════════════════════════════════════
     *  APPEND "Related LATAM Cities" block to new post
     * ══════════════════════════════════════════════════════════════════ */
    public static function append_related_block( $post_id, $country_key, $city_name, $theme_key ) {
        global $wpdb;
        $related = $wpdb->get_results( $wpdb->prepare(
            "SELECT p.ID, p.post_title FROM {$wpdb->posts} p
             INNER JOIN {$wpdb->postmeta} pm ON p.ID=pm.post_id AND pm.meta_key='_dba_latam_auto_created'
             LEFT JOIN {$wpdb->postmeta} pc ON p.ID=pc.post_id AND pc.meta_key='_dba_latam_country'
             LEFT JOIN {$wpdb->postmeta} pt ON p.ID=pt.post_id AND pt.meta_key='_dba_latam_theme'
             WHERE p.post_status='publish' AND p.ID!=%d
             ORDER BY
               CASE WHEN pc.meta_value=%s THEN 0 ELSE 1 END,
               CASE WHEN pt.meta_value=%s THEN 0 ELSE 1 END,
               p.post_date DESC
             LIMIT 3",
            $post_id, $country_key, $theme_key
        ), ARRAY_A );

        if ( empty( $related ) ) return false;

        $block = "\n\n<!-- LATAM Anti-Orphan Related Block -->\n"
            . '<div class="' . self::RELATED_CLASS . '" style="background:#f9fafb;border:1px solid #e5e7eb;border-radius:6px;padding:18px 22px;margin:28px 0;">'
            . "\n<h3 style=\"margin-top:0;color:#1a365d;\">Related Investment Insights</h3>\n<ul>\n";

        foreach ( $related as $r ) {
            $url = get_permalink( $r['ID'] );
            if ( ! $url ) continue;
            $block .= '<li><a href="' . esc_url( $url ) . '">' . esc_html( $r['post_title'] ) . '</a></li>' . "\n";
        }

        $block .= "</ul>\n</div>\n";

        $content = get_post_field( 'post_content', $post_id );
        $content .= $block;

        $wpdb->update( $wpdb->posts, array( 'post_content' => $content ), array( 'ID' => $post_id ) );
        update_post_meta( $post_id, '_et_pb_old_content', $content );
        clean_post_cache( $post_id );

        return count( $related );
    }

    /* ══════════════════════════════════════════════════════════════════
     *  INJECT BACKLINKS from related posts → new post
     * ══════════════════════════════════════════════════════════════════ */
    public static function inject_backlinks( $new_post_id, $country_key, $theme_key ) {
        global $wpdb;

        $targets = $wpdb->get_results( $wpdb->prepare(
            "SELECT p.ID, p.post_content FROM {$wpdb->posts} p
             INNER JOIN {$wpdb->postmeta} pm ON p.ID=pm.post_id AND pm.meta_key='_dba_latam_auto_created'
             LEFT JOIN {$wpdb->postmeta} pc ON p.ID=pc.post_id AND pc.meta_key='_dba_latam_country'
             WHERE p.post_status='publish' AND p.ID!=%d
             ORDER BY CASE WHEN pc.meta_value=%s THEN 0 ELSE 1 END, p.post_date DESC
             LIMIT 3",
            $new_post_id, $country_key
        ), ARRAY_A );

        $new_url   = get_permalink( $new_post_id );
        $new_title = get_the_title( $new_post_id );
        if ( ! $new_url ) return 0;

        $count = 0;
        foreach ( $targets as $t ) {
            if ( strpos( $t['post_content'], $new_url ) !== false ) continue; // already linked

            // Find the related block and append
            $block_html = '<li><a href="' . esc_url( $new_url ) . '">' . esc_html( $new_title ) . '</a></li>';

            if ( strpos( $t['post_content'], self::RELATED_CLASS ) !== false ) {
                // Append to existing related block's <ul>
                $updated = str_replace( '</ul>', $block_html . "\n</ul>", $t['post_content'] );
            } else {
                // Create a mini related block at the end
                $updated = $t['post_content'] . "\n<!-- LATAM Anti-Orphan Backlink -->\n"
                    . '<div class="' . self::RELATED_CLASS . '" style="background:#f9fafb;border:1px solid #e5e7eb;border-radius:6px;padding:18px 22px;margin:28px 0;">'
                    . "\n<h3 style=\"margin-top:0;color:#1a365d;\">Related Investment Insights</h3>\n<ul>\n"
                    . $block_html . "\n</ul>\n</div>\n";
            }

            $wpdb->update( $wpdb->posts, array( 'post_content' => $updated ), array( 'ID' => $t['ID'] ) );
            update_post_meta( $t['ID'], '_et_pb_old_content', $updated );
            clean_post_cache( $t['ID'] );
            $count++;
        }

        return $count;
    }

    /* ══════════════════════════════════════════════════════════════════
     *  FULL PIPELINE — call from scheduler Step 10
     * ══════════════════════════════════════════════════════════════════ */
    public static function on_post_created( $post_id, $country_key, $city_name, $country_label, $theme_key ) {
        // 1. Inject government authority links into post content
        $content = get_post_field( 'post_content', $post_id );
        $updated = self::inject_gov_links( $content, $country_key, $city_name, $country_label );
        if ( $updated !== $content ) {
            global $wpdb;
            $wpdb->update( $wpdb->posts, array( 'post_content' => $updated ), array( 'ID' => $post_id ) );
            update_post_meta( $post_id, '_et_pb_old_content', $updated );
            clean_post_cache( $post_id );
        }

        // 2. Append related cities block to new post
        $related = self::append_related_block( $post_id, $country_key, $city_name, $theme_key );

        // 3. Inject backlinks from related posts → new post
        $backlinks = self::inject_backlinks( $post_id, $country_key, $theme_key );

        // 4. Schedule 30-min verification
        wp_schedule_single_event( time() + 1800, self::VERIFY_HOOK, array( $post_id, $country_key ) );

        return array(
            'gov_links' => ( $updated !== $content ) ? 1 : 0,
            'related'   => $related ?: 0,
            'backlinks' => $backlinks,
        );
    }

    /* ══════════════════════════════════════════════════════════════════
     *  VERIFY — 30 min after creation
     * ══════════════════════════════════════════════════════════════════ */
    public function verify_link( $post_id, $country_key ) {
        if ( get_post_status( $post_id ) !== 'publish' ) return;
        $content = get_post_field( 'post_content', $post_id );

        // Check if related block exists
        if ( strpos( $content, self::RELATED_CLASS ) === false ) {
            $city  = get_post_meta( $post_id, '_dba_latam_city', true );
            $theme = get_post_meta( $post_id, '_dba_latam_theme', true );
            self::append_related_block( $post_id, $country_key, $city ?: '', $theme ?: '' );
            error_log( "DBA LATAM Anti-Orphan: verify fixed orphan #{$post_id}" );
        }

        // Check gov links exist
        if ( strpos( $content, self::GOV_LINK_CLASS ) === false ) {
            $city    = get_post_meta( $post_id, '_dba_latam_city', true );
            $country = get_post_meta( $post_id, '_dba_latam_country', true );
            $label   = '';
            if ( class_exists( 'DBA_LATAM_Registry' ) ) {
                $cfg = DBA_LATAM_Registry::get_country( $country );
                $label = $cfg['label'] ?? ucfirst( str_replace( '_', ' ', $country ) );
            }
            $content = get_post_field( 'post_content', $post_id );
            $updated = self::inject_gov_links( $content, $country, $city, $label );
            if ( $updated !== $content ) {
                global $wpdb;
                $wpdb->update( $wpdb->posts, array( 'post_content' => $updated ), array( 'ID' => $post_id ) );
                update_post_meta( $post_id, '_et_pb_old_content', $updated );
                clean_post_cache( $post_id );
            }
        }
    }

    /* ══════════════════════════════════════════════════════════════════
     *  AUDIT — scan all LATAM posts, fix orphans
     * ══════════════════════════════════════════════════════════════════ */
    public static function audit_country( $country_key ) {
        global $wpdb;

        $ids = $wpdb->get_col( $wpdb->prepare(
            "SELECT p.ID FROM {$wpdb->posts} p
             INNER JOIN {$wpdb->postmeta} pm ON p.ID=pm.post_id AND pm.meta_key='_dba_latam_auto_created'
             INNER JOIN {$wpdb->postmeta} pc ON p.ID=pc.post_id AND pc.meta_key='_dba_latam_country' AND pc.meta_value=%s
             WHERE p.post_status='publish'
             ORDER BY p.post_date DESC",
            $country_key
        ) );

        $total = count( $ids );
        $orphaned = 0;
        $fixed = 0;

        foreach ( $ids as $pid ) {
            $content = get_post_field( 'post_content', $pid );
            $has_related = strpos( $content, self::RELATED_CLASS ) !== false;
            $has_gov     = strpos( $content, self::GOV_LINK_CLASS ) !== false;

            if ( ! $has_related ) {
                $orphaned++;
                $city  = get_post_meta( $pid, '_dba_latam_city', true );
                $theme = get_post_meta( $pid, '_dba_latam_theme', true );
                $result = self::append_related_block( $pid, $country_key, $city, $theme );
                if ( $result ) $fixed++;
            }

            if ( ! $has_gov ) {
                $city    = get_post_meta( $pid, '_dba_latam_city', true );
                $cfg     = class_exists('DBA_LATAM_Registry') ? DBA_LATAM_Registry::get_country($country_key) : null;
                $label   = $cfg ? $cfg['label'] : ucfirst(str_replace('_',' ',$country_key));
                $content = get_post_field( 'post_content', $pid );
                $updated = self::inject_gov_links( $content, $country_key, $city, $label );
                if ( $updated !== $content ) {
                    $wpdb->update( $wpdb->posts, array('post_content'=>$updated), array('ID'=>$pid) );
                    update_post_meta( $pid, '_et_pb_old_content', $updated );
                    clean_post_cache( $pid );
                }
            }
        }

        return array( 'total' => $total, 'orphaned' => $orphaned, 'fixed' => $fixed );
    }

    /* ── Weekly audit cron — all countries ── */
    public function run_weekly_audit() {
        if ( ! class_exists( 'DBA_LATAM_Registry' ) ) return;
        foreach ( DBA_LATAM_Registry::get_countries() as $k => $cfg ) {
            self::audit_country( $k );
        }
        error_log( 'DBA LATAM Anti-Orphan: weekly audit complete' );
    }

    /* ══════════════════════════════════════════════════════════════════
     *  ADMIN HELPERS — used by class-latam-admin.php panels
     * ══════════════════════════════════════════════════════════════════ */
    public static function get_orphan_stats() {
        global $wpdb;
        $all = $wpdb->get_col(
            "SELECT pm.post_id FROM {$wpdb->postmeta} pm
             INNER JOIN {$wpdb->posts} p ON pm.post_id=p.ID
             WHERE pm.meta_key='_dba_latam_auto_created' AND p.post_status='publish'
             ORDER BY p.post_date DESC"
        );
        $total = count($all);
        $linked = 0;
        $gov_linked = 0;
        $orphans = array();

        foreach ( $all as $pid ) {
            $c = get_post_field('post_content',$pid);
            $has_related = strpos($c, self::RELATED_CLASS) !== false;
            $has_gov = strpos($c, self::GOV_LINK_CLASS) !== false;
            if ($has_related) $linked++;
            if ($has_gov) $gov_linked++;
            if (!$has_related && count($orphans) < 10) {
                $orphans[] = array('id'=>$pid, 'title'=>get_the_title($pid));
            }
        }

        return array(
            'total'       => $total,
            'linked'      => $linked,
            'gov_linked'  => $gov_linked,
            'orphan_count'=> $total - $linked,
            'orphans'     => $orphans,
        );
    }

    public static function get_all_gov_urls() {
        return self::$gov_urls;
    }
}
