<?php
/**
 * Fluxo verificavel entre submissao para o site, Art Track e post publicado.
 */

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

/** Devolve os dados extra de uma submissao como array. */
function rmbz_site_submission_extra( $submission ) {
    $extra = ! empty( $submission->extra_data ) ? json_decode( (string) $submission->extra_data, true ) : [];
    return is_array( $extra ) ? $extra : [];
}

/** Guarda os dados extra sem perder campos criados por outros modulos. */
function rmbz_site_submission_update_extra( $submission_id, array $extra ) {
    global $wpdb;
    return $wpdb->update(
        $wpdb->prefix . 'rmbz_artist_submissions',
        [ 'extra_data' => wp_json_encode( $extra, JSON_UNESCAPED_UNICODE ) ],
        [ 'id' => absint( $submission_id ) ],
        [ '%s' ],
        [ '%d' ]
    );
}

/** Procura um unico Art Track preparado para este telefone. */
function rmbz_site_submission_find_art_track_by_phone( $telemovel ) {
    if ( function_exists( 'rmbz_art_track_find_by_phone' ) && rmbz_art_tracks_native_ready() ) {
        return rmbz_art_track_find_by_phone( $telemovel );
    }
    if ( ! post_type_exists( 'imz_artista' ) ) return 0;

    $variants = function_exists( 'rmbz_artists_phone_variants' )
        ? rmbz_artists_phone_variants( $telemovel )
        : array_filter( [ trim( (string) $telemovel ) ] );
    if ( empty( $variants ) ) {
        return 0;
    }

    $matches = get_posts( [
        'post_type'      => 'imz_artista',
        'post_status'    => [ 'publish', 'draft', 'pending', 'private', 'future' ],
        'posts_per_page' => 2,
        'fields'         => 'ids',
        'meta_key'       => '_imz_artista_account_phone',
        'meta_value'     => $variants,
        'meta_compare'   => 'IN',
        'no_found_rows'  => true,
    ] );

    return count( $matches ) === 1 ? absint( $matches[0] ) : 0;
}

/**
 * Cria ou reutiliza o Art Track correspondente a uma submissao para o site.
 * O nome artistico nunca e usado como chave de identidade.
 */
function rmbz_site_submission_ensure_art_track( $submission_id ) {
    global $wpdb;

    $submission_id = absint( $submission_id );
    if ( ! $submission_id || ( ! rmbz_art_tracks_native_ready() && ! post_type_exists( 'imz_artista' ) ) ) {
        return 0;
    }

    $submission = $wpdb->get_row( $wpdb->prepare(
        "SELECT * FROM {$wpdb->prefix}rmbz_artist_submissions WHERE id = %d LIMIT 1",
        $submission_id
    ) );
    if ( ! $submission || (string) $submission->scenario_type !== 'Publicação Site' ) {
        return 0;
    }

    $extra = rmbz_site_submission_extra( $submission );
    $stored_track_id = absint( $extra['art_track_id'] ?? 0 );
    if ( $stored_track_id && ( rmbz_art_track_is_valid( $stored_track_id, true ) || get_post_type( $stored_track_id ) === 'imz_artista' ) ) {
        return $stored_track_id;
    }

    $wallet = function_exists( 'rmbz_artists_find_wallet_by_identity' )
        ? rmbz_artists_find_wallet_by_identity( (string) $submission->artist_telemovel )
        : null;
    $user_id = function_exists( 'rmbz_artists_ensure_wp_user' )
        ? rmbz_artists_ensure_wp_user( (string) $submission->artist_telemovel )
        : 0;
    $track_id = $user_id && function_exists( 'rmbz_artists_get_art_track_for_user' )
        ? rmbz_artists_get_art_track_for_user( $user_id )
        : 0;

    if ( ! $track_id ) {
        $track_id = rmbz_site_submission_find_art_track_by_phone( (string) $submission->artist_telemovel );
    }

    if ( ! $track_id ) {
        $artist_name = trim( sanitize_text_field( (string) ( $extra['artist_name'] ?? '' ) ) );
        if ( $artist_name === '' && $wallet ) $artist_name = trim( sanitize_text_field( (string) $wallet->user_nome ) );
        if ( $artist_name === '' ) $artist_name = 'Artista ' . preg_replace( '/\D+/', '', (string) $submission->artist_telemovel );
        if ( rmbz_art_tracks_native_ready() ) {
            $track_id = rmbz_art_track_create( [
                'artist_name' => $artist_name,
                'genre' => (string) $submission->music_genre,
                'account_phone' => (string) $submission->artist_telemovel,
                'account_email' => $wallet ? (string) $wallet->user_email : '',
                'linked_user_id' => $user_id,
                'linked_wallet_id' => $wallet ? (int) $wallet->id : 0,
                'created_from_submission_id' => $submission_id,
            ] );
        } else {
            $created = wp_insert_post( [ 'post_type'=>'imz_artista', 'post_status'=>'publish', 'post_title'=>$artist_name ], true );
            if ( ! is_wp_error( $created ) ) $track_id = absint( $created );
        }
        if ( ! $track_id ) {
            error_log( '[1MZ Art Tracks] Falha ao criar Art Track nativo da submissao #' . $submission_id );
            return 0;
        }
    }

    $normal_phone = function_exists( 'rmbz_artists_normalize_phone' ) ? rmbz_artists_normalize_phone( (string) $submission->artist_telemovel ) : trim( (string) $submission->artist_telemovel );
    if ( rmbz_art_track_is_valid( $track_id, true ) ) {
        $email = $wallet ? sanitize_email( (string) $wallet->user_email ) : '';
        if ( substr( strtolower( $email ), -10 ) === '@1mz.local' ) $email = '';
        rmbz_art_track_update( $track_id, [ 'genre'=>(string)$submission->music_genre, 'account_phone'=>$normal_phone, 'account_email'=>$email, 'linked_user_id'=>$user_id, 'linked_wallet_id'=>$wallet?(int)$wallet->id:0, 'created_from_submission_id'=>$submission_id ] );
    } else {
        update_post_meta( $track_id, '_imz_artista_account_phone', $normal_phone );
        if ( $wallet ) update_post_meta( $track_id, '_imz_artista_linked_wallet_id', absint( $wallet->id ) );
        if ( $user_id ) update_post_meta( $track_id, '_imz_artista_linked_user_id', $user_id );
    }
    if ( $user_id ) update_user_meta( $user_id, '_imz_art_track_id', $track_id );

    $extra['art_track_id'] = $track_id;
    $extra['art_track_linked_at'] = current_time( 'mysql' );
    rmbz_site_submission_update_extra( $submission_id, $extra );
    delete_transient( 'imz_auto_verified_' . $track_id );

    return $track_id;
}
add_action( 'rmbz_site_submission_created', 'rmbz_site_submission_ensure_art_track', 10, 1 );

