<?php
/**
 * Artist-only music boost campaigns paid from the official 1MZ wallet.
 */
if ( ! defined( 'ABSPATH' ) ) exit;

function imz_artist_boost_durations() {
    return [
        1  => [ 'label' => '1 dia',   'description' => 'Destaque rapido para uma novidade.' ],
        3  => [ 'label' => '3 dias',  'description' => 'Presenca reforcada durante o lancamento.' ],
        7  => [ 'label' => '7 dias',  'description' => 'Uma semana completa de visibilidade.' ],
        14 => [ 'label' => '14 dias', 'description' => 'Campanha continua por duas semanas.' ],
        30 => [ 'label' => '30 dias', 'description' => 'Maior periodo de recomendacao.' ],
    ];
}

function imz_artist_boost_placements() {
    return [ 'sponsored_posts', 'downloads', 'recommendations' ];
}

function imz_boost_is_active( $boost_id, $placement = '' ) {
    $boost_id = absint( $boost_id );
    if ( ! $boost_id || get_post_type( $boost_id ) !== 'impulsionamento' ) return false;
    if ( get_post_meta( $boost_id, 'status', true ) !== 'aprovado' ) return false;

    $now = current_datetime()->getTimestamp();
    $timezone = wp_timezone();
    $start = (string) get_post_meta( $boost_id, '_boost_data_inicio', true );
    $end = (string) get_post_meta( $boost_id, '_boost_data_fim', true );
    try {
        if ( $start !== '' && ( new DateTimeImmutable( $start, $timezone ) )->getTimestamp() > $now ) return false;
        if ( $end !== '' && ( new DateTimeImmutable( $end, $timezone ) )->getTimestamp() < $now ) return false;
    } catch ( Exception $exception ) {
        return false;
    }

    if ( $placement !== '' ) {
        $placements = get_post_meta( $boost_id, '_boost_placements', true );
        // Campaigns created before placement controls remain valid everywhere.
        if ( is_array( $placements ) && $placements && ! in_array( $placement, $placements, true ) ) return false;
    }
    return true;
}

function imz_music_active_boost_ids( $music_id, $placement = '' ) {
    $music_id = absint( $music_id );
    if ( ! $music_id ) return [];
    $ids = get_posts( [
        'post_type'      => 'impulsionamento',
        'post_status'    => 'publish',
        'posts_per_page' => -1,
        'fields'         => 'ids',
        'meta_query'     => [
            [ 'key' => 'post_id_original', 'value' => $music_id, 'type' => 'NUMERIC' ],
            [ 'key' => 'status', 'value' => 'aprovado' ],
        ],
        'no_found_rows'  => true,
    ] );
    return array_values( array_filter( array_map( 'absint', $ids ), static function( $boost_id ) use ( $placement ) {
        return imz_boost_is_active( $boost_id, $placement );
    } ) );
}

function imz_artist_boost_music_belongs_to_artist( $music_id, $artist_id ) {
    $music_id = absint( $music_id );
    $artist_id = absint( $artist_id );
    $music = get_post( $music_id );
    if ( ! $music || $music->post_type !== 'post' || $music->post_status !== 'publish' ) return false;
    if ( get_post_meta( $music_id, '_imz_nao_e_musica', true ) === '1' ) return false;

    $art_track_id = function_exists( 'rmbz_artists_get_art_track_for_user' )
        ? absint( rmbz_artists_get_art_track_for_user( $artist_id ) )
        : 0;
    if ( $art_track_id && function_exists( 'rmbz_art_track_music_ids' ) ) {
        return in_array( $music_id, array_map( 'absint', rmbz_art_track_music_ids( $art_track_id ) ), true );
    }
    if ( $art_track_id && absint( get_post_meta( $music_id, '_imz_artista_id', true ) ) === $art_track_id ) return true;
    return false;
}

function imz_artist_boost_redirect( $notice ) {
    $url = function_exists( 'imz_rmbz_account_url' )
        ? imz_rmbz_account_url( 'musicas' )
        : add_query_arg( 'sect', 'musicas', home_url( '/minha-conta/' ) );
    wp_safe_redirect( add_query_arg( 'boost_notice', sanitize_key( $notice ), $url ) );
    exit;
}

