<?php
/**
 * [1.5.396] Push FCM para ADMINISTRADORES (app 1MZ Admin).
 *
 * Os tokens dos dispositivos dos admins são guardados na mesma tabela
 * rmbz_app_push_tokens, sob o telemóvel sintético '__admin__' — assim
 * reutilizamos o envio E a invalidação automática de tokens mortos do
 * rmbz_fcm_send_to_user() sem criar tabela nova.
 *
 * Eventos que notificam os admins:
 *  - Novo pedido de DEPÓSITO   (hook rmbz_deposit_request_created)
 *  - Novo pedido de LEVANTAMENTO (hook rmbz_withdrawal_request_created)
 *  - Nova MENSAGEM de artista no chat de projeto (hook rmbz_pchat_message_inserted)
 */

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

if ( ! defined( 'RMBZ_ADMIN_PUSH_TEL' ) ) {
    define( 'RMBZ_ADMIN_PUSH_TEL', '__admin__' );
}

/* ------------------------------------------------------------------ */
/* Registo do token do dispositivo admin                               */
/* ------------------------------------------------------------------ */

add_action( 'rest_api_init', function () {
    register_rest_route( RMBZ_API_NAMESPACE, '/admin-app/push-token', [
        'methods'             => 'POST',
        'callback'            => 'rmbz_api_admin_app_register_push_token',
        'permission_callback' => 'rmbz_api_require_admin_app_auth',
    ] );
} );

function rmbz_api_admin_app_register_push_token( WP_REST_Request $request ) {
    global $wpdb;
    // get_param aceita JSON e form-encoded (o app envia FormBody).
    $fcm_token = trim( (string) $request->get_param( 'fcm_token' ) );
    $device_id = preg_replace( '/[^a-zA-Z0-9-]/', '', (string) $request->get_param( 'device_id' ) );
    $app_ver   = sanitize_text_field( (string) $request->get_param( 'app_version' ) );

    if ( strlen( $fcm_token ) < 50 ) {
        return new WP_Error( 'invalid_token', 'Token FCM inválido.', [ 'status' => 400 ] );
    }

    $table = $wpdb->prefix . 'rmbz_app_push_tokens';
    if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) !== $table ) {
        return new WP_Error( 'no_table', 'Tabela de tokens indisponível.', [ 'status' => 500 ] );
    }

    // Um token pertence a UM destino: se estava associado a um artista,
    // passa a ser admin (mesma regra de reatribuição do push-controller).
    $existing = $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$table} WHERE fcm_token = %s", $fcm_token ) );
    if ( $existing ) {
        $wpdb->update(
            $table,
            [ 'telemovel' => RMBZ_ADMIN_PUSH_TEL, 'platform' => 'android-admin', 'app_version' => $app_ver, 'is_active' => 1 ],
            [ 'id' => (int) $existing ],
            [ '%s', '%s', '%s', '%d' ],
            [ '%d' ]
        );
        return rmbz_api_ok( [ 'registered' => true, 'updated' => true ] );
    }

    $ok = $wpdb->insert( $table, [
        'telemovel'   => RMBZ_ADMIN_PUSH_TEL,
        'device_id'   => $device_id !== '' ? $device_id : ( 'admin-' . substr( md5( $fcm_token ), 0, 12 ) ),
        'fcm_token'   => $fcm_token,
        'platform'    => 'android-admin',
        'app_version' => $app_ver,
        'is_active'   => 1,
    ], [ '%s', '%s', '%s', '%s', '%s', '%d' ] );

    if ( $ok === false ) {
        return new WP_Error( 'db_error', 'Falha a registar token: ' . $wpdb->last_error, [ 'status' => 500 ] );
    }
    return rmbz_api_ok( [ 'registered' => true, 'updated' => false ] );
}

/* ------------------------------------------------------------------ */
/* Envio                                                                */
/* ------------------------------------------------------------------ */

/**
 * Envia push a TODOS os dispositivos admin registados.
 */
function rmbz_admin_push( $title, $body, $data = [] ) {
    if ( ! function_exists( 'rmbz_fcm_send_to_user' ) ) return;
    $data['for_admin'] = '1';
    rmbz_fcm_send_to_user( RMBZ_ADMIN_PUSH_TEL, $title, $body, $data );
}

/** Nome legível do artista (fallback para o número). */
function rmbz_admin_push_artist_name( $telemovel ) {
    global $wpdb;
    $nome = $wpdb->get_var( $wpdb->prepare(
        "SELECT user_nome FROM {$wpdb->prefix}rmbz_wallets WHERE user_telemovel = %s",
        (string) $telemovel
    ) );
    return $nome ?: (string) $telemovel;
}

/* ------------------------------------------------------------------ */
/* Gatilhos                                                             */
/* ------------------------------------------------------------------ */

// Novo depósito pendente (app e site).
add_action( 'rmbz_deposit_request_created', function ( $id, $telemovel, $amount, $origin = '' ) {
    $nome = rmbz_admin_push_artist_name( $telemovel );
    rmbz_admin_push(
        '💰 Novo depósito pendente',
        sprintf( '%s pediu depósito de %s MT.', $nome, number_format( (float) $amount, 0, ',', ' ' ) ),
        [ 'module' => 'finance', 'item_id' => (string) $id ]
    );
}, 10, 4 );

// Novo levantamento pendente (hook já existente no wallet-controller).
add_action( 'rmbz_withdrawal_request_created', function ( $id, $telemovel, $amount, $origin = '' ) {
    $nome = rmbz_admin_push_artist_name( $telemovel );
    rmbz_admin_push(
        '🏧 Novo levantamento pendente',
        sprintf( '%s pediu levantamento de %s MT.', $nome, number_format( (float) $amount, 0, ',', ' ' ) ),
        [ 'module' => 'finance', 'item_id' => (string) $id ]
    );
}, 10, 4 );

// Nova mensagem de ARTISTA no chat de um projeto.
add_action( 'rmbz_pchat_message_inserted', function ( $project_id, $author_type, $body_text ) {
    if ( $author_type !== 'artist' ) return;
    global $wpdb;
    $proj = $wpdb->get_row( $wpdb->prepare(
        "SELECT project_title, artist_telemovel FROM {$wpdb->prefix}rmbz_artist_projects WHERE id = %d",
        (int) $project_id
    ) );
    $nome    = $proj ? rmbz_admin_push_artist_name( $proj->artist_telemovel ) : 'Artista';
    $preview = trim( (string) $body_text );
    $preview = $preview !== '' ? mb_substr( $preview, 0, 90 ) : '📎 Anexo';
    rmbz_admin_push(
        '💬 ' . $nome . ( $proj && $proj->project_title ? ' · ' . mb_substr( $proj->project_title, 0, 40 ) : '' ),
        $preview,
        [ 'module' => 'projects', 'project_id' => (string) $project_id ]
    );
}, 10, 3 );
