<?php
/**
 * [1.5.413] CARTEIRA & LEVANTAMENTOS DA EQUIPA DE PRODUÇÃO — eMola / M-Pesa.
 *
 * Dá a cada membro da equipa (Equipas & Pessoas) uma carteira própria em
 * Metical, separada da carteira dos artistas:
 *   - A administração CREDITA ganhos (vistorias pagas, subsídios, bónus)
 *     na página admin "Equipa 💼 Carteira".
 *   - O membro pede LEVANTAMENTO no portal (minha-conta) escolhendo
 *     eMola ou M-Pesa + número — fica "pendente" até o admin pagar
 *     na carteira móvel e marcar como concluído.
 *   - Taxa de levantamento configurável (% com mínimo em MT).
 *
 * Tabela: {$prefix}rmbz_team_payouts (ledger: créditos e levantamentos).
 * Portal (frontend): includes/team-portal-page.php usa os helpers daqui.
 *
 * Local: includes/team-portal-withdrawals.php
 */
if ( ! defined( 'ABSPATH' ) ) { exit; }

// =============================================================================
// SCHEMA
// =============================================================================

function rmbz_team_payouts_install_schema() {
    global $wpdb;
    if ( get_option( 'rmbz_team_payouts_schema_version' ) === '1.0' ) return;
    require_once ABSPATH . 'wp-admin/includes/upgrade.php';
    $t = $wpdb->prefix . 'rmbz_team_payouts';
    $charset = $wpdb->get_charset_collate();
    dbDelta( "CREATE TABLE {$t} (
        id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
        member_id BIGINT(20) UNSIGNED NOT NULL,
        type VARCHAR(12) NOT NULL DEFAULT 'credit',
        amount DECIMAL(12,2) NOT NULL DEFAULT 0,
        fee DECIMAL(12,2) NOT NULL DEFAULT 0,
        method VARCHAR(12) DEFAULT NULL,
        phone VARCHAR(20) DEFAULT NULL,
        status VARCHAR(12) NOT NULL DEFAULT 'concluido',
        details VARCHAR(255) DEFAULT NULL,
        created_at DATETIME NOT NULL,
        decided_at DATETIME DEFAULT NULL,
        decided_by VARCHAR(60) DEFAULT NULL,
        PRIMARY KEY (id),
        KEY member_id (member_id),
        KEY status (status)
    ) {$charset};" );
    update_option( 'rmbz_team_payouts_schema_version', '1.0' );
}
add_action( 'admin_init', 'rmbz_team_payouts_install_schema', 5 );
add_action( 'init', 'rmbz_team_payouts_install_schema', 5 );

// =============================================================================
// HELPERS
// =============================================================================

/** Definições do levantamento da equipa (taxa % + mínimos). */
function rmbz_team_wd_settings() {
    $pct = get_option( 'rmbz_team_wd_fee_pct', 2 );
    $min = get_option( 'rmbz_team_wd_min', 100 );
    return [
        'fee_pct' => is_numeric( $pct ) ? max( 0, (float) $pct ) : 2.0,
        'fee_min' => 10.0,
        'min'     => is_numeric( $min ) ? max( 0, (float) $min ) : 100.0,
    ];
}

/** Taxa de UM levantamento (percentagem com mínimo em MT). */
function rmbz_team_wd_fee( $amount ) {
    $s = rmbz_team_wd_settings();
    $amount = (float) $amount;
    if ( $amount <= 0 ) return 0.0;
    return round( max( $s['fee_min'], $amount * $s['fee_pct'] / 100 ), 2 );
}

/**
 * Saldo DISPONÍVEL do membro = créditos concluídos − levantamentos
 * (pendentes contam como já saídos; rejeitados voltam ao saldo).
 */
function rmbz_team_wallet_balance( $member_id ) {
    global $wpdb;
    $t = $wpdb->prefix . 'rmbz_team_payouts';
    $in  = (float) $wpdb->get_var( $wpdb->prepare(
        "SELECT COALESCE(SUM(amount),0) FROM {$t} WHERE member_id = %d AND type = 'credit' AND status = 'concluido'",
        (int) $member_id
    ) );
    $out = (float) $wpdb->get_var( $wpdb->prepare(
        "SELECT COALESCE(SUM(amount),0) FROM {$t} WHERE member_id = %d AND type = 'debit' AND status IN ('pendente','concluido')",
        (int) $member_id
    ) );
    return round( max( 0, $in - $out ), 2 );
}