function imz_process_artist_wallet_boost() {
    $logged_in = function_exists( 'imz_rmbz_is_artist_logged_in' ) ? imz_rmbz_is_artist_logged_in() : is_user_logged_in();
    if ( ! $logged_in ) imz_artist_boost_redirect( 'login_required' );

    $nonce = isset( $_POST['imz_artist_boost_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['imz_artist_boost_nonce'] ) ) : '';
    if ( ! wp_verify_nonce( $nonce, 'imz_artist_wallet_boost' ) ) imz_artist_boost_redirect( 'security_error' );

    $artist_id = function_exists( 'imz_get_current_artist_user_id' ) ? absint( imz_get_current_artist_user_id() ) : get_current_user_id();
    $phone = function_exists( 'rmbz_get_current_user_telemovel' ) ? trim( (string) rmbz_get_current_user_telemovel() ) : '';
    if ( ! $artist_id || $phone === '' ) imz_artist_boost_redirect( 'account_error' );
    if ( function_exists( 'imz_rmbz_artist_account_status' ) && imz_rmbz_artist_account_status( $artist_id ) === 'blocked' ) imz_artist_boost_redirect( 'account_blocked' );
    if ( function_exists( 'rmbz_partnership_has_access' ) && ! rmbz_partnership_has_access( $phone ) ) imz_artist_boost_redirect( 'partnership_required' );

    $music_id = absint( $_POST['music_id'] ?? 0 );
    $days = absint( $_POST['boost_days'] ?? 0 );
    $request_key = sanitize_key( wp_unslash( $_POST['boost_request_key'] ?? '' ) );
    $durations = imz_artist_boost_durations();
    if ( ! isset( $durations[ $days ] ) ) imz_artist_boost_redirect( 'invalid_duration' );
    if ( ! imz_artist_boost_music_belongs_to_artist( $music_id, $artist_id ) ) imz_artist_boost_redirect( 'invalid_music' );
    if ( ! function_exists( 'rmbz_update_wallet_balance' ) || ! function_exists( 'rmbz_get_wallet_balance_by_phone' ) ) imz_artist_boost_redirect( 'wallet_unavailable' );

    if ( ! preg_match( '/^[a-z0-9-]{20,80}$/', $request_key ) ) imz_artist_boost_redirect( 'security_error' );
    $signature = sanitize_text_field( wp_unslash( $_POST['boost_signature'] ?? '' ) );
    $expected_signature = hash_hmac( 'sha256', $artist_id . '|' . $phone . '|' . $request_key, wp_salt( 'auth' ) );
    if ( ! hash_equals( $expected_signature, $signature ) ) imz_artist_boost_redirect( 'security_error' );
    $request_transient = 'imz_artist_boost_' . md5( $artist_id . '|' . $request_key );
    if ( get_transient( $request_transient ) ) imz_artist_boost_redirect( 'already_processed' );

    global $wpdb;
    $lock_name = 'imz_artist_boost_' . md5( $artist_id . '|' . $request_key );
    $got_lock = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, 5)', $lock_name ) );
    if ( ! $got_lock ) imz_artist_boost_redirect( 'try_again' );

    try {
        if ( get_transient( $request_transient ) ) imz_artist_boost_redirect( 'already_processed' );

        $price_per_day = max( 0.01, (float) get_option( 'imz_boost_price_per_day', 50 ) );
        $total = round( $price_per_day * $days, 2 );
        if ( (float) rmbz_get_wallet_balance_by_phone( $phone ) + 0.0001 < $total ) imz_artist_boost_redirect( 'insufficient_balance' );

        $music_title = function_exists( 'imz_native_dashboard_clean_title' )
            ? imz_native_dashboard_clean_title( $music_id )
            : wp_strip_all_tags( get_the_title( $music_id ) );
        $boost_id = wp_insert_post( [
            'post_type'   => 'impulsionamento',
            'post_title'  => 'Campanha do artista - ' . $music_title,
            'post_status' => 'publish',
            'post_author' => $artist_id,
            'meta_input'  => [
                'post_id_original'       => $music_id,
                'valor'                  => $total,
                'nome'                   => '',
                'metodo_pagamento'       => 'Carteira 1MZ',
                'telefone_pagador'       => $phone,
                'status'                 => 'processando',
                '_boost_duracao_dias'    => $days,
                '_boost_format'          => 'artist_wallet',
                '_boost_payment_source'  => 'wallet',
                '_boost_owner_user_id'   => $artist_id,
                '_boost_request_key'     => $request_key,
                '_boost_placements'      => imz_artist_boost_placements(),
                'cor_forcada'            => '#2563eb',
                '_boost_data_inicio'     => '',
                '_boost_data_fim'        => '',
            ],
        ], true );
        if ( is_wp_error( $boost_id ) || ! $boost_id ) imz_artist_boost_redirect( 'save_error' );

        $details = sprintf( 'Impulsionamento de "%s" por %d dia(s), campanha #%d.', $music_title, $days, $boost_id );
        $debit = rmbz_update_wallet_balance( $phone, -$total, 'music_boost_payment', $music_id, $details );
        if ( empty( $debit['success'] ) ) {
            wp_delete_post( $boost_id, true );
            imz_artist_boost_redirect( ( $debit['error'] ?? '' ) === 'Saldo insuficiente.' ? 'insufficient_balance' : 'debit_error' );
        }

        $start = current_time( 'mysql' );
        $end = current_datetime()->modify( '+' . $days . ' days' )->format( 'Y-m-d H:i:s' );
        $updates = [
            'status'               => 'aprovado',
            '_boost_data_inicio'   => $start,
            '_boost_data_fim'      => $end,
            '_boost_auto_approved' => 'yes',
            '_boost_payment_state' => 'paid',
        ];
        foreach ( $updates as $key => $value ) {
            if ( update_post_meta( $boost_id, $key, $value ) === false && get_post_meta( $boost_id, $key, true ) !== $value ) {
                rmbz_update_wallet_balance( $phone, $total, 'music_boost_refund', $music_id, 'Reversao automatica da campanha #' . $boost_id . '.' );
                wp_delete_post( $boost_id, true );
                imz_artist_boost_redirect( 'save_error' );
            }
        }

        set_transient( $request_transient, $boost_id, DAY_IN_SECONDS );
        delete_transient( 'imz_verified_post_ids_list' );
        imz_artist_boost_redirect( 'success' );
    } finally {
        $wpdb->query( $wpdb->prepare( 'SELECT RELEASE_LOCK(%s)', $lock_name ) );
    }
}
add_action( 'admin_post_imz_artist_wallet_boost', 'imz_process_artist_wallet_boost' );
add_action( 'admin_post_nopriv_imz_artist_wallet_boost', 'imz_process_artist_wallet_boost' );