<?php
/**
 * Administração unificada do Programa de Músicas Patrocinadas.
 *
 * Mantém as tabelas e a API do Music Player, mas apresenta a operação dentro
 * do Gestor de Anúncios & Campanhas.
 */

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

if ( ! defined( 'RMBZ_SPONSORED_UNIFIED' ) ) {
    define( 'RMBZ_SPONSORED_UNIFIED', true );
}

function rmbz_sp_admin_url( array $args = [] ) {
    $url = admin_url( 'edit.php?post_type=impulsionamento&page=imz_ads_manager&view=sponsored' );
    return $args ? add_query_arg( $args, $url ) : $url;
}

function rmbz_sp_table_exists( $table ) {
    global $wpdb;
    return $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) === $table;
}

function rmbz_sponsored_admin_summary() {
    global $wpdb;

    $tracks = $wpdb->prefix . 'mp_sponsored_tracks';
    $pay    = $wpdb->prefix . 'mp_sponsored_payouts';
    $sess   = $wpdb->prefix . 'mp_sponsored_sessions';
    $empty  = [
        'ready'            => false,
        'program_on'       => false,
        'addon_on'         => false,
        'active_tracks'    => 0,
        'total_tracks'     => 0,
        'spent_usd'        => 0.0,
        'budget_remaining' => 0.0,
        'valid_sessions'   => 0,
        'alerts'           => 0,
        'pending_payouts'  => 0,
        'pending_amount'   => 0.0,
    ];

    if ( ! rmbz_sp_table_exists( $tracks ) || ! rmbz_sp_table_exists( $pay ) || ! rmbz_sp_table_exists( $sess ) ) {
        return $empty;
    }

    $features = function_exists( 'mp_get_features' ) ? mp_get_features() : [];
    $addon_on = ! empty( $features['sponsored']['enabled'] );

    return [
        'ready'            => true,
        'program_on'       => (bool) get_option( 'mp_sponsored_on', 0 ),
        'addon_on'         => $addon_on,
        'active_tracks'    => (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$tracks} WHERE active=1 AND (budget_usd=0 OR spent_usd<budget_usd)" ),
        'total_tracks'     => (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$tracks}" ),
        'spent_usd'        => (float) $wpdb->get_var( "SELECT COALESCE(SUM(spent_usd),0) FROM {$tracks}" ),
        'budget_remaining' => (float) $wpdb->get_var( "SELECT COALESCE(SUM(GREATEST(budget_usd-spent_usd,0)),0) FROM {$tracks} WHERE budget_usd>0" ),
        'valid_sessions'   => (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$sess} WHERE credited_sec>0" ),
        'alerts'           => (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$sess} WHERE status='fraud' OR bad_beats>0" ),
        'pending_payouts'  => (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$pay} WHERE status='requested'" ),
        'pending_amount'   => (float) $wpdb->get_var( "SELECT COALESCE(SUM(amount_usd),0) FROM {$pay} WHERE status='requested'" ),
    ];
}

function rmbz_sp_admin_redirect( $notice ) {
    wp_safe_redirect( rmbz_sp_admin_url( [ 'sp_notice' => sanitize_key( $notice ) ] ) );
    exit;
}