/** Total ganho (todos os créditos concluídos). */
function rmbz_team_wallet_total_earned( $member_id ) {
    global $wpdb;
    $t = $wpdb->prefix . 'rmbz_team_payouts';
    return (float) $wpdb->get_var( $wpdb->prepare(
        "SELECT COALESCE(SUM(amount),0) FROM {$t} WHERE member_id = %d AND type = 'credit' AND status = 'concluido'",
        (int) $member_id
    ) );
}

/** Total em levantamentos PENDENTES. */
function rmbz_team_wallet_pending_total( $member_id ) {
    global $wpdb;
    $t = $wpdb->prefix . 'rmbz_team_payouts';
    return (float) $wpdb->get_var( $wpdb->prepare(
        "SELECT COALESCE(SUM(amount),0) FROM {$t} WHERE member_id = %d AND type = 'debit' AND status = 'pendente'",
        (int) $member_id
    ) );
}

/** Movimentos do membro, mais recentes primeiro. */
function rmbz_team_wallet_ledger( $member_id, $limit = 60 ) {
    global $wpdb;
    $t = $wpdb->prefix . 'rmbz_team_payouts';
    return $wpdb->get_results( $wpdb->prepare(
        "SELECT * FROM {$t} WHERE member_id = %d ORDER BY id DESC LIMIT %d",
        (int) $member_id, (int) $limit
    ) ) ?: [];
}

/** Nome bonito do método. */
function rmbz_team_wd_method_label( $method ) {
    return $method === 'emola' ? 'eMola' : ( $method === 'mpesa' ? 'M-Pesa' : '—' );
}

// =============================================================================
// FRONT — pedido de levantamento (portal da equipa)
// =============================================================================

function rmbz_team_wd_handle_request() {
    if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( $_POST['_wpnonce'], 'rmbz_team_wd_request' ) ) {
        wp_die( 'Falha de segurança!' );
    }
    if ( session_status() === PHP_SESSION_NONE && ! headers_sent() ) { session_start(); }
    $m = function_exists( 'rmbz_team_portal_current' ) ? rmbz_team_portal_current() : null;
    if ( ! $m ) { rmbz_safe_redirect( home_url( '/minha-conta/' ) ); }

    $s      = rmbz_team_wd_settings();
    $amount = isset( $_POST['wd_amount'] ) ? (float) str_replace( ',', '.', preg_replace( '/[^\d,.]/', '', (string) wp_unslash( $_POST['wd_amount'] ) ) ) : 0;
    $method = isset( $_POST['wd_method'] ) && in_array( $_POST['wd_method'], [ 'mpesa', 'emola' ], true ) ? (string) $_POST['wd_method'] : '';
    $phone  = isset( $_POST['wd_phone'] ) ? preg_replace( '/\D+/', '', (string) wp_unslash( $_POST['wd_phone'] ) ) : '';
    if ( strlen( $phone ) > 9 ) $phone = substr( $phone, -9 );

    $saldo = rmbz_team_wallet_balance( (int) $m->id );
    $err = '';
    if ( $amount < $s['min'] )        $err = 'O valor mínimo de levantamento é ' . number_format( $s['min'], 2, ',', '.' ) . ' MT.';
    elseif ( $amount > $saldo )       $err = 'O valor pedido excede o teu saldo disponível.';
    elseif ( $method === '' )         $err = 'Escolhe a carteira móvel (eMola ou M-Pesa).';
    elseif ( strlen( $phone ) !== 9 ) $err = 'O número da carteira tem de ter 9 dígitos (ex: 846392636).';
    elseif ( rmbz_team_wallet_pending_total( (int) $m->id ) > 0 ) $err = 'Já tens um levantamento pendente — aguarda a confirmação antes de pedir outro.';

    if ( $err !== '' ) {
        $_SESSION['rmbz_team_notice'] = [ 'error', $err ];
        rmbz_safe_redirect( home_url( '/minha-conta/' ) );
    }

    global $wpdb;
    $fee = rmbz_team_wd_fee( $amount );
    $wpdb->insert( $wpdb->prefix . 'rmbz_team_payouts', [
        'member_id'  => (int) $m->id,
        'type'       => 'debit',
        'amount'     => round( $amount, 2 ),
        'fee'        => $fee,
        'method'     => $method,
        'phone'      => $phone,
        'status'     => 'pendente',
        'details'    => 'Levantamento para carteira móvel',
        'created_at' => current_time( 'mysql' ),
    ] );

    $_SESSION['rmbz_team_notice'] = [ 'success',
        '✅ Pedido enviado! Vais receber ' . number_format( $amount - $fee, 2, ',', '.' ) . ' MT na tua carteira '
        . rmbz_team_wd_method_label( $method ) . ' (+258 ' . $phone . ') em até 24 horas úteis.' ];
    rmbz_safe_redirect( home_url( '/minha-conta/' ) );
}
add_action( 'admin_post_rmbz_team_wd_request', 'rmbz_team_wd_handle_request' );
add_action( 'admin_post_nopriv_rmbz_team_wd_request', 'rmbz_team_wd_handle_request' );