/** Converte um URL antigo no post publicado correspondente. */
function rmbz_site_submission_post_id_from_extra( array $extra ) {
    $post_id = absint( $extra['published_post_id'] ?? 0 );
    if ( $post_id ) {
        return $post_id;
    }
    return ! empty( $extra['published_url'] ) ? absint( url_to_postid( (string) $extra['published_url'] ) ) : 0;
}

/** Confirma se uma publicação ligada a submissão já pode aparecer ao artista. */
function rmbz_site_publication_is_visible( $post_id ) {
    global $wpdb;
    $post_id = absint( $post_id );
    $submission_id = absint( get_post_meta( $post_id, '_rmbz_site_submission_id', true ) );
    if ( ! $submission_id ) {
        return get_post_status( $post_id ) === 'publish';
    }
    $row = $wpdb->get_row( $wpdb->prepare(
        "SELECT review_status, extra_data FROM {$wpdb->prefix}rmbz_artist_submissions WHERE id = %d LIMIT 1",
        $submission_id
    ) );
    if ( ! $row || (string) $row->review_status !== 'finalizado' ) {
        return false;
    }
    $extra = rmbz_site_submission_extra( $row );
    $scheduled_ts = ! empty( $extra['scheduled_publish_at'] ) ? strtotime( (string) $extra['scheduled_publish_at'] . ' UTC' ) : 0;
    return get_post_status( $post_id ) === 'publish' && ( ! $scheduled_ts || $scheduled_ts <= time() );
}

/**
 * Valida e liga uma publicacao real a submissao e ao Art Track.
 * Atualiza $extra por referencia; o handler principal persiste o JSON.
 */