/** Processa mutações antes de o wp-admin enviar HTML. */
function rmbz_sp_admin_process_request() {
    if ( ! is_admin() || ! current_user_can( 'manage_options' ) || ($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST' ) {
        return;
    }

    $page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : '';
    $view = isset( $_GET['view'] ) ? sanitize_key( wp_unslash( $_GET['view'] ) ) : '';
    if ( $page !== 'imz_ads_manager' || $view !== 'sponsored' ) {
        return;
    }

    check_admin_referer( 'mp_sponsored' );
    global $wpdb;
    $tracks = $wpdb->prefix . 'mp_sponsored_tracks';
    $pay    = $wpdb->prefix . 'mp_sponsored_payouts';

    if ( isset( $_POST['mp_sponsored_settings'] ) ) {
        update_option( 'mp_sponsored_on', isset( $_POST['mp_sponsored_on'] ) ? 1 : 0 );
        update_option( 'mp_sponsored_countries', strtoupper( sanitize_textarea_field( wp_unslash( $_POST['mp_sponsored_countries'] ?? '' ) ) ) );
        update_option( 'mp_sponsored_min_payout', max( 0, (float) ( $_POST['mp_sponsored_min_payout'] ?? 5 ) ) );
        update_option( 'mp_sponsored_daily_cap_min', max( 1, (int) ( $_POST['mp_sponsored_daily_cap_min'] ?? 30 ) ) );
        update_option( 'mp_sponsored_min_volume', min( 100, max( 0, (int) ( $_POST['mp_sponsored_min_volume'] ?? 20 ) ) ) );
        update_option( 'mp_sponsored_vol_pause_min', min( 120, max( 1, (int) ( $_POST['mp_sponsored_vol_pause_min'] ?? 10 ) ) ) );
        $car = sanitize_key( wp_unslash( $_POST['mp_sponsored_car_earn'] ?? 'flag' ) );
        update_option( 'mp_sponsored_car_earn', in_array( $car, [ 'allow', 'flag', 'block' ], true ) ? $car : 'flag' );
        $methods = array_values( array_intersect(
            array_map( 'sanitize_text_field', (array) wp_unslash( $_POST['mp_sponsored_methods'] ?? [] ) ),
            [ 'PayPal', 'M-Pesa', 'Emola' ]
        ) );
        update_option( 'mp_sponsored_methods', $methods );
        rmbz_sp_admin_redirect( 'settings_saved' );
    }

    if ( isset( $_POST['mp_sponsored_track'] ) ) {
        $data = [
            'title'        => sanitize_text_field( wp_unslash( $_POST['sp_title'] ?? '' ) ),
            'artist'       => sanitize_text_field( wp_unslash( $_POST['sp_artist'] ?? '' ) ),
            'audio_url'    => esc_url_raw( wp_unslash( $_POST['sp_audio'] ?? '' ) ),
            'cover_url'    => esc_url_raw( wp_unslash( $_POST['sp_cover'] ?? '' ) ),
            'countries'    => strtoupper( sanitize_text_field( wp_unslash( $_POST['sp_countries'] ?? '' ) ) ),
            'rate_per_min' => max( 0, (float) ( $_POST['sp_rate'] ?? 0 ) ),
            'budget_usd'   => max( 0, (float) ( $_POST['sp_budget'] ?? 0 ) ),
            'duration_sec' => max( 0, (int) ( $_POST['sp_duration'] ?? 0 ) ),
            'active'       => isset( $_POST['sp_active'] ) ? 1 : 0,
        ];
        if ( $data['title'] === '' || $data['audio_url'] === '' ) {
            rmbz_sp_admin_redirect( 'track_invalid' );
        }
        $track_id = absint( $_POST['sp_id'] ?? 0 );
        if ( $track_id > 0 ) {
            $wpdb->update( $tracks, $data, [ 'id' => $track_id ] );
            rmbz_sp_admin_redirect( 'track_updated' );
        }
        $wpdb->insert( $tracks, $data );
        rmbz_sp_admin_redirect( 'track_created' );
    }

    if ( isset( $_POST['mp_sponsored_delete'] ) ) {
        $wpdb->delete( $tracks, [ 'id' => absint( $_POST['sp_id'] ?? 0 ) ] );
        rmbz_sp_admin_redirect( 'track_deleted' );
    }

    if ( isset( $_POST['mp_fraud_review'] ) ) {
        $uid = absint( $_POST['fraud_uid'] ?? 0 );
        if ( $uid && function_exists( 'mp_sponsored_ai_fraud_review' ) ) {
            set_transient( 'mp_fraud_verdict_' . $uid, mp_sponsored_ai_fraud_review( $uid ), 300 );
        }
        rmbz_sp_admin_redirect( 'review_done' );
    }

    if ( isset( $_POST['mp_fraud_clear'] ) ) {
        $uid = absint( $_POST['fraud_uid'] ?? 0 );
        delete_option( 'mp_sponsored_flags_' . $uid );
        delete_option( 'mp_sponsored_score_' . $uid );
        rmbz_sp_admin_redirect( 'flags_cleared' );
    }

    if ( isset( $_POST['mp_payout_analyze'] ) ) {
        $payout_id = absint( $_POST['payout_id'] ?? 0 );
        $account_id = (int) $wpdb->get_var( $wpdb->prepare( "SELECT account_id FROM {$pay} WHERE id=%d", $payout_id ) );
        if ( $account_id && function_exists( 'mp_sponsored_ai_fraud_review' ) ) {
            $verdict = (string) mp_sponsored_ai_fraud_review( $account_id );
            $note = function_exists( 'mb_substr' ) ? mb_substr( $verdict, 0, 255 ) : substr( $verdict, 0, 255 );
            $wpdb->update( $pay, [ 'note' => $note ], [ 'id' => $payout_id ] );
        }
        rmbz_sp_admin_redirect( 'review_done' );
    }

    if ( isset( $_POST['mp_verify_device'] ) ) {
        $uid = absint( $_POST['fraud_uid'] ?? 0 );
        if ( $uid ) {
            update_option( 'mp_sponsored_verify_' . $uid, 'requested', false );
        }
        rmbz_sp_admin_redirect( 'device_requested' );
    }

    if ( isset( $_POST['mp_clawback'] ) ) {
        $uid = absint( $_POST['fraud_uid'] ?? 0 );
        if ( $uid && function_exists( 'mp_sponsored_balance' ) && function_exists( 'mp_sponsored_clawback' ) ) {
            $balance = mp_sponsored_balance( $uid );
            if ( $balance > 0 ) {
                update_option( 'mp_sponsored_clawback_' . $uid, mp_sponsored_clawback( $uid ) + $balance, false );
            }
            $wpdb->query( $wpdb->prepare( "UPDATE {$pay} SET status='rejected' WHERE account_id=%d AND status='requested'", $uid ) );
        }
        rmbz_sp_admin_redirect( 'earnings_reversed' );
    }

    if ( isset( $_POST['mp_payout_action'] ) ) {
        $payout_id = absint( $_POST['payout_id'] ?? 0 );
        $action = sanitize_key( wp_unslash( $_POST['mp_payout_action'] ) );
        if ( $action === 'paid' ) {
            $wpdb->update( $pay, [ 'status' => 'paid', 'paid_at' => current_time( 'mysql', true ) ], [ 'id' => $payout_id ] );
        } elseif ( $action === 'reject' ) {
            $wpdb->update( $pay, [ 'status' => 'rejected' ], [ 'id' => $payout_id ] );
        }
        rmbz_sp_admin_redirect( 'payout_updated' );
    }
}
add_action( 'admin_init', 'rmbz_sp_admin_process_request', 20 );

function rmbz_sp_admin_notice() {
    $code = isset( $_GET['sp_notice'] ) ? sanitize_key( wp_unslash( $_GET['sp_notice'] ) ) : '';
    $messages = [
        'settings_saved'    => [ 'success', 'Configuração do programa guardada.' ],
        'track_created'     => [ 'success', 'Faixa adicionada ao programa.' ],
        'track_updated'     => [ 'success', 'Faixa patrocinada atualizada.' ],
        'track_deleted'     => [ 'success', 'Faixa removida do programa.' ],
        'track_invalid'     => [ 'error', 'Título e URL do áudio são obrigatórios.' ],
        'review_done'       => [ 'success', 'Análise de integridade concluída.' ],
        'flags_cleared'     => [ 'success', 'Sinalizações da conta foram limpas.' ],
        'device_requested'  => [ 'success', 'O pedido de verificação foi enviado ao dispositivo.' ],
        'earnings_reversed' => [ 'success', 'O saldo suspeito foi revertido e o pedido rejeitado.' ],
        'payout_updated'    => [ 'success', 'Estado do pagamento atualizado.' ],
    ];
    if ( isset( $messages[ $code ] ) ) {
        printf( '<div class="notice notice-%1$s is-dismissible"><p>%2$s</p></div>', esc_attr( $messages[ $code ][0] ), esc_html( $messages[ $code ][1] ) );
    }
}

function rmbz_render_sponsored_campaigns_admin() {
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }

    wp_enqueue_media();
    global $wpdb;
    $tracks_table  = $wpdb->prefix . 'mp_sponsored_tracks';
    $pay_table     = $wpdb->prefix . 'mp_sponsored_payouts';
    $accounts      = $wpdb->prefix . 'mp_accounts';
    $summary       = rmbz_sponsored_admin_summary();

    if ( ! $summary['ready'] ) {
        echo '<div class="rmbz-sp-empty"><h2>Estrutura do programa indisponível</h2><p>As tabelas do Music Player ainda não foram instaladas.</p></div>';
        return;
    }

    $tracks = $wpdb->get_results( "SELECT * FROM {$tracks_table} ORDER BY id DESC LIMIT 300" );
    $payouts = $wpdb->get_results(
        "SELECT p.*,a.email,a.name FROM {$pay_table} p LEFT JOIN {$accounts} a ON a.id=p.account_id ORDER BY (p.status='requested') DESC,p.id DESC LIMIT 150"
    );
    $flagged = $wpdb->get_col( "SELECT REPLACE(option_name,'mp_sponsored_flags_','') FROM {$wpdb->options} WHERE option_name LIKE 'mp_sponsored_flags_%'" );
    $flagged = array_values( array_filter( array_map( 'absint', (array) $flagged ) ) );
    $flagged_accounts = [];
    if ( $flagged ) {
        $ids = implode( ',', $flagged );
        foreach ( (array) $wpdb->get_results( "SELECT id,email,name FROM {$accounts} WHERE id IN ({$ids})" ) as $account ) {
            $flagged_accounts[ (int) $account->id ] = $account;
        }
    }

    $program_on = $summary['program_on'];
    $fully_on   = $program_on && $summary['addon_on'];
    $methods    = (array) get_option( 'mp_sponsored_methods', [ 'M-Pesa', 'Emola' ] );
    rmbz_sp_admin_notice();
    ?>
    <div class="rmbz-sp-admin">
        <style>
        .rmbz-sp-admin{--sp-primary:#146c43;--sp-on:#fff;--sp-container:#d8f2e4;--sp-gold:#efb700;--sp-bg:#f7f7f2;--sp-surface:#fff;--sp-soft:#f0f2ed;--sp-line:#dfe4dd;--sp-text:#1a1f1b;--sp-muted:#667069;--sp-danger:#b3261e;color:var(--sp-text);font-family:Inter,"Segoe UI",Roboto,sans-serif}.rmbz-sp-admin *{box-sizing:border-box}.rmbz-sp-hero{position:relative;overflow:hidden;display:flex;justify-content:space-between;align-items:center;gap:24px;padding:26px 28px;margin-bottom:14px;border-radius:26px;background:linear-gradient(135deg,#173c31,#245d49 70%,#52662a);color:#fff}.rmbz-sp-hero:after{content:"";position:absolute;width:250px;height:250px;right:-85px;top:-135px;border-radius:50%;background:rgba(239,183,0,.19)}.rmbz-sp-hero-copy{position:relative;z-index:1}.rmbz-sp-eyebrow{display:flex;align-items:center;gap:7px;margin-bottom:8px;color:#d5e9df;font-size:11px;font-weight:800;text-transform:uppercase;letter-spacing:.08em}.rmbz-sp-hero h2{margin:0 0 6px;color:#fff;font-size:25px;letter-spacing:-.025em}.rmbz-sp-hero p{margin:0;color:#d5e4dd;font-size:13px}.rmbz-sp-hero-actions{position:relative;z-index:1;display:flex;align-items:center;gap:9px}.rmbz-sp-state{display:inline-flex;align-items:center;gap:7px;padding:9px 13px;border:1px solid rgba(255,255,255,.2);border-radius:999px;background:rgba(255,255,255,.1);font-size:12px;font-weight:800}.rmbz-sp-state:before{content:"";width:8px;height:8px;border-radius:50%;background:#f5ba20}.rmbz-sp-state.is-on:before{background:#3bd39d}.rmbz-sp-btn{min-height:40px;display:inline-flex;align-items:center;justify-content:center;gap:7px;padding:0 15px;border:1px solid var(--sp-line);border-radius:999px;background:#fff;color:var(--sp-text);font-size:12px;font-weight:800;text-decoration:none;cursor:pointer}.rmbz-sp-btn:hover{color:var(--sp-primary);border-color:#aec8ba}.rmbz-sp-btn.primary{border-color:var(--sp-gold);background:var(--sp-gold);color:#181500}.rmbz-sp-btn.danger{color:var(--sp-danger);border-color:#efc1bc}.rmbz-sp-btn.small{min-height:34px;padding:0 11px}.rmbz-sp-btn .dashicons{width:17px;height:17px;font-size:17px}.rmbz-sp-metrics{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:10px;margin:14px 0}.rmbz-sp-metric{min-height:105px;padding:18px;border:1px solid var(--sp-line);border-radius:20px;background:var(--sp-surface)}.rmbz-sp-metric-top{display:flex;align-items:center;justify-content:space-between;gap:8px}.rmbz-sp-metric .dashicons{width:38px;height:38px;display:grid;place-items:center;border-radius:13px;background:var(--sp-container);color:var(--sp-primary);font-size:19px;padding-top:9px}.rmbz-sp-metric small,.rmbz-sp-metric strong,.rmbz-sp-metric span{display:block}.rmbz-sp-metric small{color:var(--sp-muted);font-size:10px;font-weight:850;text-transform:uppercase;letter-spacing:.055em}.rmbz-sp-metric strong{margin-top:12px;font-size:25px;line-height:1;font-variant-numeric:tabular-nums}.rmbz-sp-metric span{margin-top:6px;color:var(--sp-muted);font-size:11px}.rmbz-sp-anchor-nav{display:flex;gap:7px;flex-wrap:wrap;margin:14px 0 18px;padding:7px;border:1px solid var(--sp-line);border-radius:17px;background:var(--sp-surface)}.rmbz-sp-anchor-nav a{padding:9px 13px;border-radius:11px;color:var(--sp-muted);font-size:12px;font-weight:800;text-decoration:none}.rmbz-sp-anchor-nav a:hover{background:var(--sp-soft);color:var(--sp-text)}.rmbz-sp-card{margin-bottom:16px;border:1px solid var(--sp-line);border-radius:22px;background:var(--sp-surface);overflow:hidden}.rmbz-sp-card-head{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:18px 20px;border-bottom:1px solid var(--sp-line)}.rmbz-sp-card-title{display:flex;align-items:center;gap:12px}.rmbz-sp-tonal{width:42px;height:42px;display:grid;place-items:center;border-radius:14px;background:#fff0bd;color:#745800}.rmbz-sp-tonal .dashicons{font-size:20px;width:20px;height:20px}.rmbz-sp-card h3{margin:0;font-size:17px}.rmbz-sp-card-head p{margin:3px 0 0;color:var(--sp-muted);font-size:12px}.rmbz-sp-toolbar{display:flex;align-items:center;gap:8px;padding:12px 18px;border-bottom:1px solid var(--sp-line)}.rmbz-sp-search{position:relative;min-width:260px;flex:1}.rmbz-sp-search .dashicons{position:absolute;left:12px;top:50%;transform:translateY(-50%);color:var(--sp-muted)}.rmbz-sp-search input,.rmbz-sp-toolbar select{width:100%;min-height:40px;margin:0;border:1px solid var(--sp-line);border-radius:12px;background:var(--sp-soft);box-shadow:none;font-size:12px}.rmbz-sp-search input{padding-left:40px}.rmbz-sp-table-wrap{overflow:auto}.rmbz-sp-table{width:100%;border-collapse:collapse;min-width:900px}.rmbz-sp-table th{padding:11px 14px;background:#f3f5f1;color:var(--sp-muted);font-size:10px;text-align:left;text-transform:uppercase;letter-spacing:.055em}.rmbz-sp-table td{padding:13px 14px;border-top:1px solid #edf0ec;font-size:12px;vertical-align:middle}.rmbz-sp-track{display:flex;align-items:center;gap:11px;min-width:230px}.rmbz-sp-cover{width:46px;height:46px;display:grid;place-items:center;overflow:hidden;flex:0 0 auto;border-radius:13px;background:var(--sp-container);color:var(--sp-primary)}.rmbz-sp-cover img{width:100%;height:100%;object-fit:cover}.rmbz-sp-track strong,.rmbz-sp-track span{display:block}.rmbz-sp-track strong{font-size:13px}.rmbz-sp-track span{margin-top:3px;color:var(--sp-muted);font-size:11px}.rmbz-sp-progress{width:110px;height:7px;margin-top:6px;overflow:hidden;border-radius:99px;background:#e4e7e1}.rmbz-sp-progress i{display:block;height:100%;background:var(--sp-primary)}.rmbz-sp-pill{display:inline-flex;align-items:center;padding:6px 9px;border-radius:999px;background:#ecefea;color:#59635c;font-size:10px;font-weight:850}.rmbz-sp-pill.on,.rmbz-sp-pill.paid{background:var(--sp-container);color:var(--sp-primary)}.rmbz-sp-pill.warn,.rmbz-sp-pill.requested{background:#fff0bd;color:#745800}.rmbz-sp-pill.bad,.rmbz-sp-pill.rejected{background:#fde7e4;color:var(--sp-danger)}.rmbz-sp-actions{display:flex;gap:6px;align-items:center;white-space:nowrap}.rmbz-sp-actions form{margin:0}.rmbz-sp-empty{padding:44px 20px;text-align:center;color:var(--sp-muted)}.rmbz-sp-empty h2{color:var(--sp-text)}.rmbz-sp-modal[hidden]{display:none}.rmbz-sp-modal{position:fixed;inset:0;z-index:100000;display:flex;align-items:center;justify-content:center;padding:24px}.rmbz-sp-modal-backdrop{position:absolute;inset:0;background:rgba(18,23,20,.64)}.rmbz-sp-dialog{position:relative;width:min(800px,calc(100vw - 48px));max-height:calc(100vh - 48px);overflow:auto;border-radius:24px;background:#fbfcf9;box-shadow:0 24px 80px rgba(0,0,0,.28)}.rmbz-sp-dialog.wide{width:min(980px,calc(100vw - 48px))}.rmbz-sp-dialog-head{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:19px 22px;border-bottom:1px solid var(--sp-line);background:#fff}.rmbz-sp-dialog-head h3{margin:0;font-size:19px}.rmbz-sp-dialog-head p{margin:3px 0 0;color:var(--sp-muted);font-size:12px}.rmbz-sp-close{width:38px;height:38px;display:grid;place-items:center;border:1px solid var(--sp-line);border-radius:50%;background:#fff;cursor:pointer}.rmbz-sp-dialog-body{padding:20px 22px}.rmbz-sp-fields{display:grid;grid-template-columns:1fr 1fr;gap:14px}.rmbz-sp-field{display:grid;gap:6px}.rmbz-sp-field.full{grid-column:1/-1}.rmbz-sp-field label{font-size:11px;font-weight:850;color:#475149;text-transform:uppercase;letter-spacing:.04em}.rmbz-sp-field input,.rmbz-sp-field textarea,.rmbz-sp-field select{width:100%;min-height:42px;margin:0;padding:8px 11px;border:1px solid var(--sp-line);border-radius:12px;background:#fff;box-shadow:none}.rmbz-sp-field small{color:var(--sp-muted);font-size:11px}.rmbz-sp-check{display:flex;align-items:flex-start;gap:9px;padding:12px;border:1px solid var(--sp-line);border-radius:14px;background:#fff}.rmbz-sp-check input{margin-top:2px}.rmbz-sp-dialog-foot{display:flex;justify-content:flex-end;gap:8px;padding:15px 22px;border-top:1px solid var(--sp-line);background:#fff}.rmbz-sp-picker{display:flex;gap:7px}.rmbz-sp-picker input{flex:1}.rmbz-sp-section-note{padding:12px 16px;border-radius:14px;background:#e9f3ee;color:#355346;font-size:12px}.rmbz-sp-methods{display:flex;gap:9px;flex-wrap:wrap}.rmbz-sp-methods .rmbz-sp-check{min-width:135px}.rmbz-sp-no-addon{margin:0 0 14px;padding:13px 16px;border:1px solid #efd48a;border-radius:15px;background:#fff5d8;color:#6d5500;font-size:12px}.rmbz-sp-no-addon a{font-weight:800}.rmbz-sp-admin-open{overflow:hidden}@media(max-width:1100px){.rmbz-sp-metrics{grid-template-columns:repeat(3,1fr)}}@media(max-width:782px){.rmbz-sp-hero{align-items:flex-start;display:grid;padding:21px}.rmbz-sp-hero-actions{flex-wrap:wrap}.rmbz-sp-metrics{grid-template-columns:1fr 1fr}.rmbz-sp-card-head,.rmbz-sp-toolbar{align-items:flex-start;display:grid}.rmbz-sp-search{min-width:0;width:100%}.rmbz-sp-fields{grid-template-columns:1fr}.rmbz-sp-field.full{grid-column:auto}.rmbz-sp-modal{padding:0}.rmbz-sp-dialog,.rmbz-sp-dialog.wide{width:100vw;max-height:100vh;height:100vh;border-radius:0}.rmbz-sp-dialog-foot{position:sticky;bottom:0}.rmbz-sp-table-wrap{overflow:visible}.rmbz-sp-table{display:block;min-width:0}.rmbz-sp-table thead{display:none}.rmbz-sp-table tbody,.rmbz-sp-table tr,.rmbz-sp-table td{display:block;width:100%}.rmbz-sp-table tr{padding:13px;border-top:1px solid var(--sp-line)}.rmbz-sp-table td{padding:6px 0;border:0}.rmbz-sp-table td:before{content:attr(data-label);display:block;margin-bottom:4px;color:var(--sp-muted);font-size:9px;font-weight:850;text-transform:uppercase}.rmbz-sp-actions{flex-wrap:wrap}.rmbz-sp-progress{width:100%}}@media(max-width:520px){.rmbz-sp-metrics{grid-template-columns:1fr}}
        </style>

        <section class="rmbz-sp-hero">
            <div class="rmbz-sp-hero-copy">
                <div class="rmbz-sp-eyebrow"><span class="dashicons dashicons-format-audio"></span> Campanhas com escuta validada</div>
                <h2>Músicas patrocinadas</h2>
                <p>Orçamento, catálogo, integridade das reproduções e pagamentos no mesmo centro de campanhas.</p>
            </div>
            <div class="rmbz-sp-hero-actions">
                <span class="rmbz-sp-state <?php echo $fully_on ? 'is-on' : ''; ?>"><?php echo $fully_on ? 'Programa operacional' : 'Programa incompleto'; ?></span>
                <button type="button" class="rmbz-sp-btn" data-sp-open="settings"><span class="dashicons dashicons-admin-generic"></span> Configurar</button>
                <button type="button" class="rmbz-sp-btn primary" data-sp-open="track"><span class="dashicons dashicons-plus-alt2"></span> Nova faixa</button>
            </div>
        </section>

        <?php if ( ! $summary['addon_on'] ) : ?>
            <div class="rmbz-sp-no-addon">O programa está configurado, mas o add-on <strong>Músicas Patrocinadas</strong> está desligado no Music Player. <a href="<?php echo esc_url( admin_url( 'admin.php?page=mp-control#addons' ) ); ?>">Abrir add-ons</a>.</div>
        <?php endif; ?>

        <div class="rmbz-sp-metrics">
            <div class="rmbz-sp-metric"><div class="rmbz-sp-metric-top"><small>Distribuído</small><span class="dashicons dashicons-money-alt"></span></div><strong>$<?php echo esc_html( number_format( $summary['spent_usd'], 2 ) ); ?></strong><span>Crédito atribuído por escutas</span></div>
            <div class="rmbz-sp-metric"><div class="rmbz-sp-metric-top"><small>Orçamento restante</small><span class="dashicons dashicons-chart-area"></span></div><strong>$<?php echo esc_html( number_format( $summary['budget_remaining'], 2 ) ); ?></strong><span>Apenas campanhas com limite</span></div>
            <div class="rmbz-sp-metric"><div class="rmbz-sp-metric-top"><small>Faixas ativas</small><span class="dashicons dashicons-playlist-audio"></span></div><strong><?php echo (int) $summary['active_tracks']; ?></strong><span><?php echo (int) $summary['total_tracks']; ?> no programa</span></div>
            <div class="rmbz-sp-metric"><div class="rmbz-sp-metric-top"><small>Escutas válidas</small><span class="dashicons dashicons-yes-alt"></span></div><strong><?php echo esc_html( number_format_i18n( $summary['valid_sessions'] ) ); ?></strong><span><?php echo esc_html( number_format_i18n( $summary['alerts'] ) ); ?> alerta(s)</span></div>
            <div class="rmbz-sp-metric"><div class="rmbz-sp-metric-top"><small>Pagamentos pendentes</small><span class="dashicons dashicons-bank"></span></div><strong><?php echo (int) $summary['pending_payouts']; ?></strong><span>$<?php echo esc_html( number_format( $summary['pending_amount'], 2 ) ); ?> solicitado</span></div>
        </div>

        <nav class="rmbz-sp-anchor-nav" aria-label="Secções de músicas patrocinadas">
            <a href="#rmbz-sp-tracks">Faixas</a><a href="#rmbz-sp-integrity">Integridade</a><a href="#rmbz-sp-payouts">Pagamentos</a>
        </nav>

        <section class="rmbz-sp-card" id="rmbz-sp-tracks">
            <header class="rmbz-sp-card-head"><div class="rmbz-sp-card-title"><span class="rmbz-sp-tonal"><span class="dashicons dashicons-format-audio"></span></span><div><h3>Faixas patrocinadas</h3><p>Campanhas disponíveis no Music Player e respetivo consumo de orçamento.</p></div></div><button type="button" class="rmbz-sp-btn primary" data-sp-open="track"><span class="dashicons dashicons-plus-alt2"></span> Adicionar faixa</button></header>
            <div class="rmbz-sp-toolbar"><label class="rmbz-sp-search"><span class="dashicons dashicons-search"></span><input type="search" id="rmbz-sp-search" placeholder="Pesquisar por faixa, artista ou país"></label><select id="rmbz-sp-filter" aria-label="Filtrar estado"><option value="all">Todos os estados</option><option value="active">Ativas</option><option value="paused">Inativas</option><option value="spent">Orçamento esgotado</option></select></div>
            <?php if ( ! $tracks ) : ?><div class="rmbz-sp-empty">Ainda não existem faixas patrocinadas.</div><?php else : ?>
            <div class="rmbz-sp-table-wrap"><table class="rmbz-sp-table"><thead><tr><th>Faixa</th><th>Países</th><th>Taxa</th><th>Orçamento</th><th>Reproduções</th><th>Estado</th><th>Ações</th></tr></thead><tbody>
            <?php foreach ( $tracks as $track ) :
                $spent = (float) $track->spent_usd;
                $budget = (float) $track->budget_usd;
                $full = $budget > 0 && $spent >= $budget;
                $state = $full ? 'spent' : ( (int) $track->active === 1 ? 'active' : 'paused' );
                $percent = $budget > 0 ? min( 100, round( $spent / $budget * 100 ) ) : 0;
                $track_json = wp_json_encode( [ 'id'=>(int)$track->id,'title'=>$track->title,'artist'=>$track->artist,'audio'=>$track->audio_url,'cover'=>$track->cover_url,'countries'=>$track->countries,'duration'=>(int)$track->duration_sec,'rate'=>(float)$track->rate_per_min,'budget'=>(float)$track->budget_usd,'active'=>(int)$track->active ] );
            ?>
                <tr data-sp-row data-state="<?php echo esc_attr( $state ); ?>" data-search="<?php echo esc_attr( strtolower( $track->title . ' ' . $track->artist . ' ' . $track->countries ) ); ?>">
                    <td data-label="Faixa"><div class="rmbz-sp-track"><span class="rmbz-sp-cover"><?php if ( $track->cover_url ) : ?><img src="<?php echo esc_url( $track->cover_url ); ?>" alt="" loading="lazy"><?php else : ?><span class="dashicons dashicons-format-audio"></span><?php endif; ?></span><span><strong><?php echo esc_html( $track->title ); ?></strong><span><?php echo esc_html( $track->artist ?: 'Sem artista indicado' ); ?></span></span></div></td>
                    <td data-label="Países"><?php echo esc_html( $track->countries ?: 'Todos' ); ?></td>
                    <td data-label="Taxa"><strong>$<?php echo esc_html( number_format( (float) $track->rate_per_min, 4 ) ); ?></strong><br><small>por minuto</small></td>
                    <td data-label="Orçamento"><strong><?php echo $budget > 0 ? '$' . esc_html( number_format( $budget, 2 ) ) : 'Sem limite'; ?></strong><br><small>$<?php echo esc_html( number_format( $spent, 2 ) ); ?> utilizado</small><?php if ( $budget > 0 ) : ?><div class="rmbz-sp-progress"><i style="width:<?php echo (int) $percent; ?>%"></i></div><?php endif; ?></td>
                    <td data-label="Reproduções"><?php echo esc_html( number_format_i18n( (int) $track->plays ) ); ?></td>
                    <td data-label="Estado"><span class="rmbz-sp-pill <?php echo $state === 'active' ? 'on' : ( $state === 'spent' ? 'warn' : '' ); ?>"><?php echo $state === 'active' ? 'Ativa' : ( $state === 'spent' ? 'Orçamento esgotado' : 'Inativa' ); ?></span></td>
                    <td data-label="Ações"><div class="rmbz-sp-actions"><button type="button" class="rmbz-sp-btn small" data-sp-edit="<?php echo esc_attr( $track_json ); ?>"><span class="dashicons dashicons-edit"></span> Editar</button><form method="post" onsubmit="return confirm('Remover esta faixa do programa?')"><?php wp_nonce_field( 'mp_sponsored' ); ?><input type="hidden" name="sp_id" value="<?php echo (int) $track->id; ?>"><button class="rmbz-sp-btn small danger" name="mp_sponsored_delete" value="1" aria-label="Remover"><span class="dashicons dashicons-trash"></span></button></form></div></td>
                </tr>
            <?php endforeach; ?>
            </tbody></table></div><?php endif; ?>
        </section>

        <section class="rmbz-sp-card" id="rmbz-sp-integrity">
            <header class="rmbz-sp-card-head"><div class="rmbz-sp-card-title"><span class="rmbz-sp-tonal"><span class="dashicons dashicons-shield"></span></span><div><h3>Integridade das reproduções</h3><p>Contas sinalizadas pelos controlos de sessão, volume e dispositivo.</p></div></div><span class="rmbz-sp-pill <?php echo $flagged ? 'warn' : 'on'; ?>"><?php echo count( $flagged ); ?> conta(s)</span></header>
            <?php if ( ! $flagged ) : ?><div class="rmbz-sp-empty">Nenhuma conta sinalizada neste momento.</div><?php else : ?>
            <div class="rmbz-sp-table-wrap"><table class="rmbz-sp-table"><thead><tr><th>Conta</th><th>Score</th><th>Última análise</th><th>Ações</th></tr></thead><tbody>
            <?php foreach ( $flagged as $uid ) : $account = $flagged_accounts[$uid] ?? null; $score=(int)get_option('mp_sponsored_score_'.$uid,0); $verdict=(string)get_transient('mp_fraud_verdict_'.$uid); ?>
                <tr><td data-label="Conta"><strong><?php echo esc_html( $account && $account->name ? $account->name : 'Conta #' . $uid ); ?></strong><br><small><?php echo esc_html( $account ? $account->email : '' ); ?></small></td><td data-label="Score"><span class="rmbz-sp-pill <?php echo $score >= 3 ? 'bad' : 'warn'; ?>"><?php echo $score; ?> sinalização(ões)</span></td><td data-label="Última análise"><?php echo $verdict ? esc_html( $verdict ) : '<span style="color:#788078">Ainda não analisada</span>'; ?></td><td data-label="Ações"><form method="post" class="rmbz-sp-actions"><?php wp_nonce_field('mp_sponsored'); ?><input type="hidden" name="fraud_uid" value="<?php echo (int)$uid; ?>"><button class="rmbz-sp-btn small" name="mp_fraud_review" value="1">Analisar integridade</button><button class="rmbz-sp-btn small" name="mp_fraud_clear" value="1" onclick="return confirm('Limpar as sinalizações desta conta?')">Limpar</button></form></td></tr>
            <?php endforeach; ?>
            </tbody></table></div><?php endif; ?>
        </section>

        <section class="rmbz-sp-card" id="rmbz-sp-payouts">
            <header class="rmbz-sp-card-head"><div class="rmbz-sp-card-title"><span class="rmbz-sp-tonal"><span class="dashicons dashicons-bank"></span></span><div><h3>Pagamentos aos ouvintes</h3><p>Pedidos, análise de integridade, verificação do dispositivo e decisão.</p></div></div><span class="rmbz-sp-pill <?php echo $summary['pending_payouts'] ? 'warn' : 'on'; ?>"><?php echo (int)$summary['pending_payouts']; ?> pendente(s)</span></header>
            <?php if ( ! $payouts ) : ?><div class="rmbz-sp-empty">Ainda não existem pedidos de pagamento.</div><?php else : ?>
            <div class="rmbz-sp-table-wrap"><table class="rmbz-sp-table"><thead><tr><th>Ouvinte</th><th>Valor</th><th>Método</th><th>Análise</th><th>Estado</th><th>Ações</th></tr></thead><tbody>
            <?php foreach ( $payouts as $payout ) : $verify=(string)get_option('mp_sponsored_verify_'.(int)$payout->account_id,''); ?>
                <tr><td data-label="Ouvinte"><strong><?php echo esc_html($payout->name ?: ($payout->email ?: 'Conta #'.$payout->account_id)); ?></strong><br><small><?php echo esc_html($payout->email ?: gmdate('d/m/Y',strtotime($payout->created_at))); ?></small></td><td data-label="Valor"><strong>$<?php echo esc_html(number_format((float)$payout->amount_usd,2)); ?></strong></td><td data-label="Método"><?php echo esc_html($payout->method ?: 'Não indicado'); ?><br><small><?php echo esc_html($payout->detail); ?></small></td><td data-label="Análise"><?php if($payout->note): echo esc_html($payout->note); else: ?><form method="post"><?php wp_nonce_field('mp_sponsored'); ?><input type="hidden" name="payout_id" value="<?php echo (int)$payout->id; ?>"><button class="rmbz-sp-btn small" name="mp_payout_analyze" value="1">Analisar</button></form><?php endif; ?></td><td data-label="Estado"><span class="rmbz-sp-pill <?php echo esc_attr($payout->status); ?>"><?php echo esc_html(ucfirst($payout->status)); ?></span><?php if($verify==='requested'): ?><br><small>Dispositivo solicitado</small><?php endif; ?></td><td data-label="Ações"><?php if($payout->status==='requested'): ?><form method="post" class="rmbz-sp-actions"><?php wp_nonce_field('mp_sponsored'); ?><input type="hidden" name="payout_id" value="<?php echo (int)$payout->id; ?>"><input type="hidden" name="fraud_uid" value="<?php echo (int)$payout->account_id; ?>"><button class="rmbz-sp-btn small primary" name="mp_payout_action" value="paid" onclick="return confirm('Confirmas que este pagamento foi efetuado?')">Marcar pago</button><button class="rmbz-sp-btn small" name="mp_payout_action" value="reject" onclick="return confirm('Rejeitar este pedido de pagamento?')">Rejeitar</button><?php if($verify!=='requested'): ?><button class="rmbz-sp-btn small" name="mp_verify_device" value="1">Verificar aparelho</button><?php endif; ?><button class="rmbz-sp-btn small danger" name="mp_clawback" value="1" onclick="return confirm('Reverter todo o saldo desta conta e rejeitar o pedido?')">Reverter saldo</button></form><?php else: ?><span style="color:#788078">Processado</span><?php endif; ?></td></tr>
            <?php endforeach; ?>
            </tbody></table></div><?php endif; ?>
        </section>

        <div class="rmbz-sp-modal" id="rmbz-sp-settings" hidden aria-hidden="true"><div class="rmbz-sp-modal-backdrop" data-sp-close></div><div class="rmbz-sp-dialog" role="dialog" aria-modal="true" aria-labelledby="rmbz-sp-settings-title"><form method="post"><?php wp_nonce_field('mp_sponsored'); ?><header class="rmbz-sp-dialog-head"><div><h3 id="rmbz-sp-settings-title">Configurar programa</h3><p>Disponibilidade, limites, integridade e pagamentos.</p></div><button type="button" class="rmbz-sp-close" data-sp-close aria-label="Fechar">&times;</button></header><div class="rmbz-sp-dialog-body"><div class="rmbz-sp-fields"><label class="rmbz-sp-check rmbz-sp-field full"><input type="checkbox" name="mp_sponsored_on" <?php checked($program_on); ?>><span><strong>Programa ativo</strong><br><small>Permite apresentar faixas e creditar escutas elegíveis.</small></span></label><div class="rmbz-sp-field full"><label>Países globais elegíveis</label><textarea name="mp_sponsored_countries" rows="2" placeholder="MZ, AO, PT. Vazio permite todos."><?php echo esc_textarea(get_option('mp_sponsored_countries','')); ?></textarea></div><div class="rmbz-sp-field"><label>Pagamento mínimo ($)</label><input type="number" step="0.5" min="0" name="mp_sponsored_min_payout" value="<?php echo esc_attr(get_option('mp_sponsored_min_payout',5)); ?>"></div><div class="rmbz-sp-field"><label>Limite por faixa/dia (min)</label><input type="number" min="1" name="mp_sponsored_daily_cap_min" value="<?php echo esc_attr(get_option('mp_sponsored_daily_cap_min',30)); ?>"></div><div class="rmbz-sp-field"><label>Volume mínimo (%)</label><input type="number" min="0" max="100" name="mp_sponsored_min_volume" value="<?php echo esc_attr(get_option('mp_sponsored_min_volume',20)); ?>"><small>Zero desativa esta regra.</small></div><div class="rmbz-sp-field"><label>Pausa após volume baixo (min)</label><input type="number" min="1" max="120" name="mp_sponsored_vol_pause_min" value="<?php echo esc_attr(get_option('mp_sponsored_vol_pause_min',10)); ?>"></div><div class="rmbz-sp-field full"><label>Carro ou Bluetooth</label><select name="mp_sponsored_car_earn"><option value="allow" <?php selected(get_option('mp_sponsored_car_earn','flag'),'allow'); ?>>Permitir</option><option value="flag" <?php selected(get_option('mp_sponsored_car_earn','flag'),'flag'); ?>>Permitir e sinalizar</option><option value="block" <?php selected(get_option('mp_sponsored_car_earn','flag'),'block'); ?>>Bloquear ganho</option></select></div><div class="rmbz-sp-field full"><label>Métodos de pagamento</label><div class="rmbz-sp-methods"><?php foreach(['PayPal','M-Pesa','Emola'] as $method): ?><label class="rmbz-sp-check"><input type="checkbox" name="mp_sponsored_methods[]" value="<?php echo esc_attr($method); ?>" <?php checked(in_array($method,$methods,true)); ?>><span><?php echo esc_html($method); ?></span></label><?php endforeach; ?></div></div></div></div><footer class="rmbz-sp-dialog-foot"><button type="button" class="rmbz-sp-btn" data-sp-close>Cancelar</button><button class="rmbz-sp-btn primary" name="mp_sponsored_settings" value="1">Guardar configuração</button></footer></form></div></div>

        <div class="rmbz-sp-modal" id="rmbz-sp-track" hidden aria-hidden="true"><div class="rmbz-sp-modal-backdrop" data-sp-close></div><div class="rmbz-sp-dialog wide" role="dialog" aria-modal="true" aria-labelledby="rmbz-sp-track-title"><form method="post" id="rmbz-sp-track-form"><?php wp_nonce_field('mp_sponsored'); ?><input type="hidden" name="sp_id" id="rmbz-sp-id" value="0"><header class="rmbz-sp-dialog-head"><div><h3 id="rmbz-sp-track-title">Nova faixa patrocinada</h3><p>Define o conteúdo, público, remuneração e orçamento.</p></div><button type="button" class="rmbz-sp-close" data-sp-close aria-label="Fechar">&times;</button></header><div class="rmbz-sp-dialog-body"><div class="rmbz-sp-fields"><div class="rmbz-sp-field"><label>Título</label><input type="text" name="sp_title" id="rmbz-sp-title" required></div><div class="rmbz-sp-field"><label>Artista ou marca</label><input type="text" name="sp_artist" id="rmbz-sp-artist"></div><div class="rmbz-sp-field full"><label>Áudio</label><div class="rmbz-sp-picker"><input type="url" name="sp_audio" id="rmbz-sp-audio" required placeholder="https://"><button type="button" class="rmbz-sp-btn" id="rmbz-sp-pick-audio">Biblioteca</button></div><small>A duração é detetada quando o navegador consegue ler o ficheiro.</small></div><div class="rmbz-sp-field full"><label>Capa</label><div class="rmbz-sp-picker"><input type="url" name="sp_cover" id="rmbz-sp-cover" placeholder="https://"><button type="button" class="rmbz-sp-btn" id="rmbz-sp-pick-cover">Biblioteca</button></div></div><div class="rmbz-sp-field"><label>Países elegíveis</label><input type="text" name="sp_countries" id="rmbz-sp-countries" placeholder="MZ, AO, PT"></div><div class="rmbz-sp-field"><label>Duração (segundos)</label><input type="number" min="0" name="sp_duration" id="rmbz-sp-duration"></div><div class="rmbz-sp-field"><label>Taxa por minuto ($)</label><input type="number" step="0.0001" min="0" name="sp_rate" id="rmbz-sp-rate"></div><div class="rmbz-sp-field"><label>Orçamento total ($)</label><input type="number" step="0.01" min="0" name="sp_budget" id="rmbz-sp-budget"><small>Zero deixa a campanha sem limite financeiro.</small></div><label class="rmbz-sp-check rmbz-sp-field full"><input type="checkbox" name="sp_active" id="rmbz-sp-active" checked><span><strong>Faixa ativa</strong><br><small>Fica disponível no app assim que guardar.</small></span></label></div></div><footer class="rmbz-sp-dialog-foot"><button type="button" class="rmbz-sp-btn" data-sp-close>Cancelar</button><button class="rmbz-sp-btn primary" name="mp_sponsored_track" value="1">Guardar faixa</button></footer></form><audio id="rmbz-sp-probe" preload="metadata" hidden></audio></div></div>

        <script>
        (function(){
            var body=document.body, modals={settings:document.getElementById('rmbz-sp-settings'),track:document.getElementById('rmbz-sp-track')};
            function openModal(name){var modal=modals[name];if(!modal)return;modal.hidden=false;modal.setAttribute('aria-hidden','false');body.classList.add('rmbz-sp-admin-open');var focus=modal.querySelector('input:not([type=hidden]),button');if(focus)setTimeout(function(){focus.focus();},30);}
            function closeModal(modal){if(!modal)return;modal.hidden=true;modal.setAttribute('aria-hidden','true');body.classList.remove('rmbz-sp-admin-open');}
            document.querySelectorAll('[data-sp-open]').forEach(function(btn){btn.addEventListener('click',function(){if(btn.dataset.spOpen==='track')resetTrack();openModal(btn.dataset.spOpen);});});
            document.querySelectorAll('[data-sp-close]').forEach(function(btn){btn.addEventListener('click',function(){closeModal(btn.closest('.rmbz-sp-modal'));});});
            document.addEventListener('keydown',function(e){if(e.key==='Escape')document.querySelectorAll('.rmbz-sp-modal:not([hidden])').forEach(closeModal);});
            var fields={id:'rmbz-sp-id',title:'rmbz-sp-title',artist:'rmbz-sp-artist',audio:'rmbz-sp-audio',cover:'rmbz-sp-cover',countries:'rmbz-sp-countries',duration:'rmbz-sp-duration',rate:'rmbz-sp-rate',budget:'rmbz-sp-budget'};
            function resetTrack(){document.getElementById('rmbz-sp-track-form').reset();document.getElementById(fields.id).value=0;document.getElementById('rmbz-sp-active').checked=true;document.getElementById('rmbz-sp-track-title').textContent='Nova faixa patrocinada';}
            document.querySelectorAll('[data-sp-edit]').forEach(function(btn){btn.addEventListener('click',function(){var data=JSON.parse(btn.dataset.spEdit);Object.keys(fields).forEach(function(key){document.getElementById(fields[key]).value=data[key]===null?'':data[key];});document.getElementById('rmbz-sp-active').checked=Number(data.active)===1;document.getElementById('rmbz-sp-track-title').textContent='Editar faixa patrocinada';openModal('track');});});
            function mediaPicker(type,inputId){var frame=wp.media({title:type==='audio'?'Selecionar áudio':'Selecionar capa',button:{text:'Usar ficheiro'},library:{type:type},multiple:false});frame.on('select',function(){var item=frame.state().get('selection').first().toJSON();document.getElementById(inputId).value=item.url||'';if(type==='audio'&&item.fileLength)document.getElementById(fields.duration).value=Math.round(item.fileLength);if(type==='audio')probeAudio();});frame.open();}
            document.getElementById('rmbz-sp-pick-audio').addEventListener('click',function(){mediaPicker('audio',fields.audio);});document.getElementById('rmbz-sp-pick-cover').addEventListener('click',function(){mediaPicker('image',fields.cover);});
            function probeAudio(){var url=document.getElementById(fields.audio).value,probe=document.getElementById('rmbz-sp-probe');if(!url)return;probe.src=url;probe.onloadedmetadata=function(){if(isFinite(probe.duration))document.getElementById(fields.duration).value=Math.round(probe.duration);};}
            document.getElementById(fields.audio).addEventListener('change',probeAudio);
            var search=document.getElementById('rmbz-sp-search'),filter=document.getElementById('rmbz-sp-filter');function filterRows(){var q=(search.value||'').toLowerCase().trim(),state=filter.value;document.querySelectorAll('[data-sp-row]').forEach(function(row){row.hidden=!!(q&&row.dataset.search.indexOf(q)===-1)||!!(state!=='all'&&row.dataset.state!==state);});}search.addEventListener('input',filterRows);filter.addEventListener('change',filterRows);
        })();
        </script>
    </div>
    <?php
}