// =============================================================================
// ADMIN — creditar, aprovar/rejeitar, definições
// =============================================================================

/** Creditar ganhos a um membro (admin). */
function rmbz_team_wallet_handle_credit() {
    if ( ! current_user_can( 'manage_options' ) ) wp_die( 'Sem permissão.' );
    check_admin_referer( 'rmbz_team_wallet_credit' );
    global $wpdb;
    $member_id = isset( $_POST['member_id'] ) ? (int) $_POST['member_id'] : 0;
    $amount    = isset( $_POST['amount'] ) ? (float) str_replace( ',', '.', (string) $_POST['amount'] ) : 0;
    $details   = isset( $_POST['details'] ) ? sanitize_text_field( (string) wp_unslash( $_POST['details'] ) ) : '';
    if ( $member_id > 0 && $amount > 0 ) {
        $who = wp_get_current_user();
        $wpdb->insert( $wpdb->prefix . 'rmbz_team_payouts', [
            'member_id'  => $member_id,
            'type'       => 'credit',
            'amount'     => round( $amount, 2 ),
            'status'     => 'concluido',
            'details'    => $details !== '' ? $details : 'Crédito de ganhos',
            'created_at' => current_time( 'mysql' ),
            'decided_at' => current_time( 'mysql' ),
            'decided_by' => $who ? (string) $who->user_login : 'admin',
        ] );
    }
    rmbz_safe_redirect( admin_url( 'admin.php?page=rmbz-team-wallet&ok=credit' ) );
}
add_action( 'admin_post_rmbz_team_wallet_credit', 'rmbz_team_wallet_handle_credit' );

/** Aprovar (concluído) ou rejeitar um levantamento pendente. */
function rmbz_team_wd_handle_decide() {
    if ( ! current_user_can( 'manage_options' ) ) wp_die( 'Sem permissão.' );
    check_admin_referer( 'rmbz_team_wd_decide' );
    global $wpdb;
    $id  = isset( $_POST['payout_id'] ) ? (int) $_POST['payout_id'] : 0;
    $dec = isset( $_POST['decision'] ) && $_POST['decision'] === 'aprovar' ? 'concluido' : 'rejeitado';
    if ( $id > 0 ) {
        $who = wp_get_current_user();
        $wpdb->update( $wpdb->prefix . 'rmbz_team_payouts', [
            'status'     => $dec,
            'decided_at' => current_time( 'mysql' ),
            'decided_by' => $who ? (string) $who->user_login : 'admin',
        ], [ 'id' => $id, 'status' => 'pendente' ] );
    }
    rmbz_safe_redirect( admin_url( 'admin.php?page=rmbz-team-wallet&ok=' . $dec ) );
}
add_action( 'admin_post_rmbz_team_wd_decide', 'rmbz_team_wd_handle_decide' );

/** Guardar definições (taxa % + mínimo). */
function rmbz_team_wd_handle_settings() {
    if ( ! current_user_can( 'manage_options' ) ) wp_die( 'Sem permissão.' );
    check_admin_referer( 'rmbz_team_wd_settings' );
    if ( isset( $_POST['fee_pct'] ) && is_numeric( $_POST['fee_pct'] ) ) update_option( 'rmbz_team_wd_fee_pct', max( 0, (float) $_POST['fee_pct'] ) );
    if ( isset( $_POST['wd_min'] ) && is_numeric( $_POST['wd_min'] ) )   update_option( 'rmbz_team_wd_min', max( 0, (float) $_POST['wd_min'] ) );
    rmbz_safe_redirect( admin_url( 'admin.php?page=rmbz-team-wallet&ok=settings' ) );
}
add_action( 'admin_post_rmbz_team_wd_settings', 'rmbz_team_wd_handle_settings' );

