<?php
/**
 * [1.5.413] PORTAL DA EQUIPA DE PRODUÇÃO 1MZ — página no site (minha-conta).
 *
 * A pessoa criada em "Equipas & Pessoas" entra no MESMO login do site com o
 * TELEFONE do perfil dela + um PIN inicial definido pelo admin. No primeiro
 * login é obrigada a definir um PIN novo. Depois vê um PAINEL MATERIAL 3
 * CLARO com navegação por separadores:
 *   - Início: saldo disponível em MT + botão LEVANTAR (eMola/M-Pesa),
 *     gravação a decorrer, próxima gravação, produções ativas e últimos
 *     movimentos da carteira;
 *   - Projetos: produções onde está atribuída (estado, progresso, papel,
 *     vistorias em nome dela + subsídio de multas);
 *   - Sessões: dias de gravação (duração, presenças por categoria, REC);
 *   - Agenda: próximas gravações;
 *   - Pagamentos: extrato da carteira (créditos + levantamentos);
 *   - Perfil: dados, cargos e alteração de PIN.
 *
 * LEVANTAMENTOS: fluxo em 3 passos (valor → carteira eMola/M-Pesa + número
 * → confirmação com taxa) — núcleo em includes/team-portal-withdrawals.php
 * (tabela rmbz_team_payouts; o admin aprova em "Equipa 💼 Carteira").
 *
 * Núcleo dos membros/PIN em includes/admin/project-team.php
 * (rmbz_team_find_by_phone, rmbz_team_verify_pin, rmbz_team_set_pin,
 *  rmbz_team_member_projects).
 *
 * Local: includes/team-portal-page.php
 */
if ( ! defined( 'ABSPATH' ) ) { exit; }

// =============================================================================
// SESSÃO
// =============================================================================

/** Membro da equipa com sessão ativa no site, ou null. */
function rmbz_team_portal_current() {
    if ( session_status() === PHP_SESSION_NONE && ! headers_sent() ) { session_start(); }
    $mid = isset( $_SESSION['rmbz_team_member_id'] ) ? (int) $_SESSION['rmbz_team_member_id'] : 0;
    if ( $mid <= 0 || ! function_exists( 'rmbz_team_get' ) ) return null;
    $m = rmbz_team_get( $mid );
    if ( ! $m || empty( $m->is_active ) || empty( $m->pin_hash ) ) {
        unset( $_SESSION['rmbz_team_member_id'] );
        return null;
    }
    return $m;
}

/** Abre a sessão do portal para um membro (depois do PIN verificado). */
function rmbz_team_portal_login( $member ) {
    global $wpdb;
    if ( session_status() === PHP_SESSION_NONE && ! headers_sent() ) { session_start(); }
    if ( function_exists( 'session_regenerate_id' ) ) { @session_regenerate_id( true ); }
    $_SESSION['rmbz_team_member_id'] = (int) $member->id;
    $wpdb->update(
        $wpdb->prefix . 'rmbz_team_members',
        [ 'last_login_at' => current_time( 'mysql' ) ],
        [ 'id' => (int) $member->id ]
    );
}

/** Fecha só a sessão do portal (não mexe na sessão de artista). */
function rmbz_team_portal_handle_logout() {
    if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( $_GET['_wpnonce'], 'rmbz_team_portal_logout' ) ) {
        rmbz_safe_redirect( home_url( '/minha-conta/' ) );
    }
    if ( session_status() === PHP_SESSION_NONE && ! headers_sent() ) { session_start(); }
    unset( $_SESSION['rmbz_team_member_id'] );
    rmbz_safe_redirect( home_url( '/minha-conta/' ) );
}
add_action( 'admin_post_rmbz_team_portal_logout', 'rmbz_team_portal_handle_logout' );
add_action( 'admin_post_nopriv_rmbz_team_portal_logout', 'rmbz_team_portal_handle_logout' );

/**
 * Trocar o PIN (obrigatório no primeiro login; voluntário depois).
 * Pede sempre o PIN ATUAL + novo (2×).
 */
function rmbz_team_portal_handle_change_pin() {
    if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( $_POST['_wpnonce'], 'rmbz_team_change_pin' ) ) {
        wp_die( 'Falha de segurança!' );
    }
    $m = rmbz_team_portal_current();
    if ( ! $m ) { rmbz_safe_redirect( home_url( '/minha-conta/' ) ); }

    $cur  = isset( $_POST['pin_atual'] ) ? trim( (string) wp_unslash( $_POST['pin_atual'] ) ) : '';
    $new  = isset( $_POST['pin_novo'] ) ? trim( (string) wp_unslash( $_POST['pin_novo'] ) ) : '';
    $new2 = isset( $_POST['pin_novo2'] ) ? trim( (string) wp_unslash( $_POST['pin_novo2'] ) ) : '';

    if ( ! rmbz_team_verify_pin( $m, $cur ) ) {
        $_SESSION['rmbz_team_notice'] = [ 'error', 'O PIN atual está errado.' ];
    } elseif ( ! preg_match( '/^\d{4,8}$/', $new ) ) {
        $_SESSION['rmbz_team_notice'] = [ 'error', 'O PIN novo deve ter 4 a 8 dígitos.' ];
    } elseif ( $new !== $new2 ) {
        $_SESSION['rmbz_team_notice'] = [ 'error', 'A confirmação do PIN novo não coincide.' ];
    } elseif ( $new === $cur ) {
        $_SESSION['rmbz_team_notice'] = [ 'error', 'O PIN novo tem de ser diferente do atual.' ];
    } else {
        $r = rmbz_team_set_pin( (int) $m->id, $new, false ); // false = já é o PIN dele
        $_SESSION['rmbz_team_notice'] = $r === true
            ? [ 'success', '✅ PIN atualizado — usa o novo a partir de agora.' ]
            : [ 'error', (string) $r ];
    }
    rmbz_safe_redirect( home_url( '/minha-conta/' ) );
}
add_action( 'admin_post_rmbz_team_change_pin', 'rmbz_team_portal_handle_change_pin' );
add_action( 'admin_post_nopriv_rmbz_team_change_pin', 'rmbz_team_portal_handle_change_pin' );

// =============================================================================
// DADOS DO PAINEL
// =============================================================================

/** Labels + cores CLARAS (M3) dos estados de produção. */
function rmbz_team_portal_status_meta( $st ) {
    $map = [
        'pending_review'     => [ 'Em Avaliação', '#FBEED0', '#8A6D00' ],
        'approved'           => [ 'Aprovado', '#D7EDDD', '#256C42' ],
        'kyc_review'         => [ 'KYC Pendente', '#FBEED0', '#8A6D00' ],
        'pre-production'     => [ 'Pré-Produção', '#E4E7F5', '#3B4FA0' ],
        'filming'            => [ 'Filmagem', '#FFE088', '#6B5300' ],
        'editing'            => [ 'Edição', '#EADDF5', '#6C3D9E' ],
        'done'               => [ 'Concluído', '#D7EDDD', '#256C42' ],
        'correction'         => [ 'Correção', '#FBEED0', '#8A6D00' ],
        'rejected'           => [ 'Rejeitado', '#FDE2E2', '#C01818' ],
        'cancelled_deadline' => [ 'Cancelado', '#F0E8D6', '#4C4639' ],
    ];
    return $map[ (string) $st ] ?? [ strtoupper( (string) $st ), '#F0E8D6', '#4C4639' ];
}

/**
 * Junta tudo o que o painel mostra por projeto para ESTE membro:
 * filmagem (datas, dias, REC), papel dele, vistorias em nome dele + estado,
 * multas pagas (subsídio repartido pela equipa do projeto).
 */