function rmbz_site_submission_link_publication( $submission, $published_post_id, array &$extra ) {
    $published_post_id = absint( $published_post_id );
    if ( ! $submission || (string) $submission->scenario_type !== 'Publicação Site' ) {
        return new WP_Error( 'invalid_submission', 'Esta operação só está disponível para envios destinados ao site.' );
    }
    $published_post = get_post( $published_post_id );
    if ( ! $published_post || $published_post->post_type !== 'post' || $published_post->post_status !== 'publish' ) {
        return new WP_Error( 'invalid_publication', 'Escolhe uma publicação do site que já esteja publicada.' );
    }

    $track_id = rmbz_site_submission_ensure_art_track( (int) $submission->id );
    if ( ! $track_id ) {
        return new WP_Error( 'missing_art_track', 'Não foi possível preparar o Art Track desta conta.' );
    }

    $current_track = absint( get_post_meta( $published_post_id, '_imz_artista_id', true ) );
    if ( $current_track && $current_track !== $track_id ) {
        return new WP_Error( 'publication_owned', 'Esta publicação já pertence a outro Art Track.' );
    }

    $native_track = function_exists( 'rmbz_art_track_get' ) ? rmbz_art_track_get( $track_id ) : null;
    $linked_user_id = $native_track ? absint( $native_track->linked_user_id ) : absint( get_post_meta( $track_id, '_imz_artista_linked_user_id', true ) );
    if ( ! $linked_user_id && function_exists( 'rmbz_artists_ensure_wp_user' ) ) {
        $linked_user_id = rmbz_artists_ensure_wp_user( (string) $submission->artist_telemovel );
    }

    if ( $linked_user_id && (int) $published_post->post_author !== $linked_user_id ) {
        $updated = wp_update_post( [ 'ID' => $published_post_id, 'post_author' => $linked_user_id ], true );
        if ( is_wp_error( $updated ) ) {
            return new WP_Error( 'publication_owner_failed', 'A publicação é válida, mas não foi possível associar a conta do artista.' );
        }
    }

    update_post_meta( $published_post_id, '_imz_artista_id', $track_id );
    update_post_meta( $published_post_id, '_rmbz_site_submission_id', (int) $submission->id );
    update_post_meta( $published_post_id, '_rmbz_is_artist_submission', '1' );
    if ( function_exists( 'rmbz_art_track_sync_music' ) ) rmbz_art_track_sync_music( $track_id, $published_post_id, 'primary', (int) $submission->id );
    if ( function_exists( 'rmbz_dm_save_enrollment' ) && ! rmbz_dm_enrollment( $published_post_id ) ) {
        rmbz_dm_save_enrollment( $published_post_id, [
            'art_track_id'  => $track_id,
            'account_phone' => (string) $submission->artist_telemovel,
            'status'        => 'inactive',
        ] );
    }

    $extra['art_track_id'] = $track_id;
    $extra['published_post_id'] = $published_post_id;
    $extra['published_url'] = get_permalink( $published_post_id );
    $extra['published_linked_at'] = current_time( 'mysql' );
    delete_transient( 'imz_artist_catalog_' . $track_id );
    delete_transient( 'imz_auto_verified_' . $track_id );

    return [
        'art_track_id' => $track_id,
        'post_id'      => $published_post_id,
        'url'          => (string) $extra['published_url'],
    ];
}

/** Campo administrativo para escolher a publicacao oficial. */
function rmbz_render_site_publication_selector( $submission, array $extra ) {
    $track_id = rmbz_site_submission_ensure_art_track( (int) $submission->id );
    $selected = rmbz_site_submission_post_id_from_extra( $extra );
    $posts = get_posts( [
        'post_type'      => 'post',
        'post_status'    => 'publish',
        'posts_per_page' => -1,
        'orderby'        => 'date',
        'order'          => 'DESC',
        'no_found_rows'  => true,
    ] );
    ?>
    <div class="rmbz-mod-field-label">
        <span class="dashicons dashicons-admin-links" aria-hidden="true"></span> Publicação oficial no site
    </div>
    <select name="published_post_id" id="rmbz-published-post-id" style="width:100%;min-height:42px;">
        <option value="">Selecionar uma publicação já publicada</option>
        <?php foreach ( $posts as $site_post ) :
            if ( get_post_meta( $site_post->ID, '_rmbz_nao_e_musica', true ) === '1' ) continue;
            $owner = absint( get_post_meta( $site_post->ID, '_imz_artista_id', true ) );
            $blocked = $owner && $track_id && $owner !== $track_id;
            ?>
            <option value="<?php echo (int) $site_post->ID; ?>" <?php selected( $selected, $site_post->ID ); ?> <?php disabled( $blocked ); ?>>
                <?php echo esc_html( get_the_date( 'd/m/Y', $site_post ) . ' · ' . get_the_title( $site_post ) . ( $blocked ? ' · pertence a outro Art Track' : '' ) ); ?>
            </option>
        <?php endforeach; ?>
    </select>
    <p style="font-size:11px;color:#646970;margin:6px 0 14px;line-height:1.5;">
        Para marcar como <strong>Finalizado</strong>, escolhe o post real publicado. O link, o Art Track e a conta do artista serão associados automaticamente.
    </p>
    <?php if ( $selected && get_post_status( $selected ) === 'publish' ) : ?>
        <div class="rmbz-mod-link-row" style="margin-bottom:14px;">
            <span class="dashicons dashicons-yes-alt" style="color:#059669;"></span>
            <a href="<?php echo esc_url( get_permalink( $selected ) ); ?>" target="_blank" rel="noopener"><?php echo esc_html( get_the_title( $selected ) ); ?></a>
            <a href="<?php echo esc_url( get_edit_post_link( $selected ) ); ?>" class="rmbz-mod-icon-btn">Editar post</a>
        </div>
    <?php endif;
}