/** Menu admin (a seguir aos menus principais do 1MZ Manager). */
add_action( 'admin_menu', function () {
    $pend = 0;
    global $wpdb;
    $t = $wpdb->prefix . 'rmbz_team_payouts';
    if ( $wpdb->get_var( "SHOW TABLES LIKE '{$t}'" ) === $t ) {
        $pend = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$t} WHERE type='debit' AND status='pendente'" );
    }
    $bubble = $pend > 0 ? ' <span class="awaiting-mod">' . $pend . '</span>' : '';
    add_submenu_page( 'rmbz-dashboard', 'Carteira da Equipa', 'Equipa 💼 Carteira' . $bubble, 'manage_options', 'rmbz-team-wallet', 'rmbz_team_wallet_render_admin' );
}, 99 );

function rmbz_team_wallet_render_admin() {
    global $wpdb;
    $t   = $wpdb->prefix . 'rmbz_team_payouts';
    $fmt = fn( $v ) => number_format( (float) $v, 2, ',', '.' );
    $s   = rmbz_team_wd_settings();
    $members = function_exists( 'rmbz_team_get_all' ) ? rmbz_team_get_all( true ) : [];
    $by_id = [];
    foreach ( $members as $mm ) $by_id[ (int) $mm->id ] = $mm;

    $pendentes = $wpdb->get_results( "SELECT * FROM {$t} WHERE type='debit' AND status='pendente' ORDER BY id ASC" ) ?: [];
    $recentes  = $wpdb->get_results( "SELECT * FROM {$t} ORDER BY id DESC LIMIT 40" ) ?: [];
    $ok = isset( $_GET['ok'] ) ? (string) $_GET['ok'] : '';
    ?>
    <div class="wrap">
        <h1>💼 Carteira da Equipa de Produção</h1>
        <?php if ( $ok !== '' ): ?>
            <div class="notice notice-success is-dismissible"><p>
                <?php echo esc_html( [ 'credit' => '✅ Crédito registado.', 'concluido' => '✅ Levantamento marcado como PAGO.', 'rejeitado' => '↩️ Levantamento rejeitado — o valor voltou ao saldo.', 'settings' => '✅ Definições guardadas.' ][ $ok ] ?? 'Feito.' ); ?>
            </p></div>
        <?php endif; ?>

        <h2>⏳ Levantamentos pendentes (<?php echo count( $pendentes ); ?>)</h2>
        <table class="widefat striped" style="max-width:1100px;">
            <thead><tr><th>Pedido</th><th>Membro</th><th>Valor</th><th>Taxa</th><th>A pagar</th><th>Carteira</th><th>Ações</th></tr></thead>
            <tbody>
            <?php if ( empty( $pendentes ) ): ?>
                <tr><td colspan="7">Sem pedidos pendentes. 🎉</td></tr>
            <?php else: foreach ( $pendentes as $row ):
                $mm = $by_id[ (int) $row->member_id ] ?? null; ?>
                <tr>
                    <td>#<?php echo (int) $row->id; ?><br><small><?php echo esc_html( $row->created_at ); ?></small></td>
                    <td><strong><?php echo esc_html( $mm ? $mm->name : ( 'Membro #' . (int) $row->member_id ) ); ?></strong></td>
                    <td><?php echo esc_html( $fmt( $row->amount ) ); ?> MT</td>
                    <td><?php echo esc_html( $fmt( $row->fee ) ); ?> MT</td>
                    <td><strong><?php echo esc_html( $fmt( (float) $row->amount - (float) $row->fee ) ); ?> MT</strong></td>
                    <td><?php echo esc_html( rmbz_team_wd_method_label( $row->method ) ); ?> · +258 <?php echo esc_html( (string) $row->phone ); ?></td>
                    <td>
                        <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="display:inline;">
                            <input type="hidden" name="action" value="rmbz_team_wd_decide">
                            <input type="hidden" name="payout_id" value="<?php echo (int) $row->id; ?>">
                            <input type="hidden" name="decision" value="aprovar">
                            <?php wp_nonce_field( 'rmbz_team_wd_decide' ); ?>
                            <button class="button button-primary" onclick="return confirm('Confirmas que JÁ PAGASTE este valor na carteira móvel do membro?');">✅ Já paguei</button>
                        </form>
                        <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="display:inline;">
                            <input type="hidden" name="action" value="rmbz_team_wd_decide">
                            <input type="hidden" name="payout_id" value="<?php echo (int) $row->id; ?>">
                            <input type="hidden" name="decision" value="rejeitar">
                            <?php wp_nonce_field( 'rmbz_team_wd_decide' ); ?>
                            <button class="button" onclick="return confirm('Rejeitar este levantamento? O valor volta ao saldo do membro.');">✖ Rejeitar</button>
                        </form>
                    </td>
                </tr>
            <?php endforeach; endif; ?>
            </tbody>
        </table>

        <div style="display:flex; gap:40px; flex-wrap:wrap; margin-top:28px; max-width:1100px;">
            <div style="flex:1; min-width:340px;">
                <h2>➕ Creditar ganhos a um membro</h2>
                <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
                    <input type="hidden" name="action" value="rmbz_team_wallet_credit">
                    <?php wp_nonce_field( 'rmbz_team_wallet_credit' ); ?>
                    <table class="form-table">
                        <tr><th>Membro</th><td>
                            <select name="member_id" required style="min-width:260px;">
                                <option value="">— escolher —</option>
                                <?php foreach ( $members as $mm ): ?>
                                    <option value="<?php echo (int) $mm->id; ?>">
                                        <?php echo esc_html( $mm->name . ' (saldo: ' . $fmt( rmbz_team_wallet_balance( (int) $mm->id ) ) . ' MT)' ); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </td></tr>
                        <tr><th>Valor (MT)</th><td><input type="number" step="0.01" min="1" name="amount" required></td></tr>
                        <tr><th>Descrição</th><td><input type="text" name="details" placeholder="Ex: Vistoria — «Nita Wena» (Câmara)" style="min-width:320px;"></td></tr>
                    </table>
                    <p><button class="button button-primary">💾 Creditar</button></p>
                </form>
            </div>
            <div style="flex:1; min-width:300px;">
                <h2>⚙️ Definições do levantamento</h2>
                <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
                    <input type="hidden" name="action" value="rmbz_team_wd_settings">
                    <?php wp_nonce_field( 'rmbz_team_wd_settings' ); ?>
                    <table class="form-table">
                        <tr><th>Taxa (%)</th><td><input type="number" step="0.1" min="0" max="20" name="fee_pct" value="<?php echo esc_attr( $s['fee_pct'] ); ?>"> <small>mínimo de 10 MT por levantamento</small></td></tr>
                        <tr><th>Levantamento mínimo (MT)</th><td><input type="number" step="1" min="0" name="wd_min" value="<?php echo esc_attr( $s['min'] ); ?>"></td></tr>
                    </table>
                    <p><button class="button">💾 Guardar</button></p>
                </form>
            </div>
        </div>

        <h2 style="margin-top:28px;">🧾 Movimentos recentes</h2>
        <table class="widefat striped" style="max-width:1100px;">
            <thead><tr><th>#</th><th>Data</th><th>Membro</th><th>Tipo</th><th>Descrição</th><th>Valor</th><th>Estado</th></tr></thead>
            <tbody>
            <?php if ( empty( $recentes ) ): ?>
                <tr><td colspan="7">Ainda sem movimentos.</td></tr>
            <?php else: foreach ( $recentes as $row ):
                $mm = $by_id[ (int) $row->member_id ] ?? null; ?>
                <tr>
                    <td><?php echo (int) $row->id; ?></td>
                    <td><?php echo esc_html( $row->created_at ); ?></td>
                    <td><?php echo esc_html( $mm ? $mm->name : ( '#' . (int) $row->member_id ) ); ?></td>
                    <td><?php echo $row->type === 'credit' ? '⬇️ Crédito' : ( '⬆️ Levantamento (' . esc_html( rmbz_team_wd_method_label( $row->method ) ) . ')' ); ?></td>
                    <td><?php echo esc_html( (string) $row->details ); ?></td>
                    <td><?php echo ( $row->type === 'credit' ? '+ ' : '− ' ) . esc_html( $fmt( $row->amount ) ); ?> MT</td>
                    <td><?php echo esc_html( ucfirst( (string) $row->status ) ); ?></td>
                </tr>
            <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>
    <?php
}
