<?php

namespace Blazemedia\Affiliation\CustomPostTypes;

class Zone {

    public function __construct() {
        
        // Add the custom columns to the posts post type:
        add_filter( 'init',    [ $this, 'add_zone_post_type'] );
        // On zone save, clear formats meta for all related articles
        add_action( 'save_post_affiliate_zone', [ $this, 'on_save_zone' ], 10, 3 );
        // Add admin metabox to show related posts
        add_action( 'add_meta_boxes', [ $this, 'add_zone_usage_metabox' ] );
    }

    /**
     * registra il post-type per le tabelle
     *
     * @return void
     */
    public function add_zone_post_type() {

        register_post_type('affiliate_zone', [

            'public'          => false,
            'show_ui'         => true,
            'capability_type' => 'post',
            'hierarchical'    => false,
            'rewrite'         => [ 'with_front' => false  ],
            'supports'        => [ 'title', 'editor' ],
            'show_in_nav_menus' => true,
            'show_in_menu' => 'affiliation-management',
            'menu_position' => 21,
            
            'labels' => [
                'name' => 'Zone Affiliazione',
                'singular_name' => 'Zona Affiliazione',
                'add_new' => 'Aggiungi nuova',
                'add_new_item' => 'Aggiungi nuova zona',
                'edit' => 'Modifica',
                'edit_item' => 'Modifica zona',
                'new_item' => 'Nuovo zona',
                'view' => 'Vedi',
                'view_item' => 'Vedi zona',
                'search_items' => 'Cerca zona',
                'not_found' => 'Nessuna zona trovata',
                'not_found_in_trash' => 'Nessuna zona trovata nel cestino'
            ]
        ]);

    }


    /**
     * Register the metabox showing posts where this zone is used
     */
    public function add_zone_usage_metabox() {
        add_meta_box(
            'affiliate_zone_usage',
            'Articoli collegati alla zona',
            [ $this, 'render_zone_usage_metabox' ],
            'affiliate_zone',
            'normal',
            'default'
        );
    }

    /**
     * Render the list of posts using this zone, based on `_blz_affiliation_zone_posts` CSV
     *
     * @param \WP_Post $post
     * @return void
     */
    public function render_zone_usage_metabox( $post ) {
        if ( ! $post instanceof \WP_Post ) return;

        $list = get_post_meta( $post->ID, '_blz_affiliation_zone_posts', true );
        $ids = is_string($list) && $list !== ''
            ? array_unique( array_filter( array_map( 'intval', array_map( 'trim', explode( ',', $list ) ) ) ) )
            : [];

        echo '<div class="affiliate-zone-usage">';
        if ( empty( $ids ) ) {
            echo '<p>Nessun articolo collegato a questa zona.</p>';
            echo '</div>';
            return;
        }

        echo '<p>Questa zona è presente nei seguenti articoli:</p>';
        echo '<ul style="margin-left:1em; list-style:disc;">';
        foreach ( $ids as $articleId ) {
            $article = get_post( $articleId );
            if ( ! $article || $article instanceof \WP_Post === false ) continue;

            $title = get_the_title( $article );
            if ( $title === '' ) $title = '(senza titolo)';
            $edit_link = get_edit_post_link( $articleId );
            $view_link = get_permalink( $articleId );

            echo '<li>';
            if ( $edit_link ) {
                echo '<a href="' . esc_url( $edit_link ) . '"><strong>' . esc_html( $title ) . '</strong></a>';
            } else {
                echo '<strong>' . esc_html( $title ) . '</strong>';
            }
            if ( $view_link ) {
                echo ' &nbsp;—&nbsp; <a href="' . esc_url( $view_link ) . '" target="_blank" rel="noopener noreferrer">Visualizza</a>';
            }
            echo ' <span style="opacity:.7">(ID: ' . intval( $articleId ) . ')</span>';
            echo '</li>';
        }
        echo '</ul>';
        echo '</div>';
    }

    /**
     * When a zone is saved, clear the formats metas on all related articles
     * referenced by the zone meta `_blz_affiliation_zone_posts`.
     *
     * @param int      $post_id
     * @param \WP_Post $post
     * @param bool     $update
     * @return void
     */
    public function on_save_zone( $post_id, $post, $update ) {
        // Safety checks: avoid autosaves and revisions
        if ( wp_is_post_autosave( $post_id ) || wp_is_post_revision( $post_id ) ) return;

        if ( ! $post instanceof \WP_Post ) return;
        if ( $post->post_type !== 'affiliate_zone' ) return;

        $list = get_post_meta( $post_id, '_blz_affiliation_zone_posts', true );
        if ( ! is_string( $list ) || $list === '' ) return;

        $ids = array_unique( array_filter( array_map( 'trim', explode( ',', $list ) ) ) );
        if ( empty( $ids ) ) return;

        foreach ( $ids as $articleId ) {
            $articleId = (int) $articleId;
            if ( $articleId <= 0 ) continue;

            // Empty metas to force re-fetch/re-render on next view
            update_post_meta( $articleId, '_blz_affiliation_formats_signature', '' );
            update_post_meta( $articleId, '_blz_affiliation_formats', '' );
        }
    }

}