function rmbz_team_portal_project_info( $p, $member_id ) {
    $extra = isset( $p->rmbz_extra ) && is_array( $p->rmbz_extra ) ? $p->rmbz_extra : [];

    // Papéis dele NESTE projeto (escolhidos por projeto; senão todos os dele).
    $proles = ( isset( $extra['team_project_roles'][ $member_id ] ) && is_array( $extra['team_project_roles'][ $member_id ] ) )
        ? array_values( $extra['team_project_roles'][ $member_id ] ) : [];

    // Filmagem: datas + sessões (dias feitos, minutos, próxima data, REC).
    $sessions = ( isset( $extra['filming_sessions'] ) && is_array( $extra['filming_sessions'] ) ) ? $extra['filming_sessions'] : [];
    $days_done = 0; $total_min = 0; $next_date = ''; $live = false;
    foreach ( $sessions as $s ) {
        if ( ! is_array( $s ) ) continue;
        if ( empty( $s['ended_at'] ) ) { $live = true; continue; }
        $days_done++;
        $total_min += (int) ( $s['duration_min'] ?? 0 );
        if ( ! empty( $s['next_date'] ) ) $next_date = (string) $s['next_date'];
    }
    $percent_left = isset( $extra['filming_progress']['percent_left'] ) ? (int) $extra['filming_progress']['percent_left'] : -1;

    // Vistorias EM NOME DELE (itens do orçamento com team_fee_for = ele).
    $vist_total = 0.0; $vist_lines = [];
    $details = ! empty( $p->scenario_details ) ? json_decode( $p->scenario_details, true ) : [];
    if ( is_array( $details ) ) {
        foreach ( $details as $it ) {
            if ( ! is_array( $it ) || (int) ( $it['team_fee_for'] ?? 0 ) !== (int) $member_id ) continue;
            $cost = (float) ( $it['cost'] ?? 0 );
            $vist_total += $cost;
            $dk = (string) ( $it['team_fee_dept'] ?? '' );
            $dm = ( $dk !== '' && function_exists( 'rmbz_team_department_meta' ) )
                ? rmbz_team_department_meta( $dk ) : [ 'label' => 'Vistoria', 'icon' => '💰' ];
            $vist_lines[] = [ 'label' => (string) $dm['icon'] . ' ' . (string) $dm['label'], 'value' => $cost ];
        }
    }
    // Estado do pagamento da vistoria (agregado do projeto).
    $vs = function_exists( 'rmbz_team_vistoria_status' )
        ? rmbz_team_vistoria_status( $p )
        : [ 'total' => 0, 'left' => 0, 'blocked' => false ];
    $vist_paid = $vist_total > 0 && (float) $vs['left'] <= 0;

    // Subsídio: multas por atraso PAGAS neste projeto, repartidas pela
    // equipa atribuída (log começa a existir a partir da 1.5.412).
    $fines_paid = 0.0;
    if ( isset( $extra['fine_paid_log'] ) && is_array( $extra['fine_paid_log'] ) ) {
        foreach ( $extra['fine_paid_log'] as $f ) {
            if ( is_array( $f ) ) $fines_paid += (float) ( $f['amount'] ?? 0 );
        }
    }
    $team_count = ( isset( $extra['team_member_ids'] ) && is_array( $extra['team_member_ids'] ) )
        ? max( 1, count( $extra['team_member_ids'] ) ) : 1;
    $subsidy_share = $fines_paid > 0 ? round( $fines_paid / $team_count, 2 ) : 0.0;

    return [
        'roles'         => $proles,
        'filming_start' => (string) ( $extra['filming_start'] ?? '' ),
        'filming_end'   => (string) ( $extra['filming_end'] ?? '' ),
        'sessions'      => $sessions,
        'days_done'     => $days_done,
        'total_min'     => $total_min,
        'next_date'     => $next_date,
        'live'          => $live,
        'percent_left'  => $percent_left,
        'vist_total'    => round( $vist_total, 2 ),
        'vist_lines'    => $vist_lines,
        'vist_paid'     => $vist_paid,
        'vist_blocked'  => ! empty( $vs['blocked'] ),
        'fines_paid'    => round( $fines_paid, 2 ),
        'team_count'    => $team_count,
        'subsidy_share' => $subsidy_share,
    ];
}

// =============================================================================
// RENDER — painel Material 3 CLARO (dentro da página minha-conta)
// =============================================================================

function rmbz_team_portal_render() {
    $m = rmbz_team_portal_current();
    if ( ! $m ) return;

    $notice = null;
    if ( isset( $_SESSION['rmbz_team_notice'] ) && is_array( $_SESSION['rmbz_team_notice'] ) ) {
        $notice = $_SESSION['rmbz_team_notice'];
        unset( $_SESSION['rmbz_team_notice'] );
    }

    $must_change = ! empty( $m->pin_must_change );
    $roles = array_values( array_filter( array_map( 'trim', explode( '·', (string) ( $m->role ?? '' ) ) ) ) );
    $logout_url = wp_nonce_url( admin_url( 'admin-post.php?action=rmbz_team_portal_logout' ), 'rmbz_team_portal_logout' );
    $fmt = fn( $v ) => number_format( (float) $v, 2, ',', '.' );

    // ── Carteira (módulo team-portal-withdrawals.php) ──
    $saldo = function_exists( 'rmbz_team_wallet_balance' ) ? rmbz_team_wallet_balance( (int) $m->id ) : 0.0;
    $wd_pendente = function_exists( 'rmbz_team_wallet_pending_total' ) ? rmbz_team_wallet_pending_total( (int) $m->id ) : 0.0;
    $tot_ganho = function_exists( 'rmbz_team_wallet_total_earned' ) ? rmbz_team_wallet_total_earned( (int) $m->id ) : 0.0;
    $ledger = function_exists( 'rmbz_team_wallet_ledger' ) ? rmbz_team_wallet_ledger( (int) $m->id ) : [];
    $wd_cfg = function_exists( 'rmbz_team_wd_settings' ) ? rmbz_team_wd_settings() : [ 'fee_pct' => 2, 'fee_min' => 10, 'min' => 100 ];
    $tel9 = function_exists( 'rmbz_team_normalize_phone' ) ? rmbz_team_normalize_phone( (string) ( $m->phone ?? '' ) ) : '';

    // ── Projetos + agregados ──
    $projects = [];
    $tot_vist = 0.0; $tot_subsidio = 0.0; $tot_dias = 0; $ativos = 0;
    $live_proj = ''; $sess_list = []; $agenda = [];
    $hoje = current_time( 'Y-m-d' );
    if ( ! $must_change && function_exists( 'rmbz_team_member_projects' ) ) {
        foreach ( rmbz_team_member_projects( (int) $m->id ) as $p ) {
            $info = rmbz_team_portal_project_info( $p, (int) $m->id );
            $projects[] = [ 'p' => $p, 'i' => $info ];
            $tot_vist     += $info['vist_total'];
            $tot_subsidio += $info['subsidy_share'];
            $tot_dias     += $info['days_done'];
            $title = (string) ( $p->project_title ?: '(sem título)' );
            if ( $info['live'] && $live_proj === '' ) $live_proj = $title;
            if ( in_array( (string) $p->production_status, [ 'approved', 'kyc_review', 'pre-production', 'filming', 'editing' ], true ) ) $ativos++;

            // Sessões (mais recentes primeiro no fim).
            $day_n = 0;
            foreach ( $info['sessions'] as $s ) {
                if ( ! is_array( $s ) ) continue;
                $day_n++;
                $cats = [];
                foreach ( (array) ( $s['participants'] ?? [] ) as $pp ) {
                    if ( ! is_array( $pp ) ) continue;
                    $ck = (string) ( $pp['category'] ?? 'outro' );
                    $cats[ $ck ] = ( $cats[ $ck ] ?? 0 ) + 1;
                }
                $chips = [];
                foreach ( $cats as $ck => $n ) {
                    $meta = function_exists( 'rmbz_fs_category_meta' ) ? rmbz_fs_category_meta( $ck ) : [ 'label' => ucfirst( $ck ), 'icon' => '👤' ];
                    $chips[] = (string) $meta['icon'] . ' ' . (string) $meta['label'] . ' (' . (int) $n . ')';
                }
                $started = ! empty( $s['started_at'] ) ? date_i18n( 'd/m/Y', strtotime( (string) $s['started_at'] ) ) : '—';
                $dur_min = (int) ( $s['duration_min'] ?? 0 );
                $sess_list[] = [
                    'proj'  => $title,
                    'dia'   => $day_n,
                    'data'  => $started,
                    'live'  => empty( $s['ended_at'] ),
                    'dur'   => $dur_min > 0 ? floor( $dur_min / 60 ) . 'h' . ( $dur_min % 60 ) . 'm' : '',
                    'chips' => $chips,
                    'ts'    => ! empty( $s['started_at'] ) ? strtotime( (string) $s['started_at'] ) : 0,
                ];
            }

            // Agenda: próxima gravação (continuação) ou início de filmagem futuro.
            if ( $info['next_date'] !== '' && $info['next_date'] >= $hoje ) {
                $agenda[] = [ 'date' => $info['next_date'], 'titulo' => '«' . $title . '» — continuação da filmagem', 'sub' => $info['percent_left'] > 0 ? 'Falta ' . (int) $info['percent_left'] . '% para terminar' : 'Dia de gravação' ];
            } elseif ( $info['filming_start'] !== '' && $info['filming_start'] >= $hoje && $info['days_done'] === 0 && ! $info['live'] ) {
                $agenda[] = [ 'date' => $info['filming_start'], 'titulo' => '«' . $title . '» — início da filmagem', 'sub' => $info['filming_end'] !== '' ? 'Filmagem até ' . date_i18n( 'd/m/Y', strtotime( $info['filming_end'] . ' 12:00' ) ) : 'Primeiro dia de gravação' ];
            }
        }
    }
    usort( $sess_list, fn( $a, $b ) => $b['ts'] <=> $a['ts'] );
    usort( $agenda, fn( $a, $b ) => strcmp( $a['date'], $b['date'] ) );
    $prox = $agenda[0] ?? null;

    $meses = [ 1=>'JAN',2=>'FEV',3=>'MAR',4=>'ABR',5=>'MAI',6=>'JUN',7=>'JUL',8=>'AGO',9=>'SET',10=>'OUT',11=>'NOV',12=>'DEZ' ];
    $initial = mb_strtoupper( mb_substr( (string) $m->name, 0, 1 ) );
    ?>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Roboto+Flex:opsz,wght@8..144,400..800&family=Roboto+Mono:wght@500;600&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,GRAD@20..48,300..600,0..1,0" rel="stylesheet">
    <div class="rmbz-fullbleed">
    <style>
    .rmbz-tpx{ background:#FBF6EA; color:#1E1B13; font-family:'Roboto Flex',system-ui,sans-serif; border-radius:28px; max-width:1120px; margin:0 auto 30px; padding:26px clamp(14px,3.5vw,36px) 40px; }
    .rmbz-tpx *{ box-sizing:border-box; }
    .rmbz-tpx .ms{ font-family:'Material Symbols Rounded'; font-weight:400; font-style:normal; line-height:1; display:inline-flex; vertical-align:middle; }
    .rmbz-tpx-mono{ font-family:'Roboto Mono',monospace; }
    .rmbz-tpx-card{ background:#FFFCF5; border:1px solid #E3DAC6; border-radius:22px; padding:22px; }
    .rmbz-tpx-hero{ display:flex; align-items:center; gap:16px; flex-wrap:wrap; margin-bottom:18px; }
    .rmbz-tpx-avatar{ width:64px; height:64px; border-radius:50%; object-fit:cover; background:#755C00; display:flex; align-items:center; justify-content:center; font-size:26px; font-weight:800; color:#fff; flex-shrink:0; }
    .rmbz-tpx-chip{ display:inline-block; background:#EEE2BC; color:#221B04; font-size:12px; font-weight:650; border-radius:99px; padding:5px 13px; margin:4px 4px 0 0; }
    .rmbz-tpx-pill{ display:inline-flex; align-items:center; gap:8px; border-radius:99px; padding:11px 22px; font-size:13.5px; font-weight:700; text-decoration:none; cursor:pointer; border:0; transition:filter .15s, background .15s; }
    .rmbz-tpx-pill--primary{ background:#755C00; color:#fff !important; box-shadow:0 2px 8px rgba(78,61,0,.25); }
    .rmbz-tpx-pill--primary:hover{ background:#5F4B00; color:#fff; }
    .rmbz-tpx-pill--ghost{ background:transparent; color:#755C00 !important; border:1px solid #D8CCB2; }
    .rmbz-tpx-pill--ghost:hover{ background:#F5EFDF; }
    .rmbz-tpx-tabs{ display:flex; gap:6px; flex-wrap:wrap; margin:6px 0 22px; }
    .rmbz-tpx-tab{ display:inline-flex; align-items:center; gap:9px; border:0; background:transparent; color:#4C4639; font-family:inherit; font-size:13.5px; font-weight:550; padding:11px 18px; border-radius:99px; cursor:pointer; transition:background .15s; }
    .rmbz-tpx-tab:hover{ background:#EDE4CF; }
    .rmbz-tpx-tab.on{ background:#EEE2BC; color:#221B04; font-weight:700; }
    .rmbz-tpx-notice{ border-radius:16px; padding:13px 18px; font-size:13.5px; font-weight:650; margin-bottom:16px; }
    .rmbz-tpx-notice.error{ background:#FDE2E2; border:1px solid #F2B8B5; color:#8C1D18; }
    .rmbz-tpx-notice.success{ background:#D7EDDD; border:1px solid #A6D8B8; color:#1D5233; }
    .rmbz-tpx-status{ display:inline-flex; align-items:center; font-size:11.5px; font-weight:700; border-radius:99px; padding:5px 13px; white-space:nowrap; }
    .rmbz-tpx-mini{ font-size:12.5px; color:#4C4639; line-height:1.6; }
    .rmbz-tpx-sect{ font-size:12px; font-weight:800; color:#755C00; letter-spacing:1px; text-transform:uppercase; margin:24px 0 12px; }
    .rmbz-tpx-input{ width:100%; background:#FFFCF5; border:1.5px solid #D8CCB2; border-radius:14px; padding:12px 16px; font-size:15px; color:#1E1B13; font-weight:700; font-family:inherit; }
    .rmbz-tpx-input:focus{ border-color:#755C00; outline:none; box-shadow:0 0 0 3px rgba(117,92,0,.15); }
    .rmbz-tpx-label{ display:block; font-size:11px; font-weight:750; color:#4C4639; letter-spacing:.6px; text-transform:uppercase; margin:14px 0 6px; }
    .rmbz-tpx-rec{ color:#C01818; font-weight:800; animation:rmbzTpxBlink 1s infinite; }
    @keyframes rmbzTpxBlink{ 50%{ opacity:.25; } }
    .rmbz-tpx-grid2{ display:grid; grid-template-columns:1fr 1fr; gap:16px; }
    .rmbz-tpx-grid3{ display:grid; grid-template-columns:repeat(auto-fill,minmax(240px,1fr)); gap:16px; }
    @media (max-width:760px){ .rmbz-tpx-grid2{ grid-template-columns:1fr; } }
    .rmbz-tpx-money{ background:#F3F9F1; border:1px solid #BFE0C8; border-radius:14px; padding:12px 16px; margin-top:12px; }
    .rmbz-tpx-money.pending{ background:#FBF3DA; border-color:#EAD48F; }
    .rmbz-tpx-row{ display:flex; align-items:center; justify-content:space-between; gap:10px; flex-wrap:wrap; }
    .rmbz-tpx-table{ width:100%; border-collapse:collapse; min-width:640px; }
    .rmbz-tpx-table th{ text-align:left; font-size:11px; font-weight:800; color:#4C4639; letter-spacing:.5px; padding:12px 10px; border-bottom:1px solid #E3DAC6; }
    .rmbz-tpx-table td{ font-size:13.5px; padding:14px 10px; border-bottom:1px solid #F0E8D6; }
    .rmbz-tpx-badge{ display:inline-block; font-size:11.5px; font-weight:750; border-radius:99px; padding:4px 12px; }
    /* Dialog levantamento */
    .rmbz-tpx-scrim{ position:fixed; inset:0; background:rgba(30,27,19,.5); display:none; align-items:center; justify-content:center; z-index:99999; padding:16px; }
    .rmbz-tpx-scrim.open{ display:flex; }
    .rmbz-tpx-dialog{ background:#FBF5E7; border-radius:28px; width:440px; max-width:100%; max-height:92vh; overflow-y:auto; padding:26px 28px; }
    .rmbz-tpx-step{ display:none; }
    .rmbz-tpx-step.on{ display:block; }
    .rmbz-tpx-met{ display:flex; align-items:center; gap:14px; width:100%; border:2px solid #E3DAC6; background:#FFFCF5; border-radius:18px; padding:14px 16px; text-align:left; cursor:pointer; font-family:inherit; margin-bottom:10px; }
    .rmbz-tpx-met.on{ border-color:#755C00; background:#FFF3D0; }
    .rmbz-tpx-amt-chip{ border:1px solid #D8CCB2; background:transparent; color:#221B04; font-family:inherit; font-size:13px; font-weight:650; padding:9px 16px; border-radius:99px; cursor:pointer; }
    .rmbz-tpx-amt-chip:hover{ background:#EEE2BC; }
    </style>
    <div class="rmbz-tpx" id="rmbz-tpx"
         data-saldo="<?php echo esc_attr( $saldo ); ?>"
         data-min="<?php echo esc_attr( $wd_cfg['min'] ); ?>"
         data-fee-pct="<?php echo esc_attr( $wd_cfg['fee_pct'] ); ?>"
         data-fee-min="<?php echo esc_attr( $wd_cfg['fee_min'] ); ?>">

        <?php if ( $notice ): ?>
            <div class="rmbz-tpx-notice <?php echo esc_attr( $notice[0] ); ?>"><?php echo esc_html( $notice[1] ); ?></div>
        <?php endif; ?>

        <!-- HERO -->
        <div class="rmbz-tpx-hero">
            <?php if ( ! empty( $m->photo_url ) ): ?>
                <img class="rmbz-tpx-avatar" src="<?php echo esc_url( $m->photo_url ); ?>" alt="">
            <?php else: ?>
                <div class="rmbz-tpx-avatar"><?php echo esc_html( $initial ); ?></div>
            <?php endif; ?>
            <div style="flex:1; min-width:200px;">
                <div style="font-size:11px; font-weight:800; color:#755C00; letter-spacing:1px; text-transform:uppercase;">🎬 Equipa de Produção 1MZ</div>
                <p style="margin:4px 0 0; font-size:22px; font-weight:750; letter-spacing:-.01em; color:#1E1B13;"><?php echo esc_html( $m->name ); ?></p>
                <div>
                    <?php foreach ( array_slice( $roles, 0, 5 ) as $r ): ?>
                        <span class="rmbz-tpx-chip"><?php echo esc_html( $r ); ?></span>
                    <?php endforeach; ?>
                </div>
            </div>
            <a class="rmbz-tpx-pill rmbz-tpx-pill--ghost" href="<?php echo esc_url( $logout_url ); ?>"><span class="ms" style="font-size:18px;">logout</span> Sair</a>
        </div>

        <?php if ( $must_change ): ?>
            <!-- PRIMEIRO LOGIN: definir PIN novo (obrigatório) -->
            <div class="rmbz-tpx-card" style="max-width:460px; margin:24px auto;">
                <p style="font-size:17px; font-weight:750; margin:0;">🔐 Define o teu PIN</p>
                <p class="rmbz-tpx-mini" style="margin:8px 0 0;">
                    Entraste com o PIN inicial dado pela administração. Por segurança, tens de definir agora um <b>PIN novo só teu</b> (4 a 8 dígitos) — vai ser o teu acesso ao portal a partir de agora.
                </p>
                <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
                    <input type="hidden" name="action" value="rmbz_team_change_pin">
                    <?php wp_nonce_field( 'rmbz_team_change_pin' ); ?>
                    <label class="rmbz-tpx-label">PIN atual (o que a administração te deu)</label>
                    <input class="rmbz-tpx-input" type="password" name="pin_atual" inputmode="numeric" maxlength="8" required autocomplete="current-password" style="letter-spacing:4px; text-align:center;">
                    <label class="rmbz-tpx-label">PIN novo (4–8 dígitos)</label>
                    <input class="rmbz-tpx-input" type="password" name="pin_novo" inputmode="numeric" pattern="\d{4,8}" maxlength="8" required autocomplete="new-password" style="letter-spacing:4px; text-align:center;">
                    <label class="rmbz-tpx-label">Repete o PIN novo</label>
                    <input class="rmbz-tpx-input" type="password" name="pin_novo2" inputmode="numeric" pattern="\d{4,8}" maxlength="8" required autocomplete="new-password" style="letter-spacing:4px; text-align:center;">
                    <button type="submit" class="rmbz-tpx-pill rmbz-tpx-pill--primary" style="width:100%; justify-content:center; margin-top:18px; padding:14px;">💾 Guardar PIN novo e entrar</button>
                </form>
            </div>
        <?php else: ?>

        <!-- TABS -->
        <nav class="rmbz-tpx-tabs" role="tablist">
            <?php
            $tabs = [
                'inicio'     => [ 'dashboard',      'Início' ],
                'projetos'   => [ 'movie',          'Projetos' ],
                'sessoes'    => [ 'videocam',       'Sessões' ],
                'agenda'     => [ 'calendar_month', 'Agenda' ],
                'pagamentos' => [ 'receipt_long',   'Pagamentos' ],
                'perfil'     => [ 'person',         'Perfil' ],
            ];
            $first = true;
            foreach ( $tabs as $tk => $tv ): ?>
                <button type="button" class="rmbz-tpx-tab<?php echo $first ? ' on' : ''; ?>" data-tab="<?php echo esc_attr( $tk ); ?>">
                    <span class="ms" style="font-size:20px;"><?php echo esc_html( $tv[0] ); ?></span><?php echo esc_html( $tv[1] ); ?>
                </button>
            <?php $first = false; endforeach; ?>
        </nav>

        <!-- ══════ INÍCIO ══════ -->
        <section data-panel="inicio" data-screen-label="Início">
            <!-- SALDO HERO -->
            <div style="background:#FFE088; border-radius:26px; padding:26px 30px; display:flex; align-items:center; justify-content:space-between; gap:22px; flex-wrap:wrap;">
                <div>
                    <div style="font-size:12.5px; font-weight:700; color:#4E3D00; display:flex; align-items:center; gap:8px;">
                        <span class="ms" style="font-size:19px;">account_balance_wallet</span> SALDO DISPONÍVEL
                    </div>
                    <div class="rmbz-tpx-mono" style="font-size:clamp(30px,5vw,42px); font-weight:600; color:#251A00; margin:6px 0 12px; letter-spacing:-.02em;"><?php echo esc_html( $fmt( $saldo ) ); ?> MT</div>
                    <div style="display:flex; gap:8px; flex-wrap:wrap;">
                        <span style="background:rgba(255,255,255,.55); border-radius:99px; padding:6px 14px; font-size:12px; font-weight:650; color:#4E3D00;">Levantamento pendente: <?php echo esc_html( $fmt( $wd_pendente ) ); ?> MT</span>
                        <span style="background:rgba(255,255,255,.55); border-radius:99px; padding:6px 14px; font-size:12px; font-weight:650; color:#4E3D00;">Total ganho: <?php echo esc_html( $fmt( $tot_ganho ) ); ?> MT</span>
                    </div>
                </div>
                <div style="display:flex; flex-direction:column; gap:10px;">
                    <button type="button" class="rmbz-tpx-pill rmbz-tpx-pill--primary" id="rmbz-tpx-open-wd" style="padding:14px 28px; font-size:15px;">
                        <span class="ms" style="font-size:20px;">payments</span> Levantar
                    </button>
                    <button type="button" class="rmbz-tpx-pill" data-goto="pagamentos" style="background:rgba(255,255,255,.6); color:#4E3D00; justify-content:center;">Histórico</button>
                </div>
            </div>

            <?php if ( $live_proj !== '' ): ?>
                <div class="rmbz-tpx-notice success" style="margin-top:16px; margin-bottom:0;"><span class="rmbz-tpx-rec">● REC</span> &nbsp;Gravação A DECORRER agora em «<?php echo esc_html( $live_proj ); ?>» — bom trabalho no terreno! 🎬</div>
            <?php endif; ?>

            <div class="rmbz-tpx-grid2" style="margin-top:16px;">
                <div class="rmbz-tpx-card">
                    <div style="font-size:12px; font-weight:750; color:#755C00; display:flex; align-items:center; gap:8px; margin-bottom:12px;">
                        <span class="ms" style="font-size:19px;">event_upcoming</span> PRÓXIMA GRAVAÇÃO
                    </div>
                    <?php if ( $prox ):
                        $pts = strtotime( $prox['date'] . ' 12:00' ); ?>
                        <div style="display:flex; gap:16px; align-items:center;">
                            <div style="background:#EEE2BC; border-radius:16px; padding:10px 16px; text-align:center; flex-shrink:0;">
                                <div style="font-size:23px; font-weight:750; color:#221B04; line-height:1.1;"><?php echo esc_html( date_i18n( 'd', $pts ) ); ?></div>
                                <div style="font-size:11px; font-weight:700; color:#4C4639;"><?php echo esc_html( $meses[ (int) date( 'n', $pts ) ] ); ?></div>
                            </div>
                            <div>
                                <div style="font-size:15px; font-weight:650;"><?php echo esc_html( $prox['titulo'] ); ?></div>
                                <div class="rmbz-tpx-mini" style="margin-top:3px;"><?php echo esc_html( $prox['sub'] ); ?></div>
                            </div>
                        </div>
                    <?php else: ?>
                        <p class="rmbz-tpx-mini" style="margin:0;">Sem gravações marcadas para os próximos dias.</p>
                    <?php endif; ?>
                </div>
                <div class="rmbz-tpx-card">
                    <div style="font-size:12px; font-weight:750; color:#755C00; display:flex; align-items:center; gap:8px; margin-bottom:12px;">
                        <span class="ms" style="font-size:19px;">insights</span> O TEU TRABALHO
                    </div>
                    <div style="display:flex; gap:26px; flex-wrap:wrap;">
                        <div><div style="font-size:22px; font-weight:750;"><?php echo count( $projects ); ?></div><div class="rmbz-tpx-mini" style="font-weight:650;">PRODUÇÕES</div></div>
                        <div><div style="font-size:22px; font-weight:750;"><?php echo (int) $ativos; ?></div><div class="rmbz-tpx-mini" style="font-weight:650;">EM CURSO</div></div>
                        <div><div style="font-size:22px; font-weight:750;"><?php echo (int) $tot_dias; ?></div><div class="rmbz-tpx-mini" style="font-weight:650;">DIAS FILMADOS</div></div>
                        <div><div style="font-size:22px; font-weight:750;"><?php echo esc_html( $fmt( $tot_vist + $tot_subsidio ) ); ?> <small style="font-size:12px;">MT</small></div><div class="rmbz-tpx-mini" style="font-weight:650;">VISTORIAS + SUBSÍDIOS</div></div>
                    </div>
                </div>
            </div>

            <?php if ( ! empty( $ledger ) ): ?>
                <div class="rmbz-tpx-sect">Últimos movimentos</div>
                <div class="rmbz-tpx-card" style="padding:6px 22px;">
                    <?php foreach ( array_slice( $ledger, 0, 3 ) as $row ): ?>
                        <div style="display:flex; align-items:center; gap:14px; padding:13px 0; border-bottom:1px solid #F0E8D6;">
                            <span class="ms" style="font-size:20px; width:38px; height:38px; border-radius:50%; align-items:center; justify-content:center; background:<?php echo $row->type === 'credit' ? '#D7EDDD' : '#F0E8D6'; ?>; color:<?php echo $row->type === 'credit' ? '#256C42' : '#755C00'; ?>;"><?php echo $row->type === 'credit' ? 'south_west' : 'north_east'; ?></span>
                            <div style="flex:1; min-width:0;">
                                <div style="font-size:13.5px; font-weight:650; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;"><?php echo esc_html( (string) $row->details ); ?></div>
                                <div class="rmbz-tpx-mini"><?php echo esc_html( date_i18n( 'd/m/Y', strtotime( (string) $row->created_at ) ) ); ?><?php echo $row->type === 'debit' ? ' · ' . esc_html( rmbz_team_wd_method_label( $row->method ) ) : ''; ?></div>
                            </div>
                            <span class="rmbz-tpx-mono" style="font-size:13.5px; font-weight:600; color:<?php echo $row->type === 'credit' ? '#256C42' : '#1E1B13'; ?>;"><?php echo ( $row->type === 'credit' ? '+ ' : '− ' ) . esc_html( $fmt( $row->amount ) ); ?> MT</span>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </section>

        <!-- ══════ PROJETOS ══════ -->
        <section data-panel="projetos" data-screen-label="Projetos" hidden>
            <?php if ( empty( $projects ) ): ?>
                <div class="rmbz-tpx-card" style="text-align:center;">
                    <div style="font-size:40px; opacity:.4;">🎥</div>
                    <p style="margin:6px 0 0; font-weight:700;">Ainda não estás atribuído(a) a nenhuma produção.</p>
                    <p class="rmbz-tpx-mini" style="margin:4px 0 0;">Quando a administração te colocar na equipa de um videoclipe, ele aparece aqui.</p>
                </div>
            <?php else: ?>
                <div class="rmbz-tpx-grid2">
                <?php foreach ( $projects as $row ):
                    $p = $row['p']; $i = $row['i'];
                    [ $st_label, $st_bg, $st_fg ] = rmbz_team_portal_status_meta( $p->production_status );
                ?>
                    <div class="rmbz-tpx-card">
                        <div class="rmbz-tpx-row" style="align-items:flex-start;">
                            <div style="min-width:0;">
                                <p style="margin:0; font-size:16px; font-weight:750;">«<?php echo esc_html( $p->project_title ?: '(sem título)' ); ?>»</p>
                                <p class="rmbz-tpx-mini" style="margin:2px 0 0;">Artista: <b style="color:#1E1B13;"><?php echo esc_html( $p->user_nome ?: '—' ); ?></b></p>
                            </div>
                            <span class="rmbz-tpx-status" style="background:<?php echo esc_attr( $st_bg ); ?>; color:<?php echo esc_attr( $st_fg ); ?>;"><?php echo esc_html( $st_label ); ?></span>
                        </div>

                        <?php if ( ! empty( $i['roles'] ) ): ?>
                            <div style="margin-top:8px;">
                                <?php foreach ( $i['roles'] as $r ): ?>
                                    <span class="rmbz-tpx-chip"><?php echo esc_html( $r ); ?></span>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>

                        <div class="rmbz-tpx-mini" style="margin-top:10px;">
                            <?php if ( $i['live'] ): ?>
                                <span class="rmbz-tpx-rec">● REC</span> <b style="color:#1E1B13;">Gravação a decorrer AGORA</b><br>
                            <?php endif; ?>
                            <?php if ( $i['filming_start'] !== '' || $i['filming_end'] !== '' ): ?>
                                📅 Filmagem: <b style="color:#1E1B13;"><?php echo esc_html( $i['filming_start'] ?: '—' ); ?></b>
                                <?php if ( $i['filming_end'] !== '' ): ?> → <b style="color:#1E1B13;"><?php echo esc_html( $i['filming_end'] ); ?></b><?php endif; ?><br>
                            <?php endif; ?>
                            <?php if ( $i['days_done'] > 0 ): ?>
                                🎬 <?php echo (int) $i['days_done']; ?> dia(s) filmado(s)
                                <?php if ( $i['total_min'] > 0 ): ?> · ⏱️ <?php echo (int) floor( $i['total_min'] / 60 ); ?>h<?php echo (int) ( $i['total_min'] % 60 ); ?>m no terreno<?php endif; ?><br>
                            <?php endif; ?>
                            <?php if ( $i['percent_left'] > 0 ): ?>
                                📊 Falta <?php echo (int) $i['percent_left']; ?>% para terminar
                                <?php if ( $i['next_date'] !== '' ): ?> · próxima gravação: <b style="color:#1E1B13;"><?php echo esc_html( $i['next_date'] ); ?></b><?php endif; ?>
                            <?php endif; ?>
                        </div>

                        <?php if ( $i['vist_total'] > 0 ): ?>
                            <div class="rmbz-tpx-money <?php echo $i['vist_paid'] ? '' : 'pending'; ?>">
                                <div class="rmbz-tpx-row">
                                    <span style="font-size:12px; font-weight:750;">💰 Vistoria em teu nome nesta produção</span>
                                    <span class="rmbz-tpx-mono" style="font-size:14px; font-weight:600;"><?php echo esc_html( $fmt( $i['vist_total'] ) ); ?> MT</span>
                                </div>
                                <?php foreach ( $i['vist_lines'] as $vl ): ?>
                                    <div class="rmbz-tpx-mini" style="display:flex; justify-content:space-between;">
                                        <span><?php echo esc_html( $vl['label'] ); ?></span>
                                        <span><?php echo esc_html( $fmt( $vl['value'] ) ); ?> MT</span>
                                    </div>
                                <?php endforeach; ?>
                                <div class="rmbz-tpx-mini" style="margin-top:4px; font-weight:750; color:<?php echo $i['vist_paid'] ? '#256C42' : '#8A6D00'; ?>;">
                                    <?php echo $i['vist_paid']
                                        ? '✅ Paga pelo artista — a administração credita na tua carteira.'
                                        : ( $i['vist_blocked']
                                            ? '🔒 Por pagar — o projeto está bloqueado até o artista regularizar.'
                                            : '⏳ Ainda por cobrar ao artista (vence no fim da filmagem).' ); ?>
                                </div>
                            </div>
                        <?php endif; ?>

                        <?php if ( $i['fines_paid'] > 0 ): ?>
                            <div class="rmbz-tpx-money" style="background:#F1EDF9; border-color:#CFC2E8;">
                                <div class="rmbz-tpx-row">
                                    <span style="font-size:12px; font-weight:750;">🎁 Subsídio — multas de atraso pagas</span>
                                    <span class="rmbz-tpx-mono" style="font-size:14px; font-weight:600;"><?php echo esc_html( $fmt( $i['subsidy_share'] ) ); ?> MT</span>
                                </div>
                                <div class="rmbz-tpx-mini">
                                    Total de multas pagas: <?php echo esc_html( $fmt( $i['fines_paid'] ) ); ?> MT, repartido pela equipa (<?php echo (int) $i['team_count']; ?> pessoa<?php echo $i['team_count'] > 1 ? 's' : ''; ?>).
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </section>

        <!-- ══════ SESSÕES ══════ -->
        <section data-panel="sessoes" data-screen-label="Sessões" hidden>
            <?php if ( empty( $sess_list ) ): ?>
                <div class="rmbz-tpx-card" style="text-align:center;">
                    <div style="font-size:40px; opacity:.4;">🎬</div>
                    <p style="margin:6px 0 0; font-weight:700;">Ainda sem dias de gravação registados.</p>
                    <p class="rmbz-tpx-mini" style="margin:4px 0 0;">Quando a equipa iniciar uma gravação num dos teus projetos, o dia aparece aqui com as presenças.</p>
                </div>
            <?php else: ?>
                <div style="display:flex; flex-direction:column; gap:14px;">
                <?php foreach ( $sess_list as $s ): ?>
                    <div class="rmbz-tpx-card" style="display:flex; gap:18px; align-items:center; flex-wrap:wrap;">
                        <div style="background:<?php echo $s['live'] ? '#256C42' : '#EEE2BC'; ?>; color:<?php echo $s['live'] ? '#FFFFFF' : '#221B04'; ?>; border-radius:16px; width:60px; height:60px; display:flex; flex-direction:column; align-items:center; justify-content:center; flex-shrink:0;">
                            <div style="font-size:10.5px; font-weight:750;">DIA</div>
                            <div style="font-size:21px; font-weight:800; line-height:1;"><?php echo (int) $s['dia']; ?></div>
                        </div>
                        <div style="flex:1; min-width:220px;">
                            <div style="font-size:15px; font-weight:700;">«<?php echo esc_html( $s['proj'] ); ?>» — <?php echo esc_html( $s['data'] ); ?></div>
                            <div class="rmbz-tpx-mini" style="margin-top:3px;">
                                <?php echo $s['live'] ? '<span class="rmbz-tpx-rec">● REC</span> Gravação a decorrer agora' : ( $s['dur'] !== '' ? '⏱️ ' . esc_html( $s['dur'] ) . ' de filmagem' : 'Dia concluído' ); ?>
                            </div>
                            <?php if ( ! empty( $s['chips'] ) ): ?>
                                <div style="display:flex; gap:6px; margin-top:9px; flex-wrap:wrap;">
                                    <?php foreach ( $s['chips'] as $c ): ?>
                                        <span style="background:#F0E8D6; border-radius:99px; padding:4px 12px; font-size:11.5px; font-weight:600; color:#4C4639;"><?php echo esc_html( $c ); ?></span>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                        <span class="rmbz-tpx-status" style="background:<?php echo $s['live'] ? '#D7EDDD' : '#F0E8D6'; ?>; color:<?php echo $s['live'] ? '#256C42' : '#4C4639'; ?>;"><?php echo $s['live'] ? 'ATIVA' : 'CONCLUÍDA'; ?></span>
                    </div>
                <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </section>

        <!-- ══════ AGENDA ══════ -->
        <section data-panel="agenda" data-screen-label="Agenda" hidden>
            <?php if ( empty( $agenda ) ): ?>
                <div class="rmbz-tpx-card" style="text-align:center;">
                    <div style="font-size:40px; opacity:.4;">📅</div>
                    <p style="margin:6px 0 0; font-weight:700;">Sem gravações marcadas.</p>
                    <p class="rmbz-tpx-mini" style="margin:4px 0 0;">As próximas datas de filmagem dos teus projetos aparecem aqui.</p>
                </div>
            <?php else: ?>
                <div style="display:flex; flex-direction:column; gap:12px;">
                <?php foreach ( $agenda as $ev ):
                    $ts = strtotime( $ev['date'] . ' 12:00' ); ?>
                    <div class="rmbz-tpx-card" style="display:flex; align-items:center; gap:18px; padding:16px 22px;">
                        <div style="background:#EEE2BC; border-radius:14px; padding:9px 15px; text-align:center; flex-shrink:0; min-width:48px;">
                            <div style="font-size:20px; font-weight:750; color:#221B04; line-height:1.1;"><?php echo esc_html( date_i18n( 'd', $ts ) ); ?></div>
                            <div style="font-size:10.5px; font-weight:700; color:#4C4639;"><?php echo esc_html( $meses[ (int) date( 'n', $ts ) ] ); ?></div>
                        </div>
                        <div style="flex:1;">
                            <div style="font-size:14.5px; font-weight:700;"><?php echo esc_html( $ev['titulo'] ); ?></div>
                            <div class="rmbz-tpx-mini" style="margin-top:2px;"><?php echo esc_html( $ev['sub'] ); ?></div>
                        </div>
                        <span class="ms" style="font-size:22px; color:#755C00;">videocam</span>
                    </div>
                <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </section>

        <!-- ══════ PAGAMENTOS ══════ -->
        <section data-panel="pagamentos" data-screen-label="Pagamentos" hidden>
            <?php if ( empty( $ledger ) ): ?>
                <div class="rmbz-tpx-card" style="text-align:center;">
                    <div style="font-size:40px; opacity:.4;">🧾</div>
                    <p style="margin:6px 0 0; font-weight:700;">Ainda sem movimentos na carteira.</p>
                    <p class="rmbz-tpx-mini" style="margin:4px 0 0;">Os teus ganhos (vistorias, subsídios) e levantamentos aparecem aqui.</p>
                </div>
            <?php else: ?>
                <div class="rmbz-tpx-card" style="padding:6px 22px; overflow-x:auto;">
                    <table class="rmbz-tpx-table">
                        <thead><tr><th>DATA</th><th>DESCRIÇÃO</th><th>MÉTODO</th><th style="text-align:right;">VALOR</th><th style="text-align:right;">ESTADO</th></tr></thead>
                        <tbody>
                        <?php foreach ( $ledger as $row ):
                            $is_c = $row->type === 'credit';
                            $st = (string) $row->status;
                            $st_fg = $st === 'pendente' ? '#8A6D00' : ( $st === 'rejeitado' ? '#C01818' : '#256C42' ); ?>
                            <tr>
                                <td class="rmbz-tpx-mini"><?php echo esc_html( date_i18n( 'd/m/Y', strtotime( (string) $row->created_at ) ) ); ?></td>
                                <td style="font-weight:600;"><?php echo esc_html( (string) $row->details ); ?><?php if ( ! $is_c && (float) $row->fee > 0 ): ?><br><span class="rmbz-tpx-mini">taxa: <?php echo esc_html( $fmt( $row->fee ) ); ?> MT · recebes <?php echo esc_html( $fmt( (float) $row->amount - (float) $row->fee ) ); ?> MT</span><?php endif; ?></td>
                                <td><?php if ( $is_c ): ?><span class="rmbz-tpx-badge" style="background:#EEE2BC; color:#6B5300;">Crédito</span><?php else: ?><span class="rmbz-tpx-badge" style="background:<?php echo $row->method === 'emola' ? '#FEEBDD' : '#FDE2E2'; ?>; color:<?php echo $row->method === 'emola' ? '#C2410C' : '#C01818'; ?>;"><?php echo esc_html( rmbz_team_wd_method_label( $row->method ) ); ?></span><?php endif; ?></td>
                                <td class="rmbz-tpx-mono" style="text-align:right; font-weight:600; color:<?php echo $is_c ? '#256C42' : '#1E1B13'; ?>;"><?php echo ( $is_c ? '+ ' : '− ' ) . esc_html( $fmt( $row->amount ) ); ?> MT</td>
                                <td style="text-align:right; font-size:12px; font-weight:700; color:<?php echo esc_attr( $st_fg ); ?>;"><?php echo esc_html( ucfirst( $st ) ); ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
            <p class="rmbz-tpx-mini" style="margin-top:14px; text-align:center; opacity:.75;">Os levantamentos são pagos na tua carteira móvel (eMola ou M-Pesa) em até 24 horas úteis, confirmados pela administração da 1MZ Records.</p>
        </section>

        <!-- ══════ PERFIL ══════ -->
        <section data-panel="perfil" data-screen-label="Perfil" hidden>
            <div class="rmbz-tpx-grid2">
                <div class="rmbz-tpx-card">
                    <p style="margin:0 0 14px; font-size:15px; font-weight:750;">Dados de conta</p>
                    <?php
                    $depts = [];
                    foreach ( array_filter( array_map( 'trim', explode( ',', (string) ( $m->departments ?? $m->department ?? '' ) ) ) ) as $dk ) {
                        $dm = function_exists( 'rmbz_team_department_meta' ) ? rmbz_team_department_meta( $dk ) : [ 'label' => $dk, 'icon' => '📌' ];
                        $depts[] = (string) $dm['icon'] . ' ' . (string) $dm['label'];
                    }
                    $campos = [
                        [ 'call', 'Telemóvel', $m->phone ? '+258 ' . $tel9 : '—' ],
                        [ 'badge', 'Departamentos', ! empty( $depts ) ? implode( ' · ', $depts ) : '—' ],
                        [ 'workspace_premium', 'Cargos', ! empty( $roles ) ? implode( ' · ', $roles ) : '—' ],
                        [ 'schedule', 'Membro desde', ! empty( $m->created_at ) ? date_i18n( 'F Y', strtotime( (string) $m->created_at ) ) : '—' ],
                    ];
                    foreach ( $campos as $c ): ?>
                        <div style="display:flex; align-items:center; gap:14px; padding:12px 0; border-bottom:1px solid #F0E8D6;">
                            <span class="ms" style="font-size:20px; color:#755C00;"><?php echo esc_html( $c[0] ); ?></span>
                            <div>
                                <div class="rmbz-tpx-mini" style="font-weight:700; text-transform:uppercase; font-size:11px;"><?php echo esc_html( $c[1] ); ?></div>
                                <div style="font-size:14px; font-weight:600; margin-top:2px;"><?php echo esc_html( $c[2] ); ?></div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                    <a class="rmbz-tpx-pill rmbz-tpx-pill--ghost" href="<?php echo esc_url( $logout_url ); ?>" style="margin-top:16px;"><span class="ms" style="font-size:18px;">logout</span> Terminar sessão</a>
                </div>
                <div class="rmbz-tpx-card">
                    <p style="margin:0 0 4px; font-size:15px; font-weight:750;">🔑 Alterar o meu PIN</p>
                    <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
                        <input type="hidden" name="action" value="rmbz_team_change_pin">
                        <?php wp_nonce_field( 'rmbz_team_change_pin' ); ?>
                        <label class="rmbz-tpx-label">PIN atual</label>
                        <input class="rmbz-tpx-input" type="password" name="pin_atual" inputmode="numeric" maxlength="8" required style="letter-spacing:4px; text-align:center;">
                        <label class="rmbz-tpx-label">PIN novo (4–8 dígitos)</label>
                        <input class="rmbz-tpx-input" type="password" name="pin_novo" inputmode="numeric" pattern="\d{4,8}" maxlength="8" required style="letter-spacing:4px; text-align:center;">
                        <label class="rmbz-tpx-label">Repete o PIN novo</label>
                        <input class="rmbz-tpx-input" type="password" name="pin_novo2" inputmode="numeric" pattern="\d{4,8}" maxlength="8" required style="letter-spacing:4px; text-align:center;">
                        <button type="submit" class="rmbz-tpx-pill rmbz-tpx-pill--primary" style="margin-top:16px;">💾 Guardar PIN novo</button>
                    </form>
                </div>
            </div>
        </section>

        <!-- ══════ DIALOG LEVANTAMENTO (3 passos) ══════ -->
        <div class="rmbz-tpx-scrim" id="rmbz-tpx-scrim" data-screen-label="Levantamento">
            <div class="rmbz-tpx-dialog" role="dialog" aria-modal="true">
                <div class="rmbz-tpx-row" style="margin-bottom:6px;">
                    <div style="font-size:11.5px; font-weight:800; color:#755C00; letter-spacing:.8px;" id="rmbz-tpx-wd-steplabel">PASSO 1 DE 3 — VALOR</div>
                    <button type="button" id="rmbz-tpx-wd-close" style="border:0; background:none; color:#4C4639; cursor:pointer; display:flex;"><span class="ms" style="font-size:22px;">close</span></button>
                </div>

                <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" id="rmbz-tpx-wd-form">
                    <input type="hidden" name="action" value="rmbz_team_wd_request">
                    <?php wp_nonce_field( 'rmbz_team_wd_request' ); ?>
                    <input type="hidden" name="wd_method" id="rmbz-tpx-wd-method" value="mpesa">

                    <!-- PASSO 1: valor -->
                    <div class="rmbz-tpx-step on" data-step="1">
                        <h3 style="margin:0 0 4px; font-size:21px; font-weight:700; color:#1E1B13;">Quanto queres levantar?</h3>
                        <p class="rmbz-tpx-mini" style="margin:0 0 18px;">Saldo disponível: <b><?php echo esc_html( $fmt( $saldo ) ); ?> MT</b> · mínimo <?php echo esc_html( $fmt( $wd_cfg['min'] ) ); ?> MT</p>
                        <div style="display:flex; align-items:baseline; gap:8px; background:#FFFCF5; border:1px solid #D8CCB2; border-radius:18px; padding:14px 18px;">
                            <input name="wd_amount" id="rmbz-tpx-wd-amount" placeholder="0" inputmode="decimal" autocomplete="off"
                                   style="flex:1; border:0; background:none; outline:none; font-family:'Roboto Mono',monospace; font-size:28px; font-weight:600; color:#1E1B13; min-width:0; width:100%;">
                            <span style="font-size:15px; font-weight:750; color:#4C4639;">MT</span>
                        </div>
                        <div style="display:flex; gap:8px; margin-top:12px; flex-wrap:wrap;" id="rmbz-tpx-wd-chips"></div>
                        <div id="rmbz-tpx-wd-erro" style="display:none; margin-top:12px; font-size:12.5px; font-weight:650; color:#C01818;"></div>
                        <button type="button" class="rmbz-tpx-pill rmbz-tpx-pill--primary" data-next="2" style="width:100%; justify-content:center; margin-top:20px; padding:14px;">Continuar</button>
                    </div>

                    <!-- PASSO 2: método + número -->
                    <div class="rmbz-tpx-step" data-step="2">
                        <h3 style="margin:0 0 4px; font-size:21px; font-weight:700; color:#1E1B13;">Para onde enviamos?</h3>
                        <p class="rmbz-tpx-mini" style="margin:0 0 16px;">Escolhe a carteira móvel para receber <b id="rmbz-tpx-wd-amt2">—</b>.</p>
                        <button type="button" class="rmbz-tpx-met on" data-method="mpesa">
                            <span style="width:44px; height:44px; border-radius:12px; background:#E60000; color:#fff; display:flex; align-items:center; justify-content:center; font-weight:800; font-size:12.5px; flex-shrink:0;">M-P</span>
                            <span style="flex:1;"><span style="display:block; font-size:15px; font-weight:750;">M-Pesa</span><span class="rmbz-tpx-mini" style="display:block;">Vodacom · 84 / 85</span></span>
                            <span class="ms met-check" style="font-size:22px; color:#755C00; font-variation-settings:'FILL' 1;">check_circle</span>
                        </button>
                        <button type="button" class="rmbz-tpx-met" data-method="emola">
                            <span style="width:44px; height:44px; border-radius:12px; background:#F26522; color:#fff; display:flex; align-items:center; justify-content:center; font-weight:800; font-size:12.5px; flex-shrink:0;">eM</span>
                            <span style="flex:1;"><span style="display:block; font-size:15px; font-weight:750;">eMola</span><span class="rmbz-tpx-mini" style="display:block;">Movitel · 86 / 87</span></span>
                            <span class="ms met-check" style="font-size:22px; color:#D8CCB2;">radio_button_unchecked</span>
                        </button>
                        <label class="rmbz-tpx-label">Número da carteira</label>
                        <div style="display:flex; align-items:center; gap:10px; background:#FFFCF5; border:1.5px solid #D8CCB2; border-radius:16px; padding:12px 16px;">
                            <span style="font-size:14px; font-weight:700; color:#4C4639;">+258</span>
                            <input name="wd_phone" id="rmbz-tpx-wd-phone" inputmode="numeric" maxlength="9" value="<?php echo esc_attr( $tel9 ); ?>"
                                   style="flex:1; border:0; background:none; outline:none; font-family:'Roboto Mono',monospace; font-size:16px; font-weight:600; min-width:0;">
                        </div>
                        <div style="display:flex; gap:10px; margin-top:20px;">
                            <button type="button" class="rmbz-tpx-pill rmbz-tpx-pill--ghost" data-back="1">Voltar</button>
                            <button type="button" class="rmbz-tpx-pill rmbz-tpx-pill--primary" data-next="3" style="flex:1; justify-content:center;">Rever pedido</button>
                        </div>
                    </div>

                    <!-- PASSO 3: confirmação -->
                    <div class="rmbz-tpx-step" data-step="3">
                        <h3 style="margin:0 0 16px; font-size:21px; font-weight:700; color:#1E1B13;">Confirma o levantamento</h3>
                        <div style="background:#FFFCF5; border:1px solid #E3DAC6; border-radius:18px; padding:6px 18px;">
                            <div class="rmbz-tpx-row" style="padding:12px 0; border-bottom:1px solid #F0E8D6; font-size:13.5px;"><span class="rmbz-tpx-mini">Valor pedido</span><span class="rmbz-tpx-mono" style="font-weight:600;" id="rmbz-tpx-sum-amt">—</span></div>
                            <div class="rmbz-tpx-row" style="padding:12px 0; border-bottom:1px solid #F0E8D6; font-size:13.5px;"><span class="rmbz-tpx-mini">Taxa (<?php echo esc_html( str_replace( '.', ',', (string) $wd_cfg['fee_pct'] ) ); ?>%, mín. <?php echo esc_html( $fmt( $wd_cfg['fee_min'] ) ); ?> MT)</span><span class="rmbz-tpx-mono" style="font-weight:600; color:#C01818;" id="rmbz-tpx-sum-fee">—</span></div>
                            <div class="rmbz-tpx-row" style="padding:12px 0; border-bottom:1px solid #F0E8D6; font-size:13.5px;"><span class="rmbz-tpx-mini">Carteira</span><span style="font-weight:650;" id="rmbz-tpx-sum-met">—</span></div>
                            <div class="rmbz-tpx-row" style="padding:14px 0; font-size:15px;"><span style="font-weight:750;">Vais receber</span><span class="rmbz-tpx-mono" style="font-weight:700; color:#256C42;" id="rmbz-tpx-sum-total">—</span></div>
                        </div>
                        <p class="rmbz-tpx-mini" style="margin:12px 2px 0;">O pedido é processado pela 1MZ Records em até 24 horas úteis. Recebes o aviso quando o valor entrar na carteira.</p>
                        <div style="display:flex; gap:10px; margin-top:18px;">
                            <button type="button" class="rmbz-tpx-pill rmbz-tpx-pill--ghost" data-back="2">Voltar</button>
                            <button type="submit" class="rmbz-tpx-pill rmbz-tpx-pill--primary" style="flex:1; justify-content:center;">Confirmar levantamento</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <?php endif; /* must_change */ ?>
    </div>
    </div><?php /* fecha .rmbz-fullbleed */ ?>

    <script>
    (function () {
        var root = document.getElementById('rmbz-tpx');
        if (!root) return;

        // ── Tabs ──
        var tabs = root.querySelectorAll('.rmbz-tpx-tab');
        var panels = root.querySelectorAll('[data-panel]');
        function goTab(key) {
            tabs.forEach(function (t) { t.classList.toggle('on', t.getAttribute('data-tab') === key); });
            panels.forEach(function (p) { p.hidden = p.getAttribute('data-panel') !== key; });
        }
        tabs.forEach(function (t) { t.addEventListener('click', function () { goTab(t.getAttribute('data-tab')); }); });
        root.querySelectorAll('[data-goto]').forEach(function (b) {
            b.addEventListener('click', function () { goTab(b.getAttribute('data-goto')); });
        });

        // ── Levantamento ──
        var scrim = document.getElementById('rmbz-tpx-scrim');
        if (!scrim) return;
        var saldo  = parseFloat(root.getAttribute('data-saldo')) || 0;
        var wdMin  = parseFloat(root.getAttribute('data-min')) || 100;
        var feePct = parseFloat(root.getAttribute('data-fee-pct')) || 0;
        var feeMin = parseFloat(root.getAttribute('data-fee-min')) || 0;
        var stepLabels = { 1: 'PASSO 1 DE 3 — VALOR', 2: 'PASSO 2 DE 3 — MÉTODO', 3: 'PASSO 3 DE 3 — CONFIRMAÇÃO' };
        var amtInput = document.getElementById('rmbz-tpx-wd-amount');
        var erroEl = document.getElementById('rmbz-tpx-wd-erro');
        var methodInput = document.getElementById('rmbz-tpx-wd-method');
        var phoneInput = document.getElementById('rmbz-tpx-wd-phone');

        function fmt(n) {
            return n.toLocaleString('pt-PT', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).replace(/[\u00A0\u202F]/g, ' ') + ' MT';
        }
        function amount() {
            var raw = String(amtInput.value).replace(/\s/g, '').replace(',', '.');
            var n = parseFloat(raw);
            return isFinite(n) ? n : 0;
        }
        function fee(a) { return a > 0 ? Math.max(feeMin, a * feePct / 100) : 0; }
        function showStep(n) {
            scrim.querySelectorAll('.rmbz-tpx-step').forEach(function (s) {
                s.classList.toggle('on', s.getAttribute('data-step') === String(n));
            });
            document.getElementById('rmbz-tpx-wd-steplabel').textContent = stepLabels[n] || '';
            if (n >= 2) {
                var a = amount(), f = fee(a);
                document.getElementById('rmbz-tpx-wd-amt2').textContent = fmt(a);
                document.getElementById('rmbz-tpx-sum-amt').textContent = fmt(a);
                document.getElementById('rmbz-tpx-sum-fee').textContent = '− ' + fmt(f);
                document.getElementById('rmbz-tpx-sum-total').textContent = fmt(Math.max(0, a - f));
                document.getElementById('rmbz-tpx-sum-met').textContent =
                    (methodInput.value === 'emola' ? 'eMola' : 'M-Pesa') + ' · +258 ' + phoneInput.value;
            }
        }
        document.getElementById('rmbz-tpx-open-wd').addEventListener('click', function () {
            scrim.classList.add('open'); amtInput.value = ''; erroEl.style.display = 'none'; showStep(1);
        });
        document.getElementById('rmbz-tpx-wd-close').addEventListener('click', function () { scrim.classList.remove('open'); });
        scrim.addEventListener('click', function (e) { if (e.target === scrim) scrim.classList.remove('open'); });

        // Chips de valor rápido.
        var chipsWrap = document.getElementById('rmbz-tpx-wd-chips');
        [1000, 2500, 5000].forEach(function (v) { if (v <= saldo) addChip(fmt(v).replace(',00', ''), v); });
        if (saldo >= wdMin) addChip('Tudo (' + fmt(saldo).replace(',00', '') + ')', saldo);
        function addChip(label, v) {
            var b = document.createElement('button');
            b.type = 'button'; b.className = 'rmbz-tpx-amt-chip'; b.textContent = label;
            b.addEventListener('click', function () { amtInput.value = String(v).replace('.', ','); erroEl.style.display = 'none'; });
            chipsWrap.appendChild(b);
        }

        scrim.querySelectorAll('[data-next]').forEach(function (b) {
            b.addEventListener('click', function () {
                var to = parseInt(b.getAttribute('data-next'), 10);
                if (to === 2) {
                    var a = amount();
                    var err = '';
                    if (a < wdMin) err = '⚠️ O valor mínimo de levantamento é ' + fmt(wdMin) + '.';
                    else if (a > saldo) err = '⚠️ O valor excede o teu saldo disponível.';
                    if (err) { erroEl.textContent = err; erroEl.style.display = 'block'; return; }
                    erroEl.style.display = 'none';
                }
                if (to === 3) {
                    var digits = String(phoneInput.value).replace(/\D+/g, '');
                    if (digits.length !== 9) { phoneInput.focus(); phoneInput.style.borderColor = '#C01818'; return; }
                    phoneInput.value = digits;
                }
                showStep(to);
            });
        });
        scrim.querySelectorAll('[data-back]').forEach(function (b) {
            b.addEventListener('click', function () { showStep(parseInt(b.getAttribute('data-back'), 10)); });
        });
        scrim.querySelectorAll('.rmbz-tpx-met').forEach(function (b) {
            b.addEventListener('click', function () {
                scrim.querySelectorAll('.rmbz-tpx-met').forEach(function (o) {
                    var on = o === b;
                    o.classList.toggle('on', on);
                    var chk = o.querySelector('.met-check');
                    chk.textContent = on ? 'check_circle' : 'radio_button_unchecked';
                    chk.style.color = on ? '#755C00' : '#D8CCB2';
                    chk.style.fontVariationSettings = on ? "'FILL' 1" : "'FILL' 0";
                });
                methodInput.value = b.getAttribute('data-method');
            });
        });
    })();
    </script>
    <?php
}
