<?php
/**
 * 1MZ For Artists — Push Controller (Fase 4b)
 *
 * Endpoints:
 *   POST /push/register-token       Regista/actualiza o token FCM do device
 *   POST /push/unregister-token     Remove o token (logout)
 *   POST /push/test                 Envia push de teste para o próprio utilizador
 *
 * @package 1MZ_For_Artists
 * @since 1.6.6
 */

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

add_action( 'rest_api_init', 'rmbz_api_register_push_routes' );

function rmbz_api_register_push_routes() {

    register_rest_route( RMBZ_API_NAMESPACE, '/push/register-token', [
        'methods'             => 'POST',
        'callback'            => 'rmbz_api_handle_register_push_token',
        'permission_callback' => 'rmbz_api_require_auth',
    ] );

    register_rest_route( RMBZ_API_NAMESPACE, '/push/unregister-token', [
        'methods'             => 'POST',
        'callback'            => 'rmbz_api_handle_unregister_push_token',
        'permission_callback' => 'rmbz_api_require_auth',
    ] );
}

/* ============================================================================
 * POST /push/register-token
 *
 * Body: { "fcm_token": "abc...", "platform": "android", "app_version": "1.0.0" }
 * Headers: X-1MZ-Device-Id (do Guarda-Costas)
 * ============================================================================ */

function rmbz_api_handle_register_push_token( WP_REST_Request $request ) {
    $telemovel = (string) $request->get_param( 'rmbz_telemovel' );

    $body = $request->get_json_params();
    if ( ! is_array( $body ) ) $body = [];

    $fcm_token = isset( $body['fcm_token'] ) ? trim( (string) $body['fcm_token'] ) : '';
    $platform  = isset( $body['platform'] ) ? sanitize_key( (string) $body['platform'] ) : 'android';
    $app_version = isset( $body['app_version'] ) ? sanitize_text_field( (string) $body['app_version'] ) : null;

    if ( empty( $fcm_token ) || strlen( $fcm_token ) < 50 ) {
        return rmbz_api_error( 'Token FCM inválido.', 422, 'invalid_token' );
    }

    // [1.6.118.109] Aceitar 'web' (PWA) além de android/ios
    if ( ! in_array( $platform, [ 'android', 'ios', 'web' ], true ) ) {
        $platform = 'android';
    }

    // Device ID vem do header (Guarda-Costas)
    $device_id = $request->get_header( 'X-1MZ-Device-Id' );
    if ( ! $device_id ) $device_id = $request->get_header( 'x_1mz_device_id' );
    $device_id = preg_replace( '/[^a-zA-Z0-9-]/', '', (string) $device_id );

    if ( empty( $device_id ) ) {
        return rmbz_api_error( 'Device ID em falta no header X-1MZ-Device-Id.', 400, 'no_device_id' );
    }

    global $wpdb;
    $table = $wpdb->prefix . 'rmbz_app_push_tokens';

    // [1.6.346] Este telemóvel só pode pertencer a UMA conta de cada vez. Ao
    // registar, tira este device (e este token) de QUALQUER OUTRA conta — assim,
    // se o utilizador trocou de conta e o logout não chegou a desregistar (app
    // morta/offline/force-stop), a conta ANTIGA deixa de receber push aqui.
    $wpdb->query( $wpdb->prepare(
        "DELETE FROM $table WHERE device_id = %s AND telemovel <> %s",
        $device_id, $telemovel
    ) );
    $wpdb->query( $wpdb->prepare(
        "UPDATE $table SET is_active = 0, last_push_status = 'reassigned' WHERE fcm_token = %s AND telemovel <> %s",
        $fcm_token, $telemovel
    ) );

    // Existe registo (telemovel + device_id)?
    $existing = $wpdb->get_var( $wpdb->prepare(
        "SELECT id FROM $table WHERE telemovel = %s AND device_id = %s",
        $telemovel, $device_id
    ) );

    if ( $existing ) {
        $wpdb->update(
            $table,
            [
                'fcm_token'   => $fcm_token,
                'platform'    => $platform,
                'app_version' => $app_version,
                'is_active'   => 1,
            ],
            [ 'id' => $existing ],
            [ '%s', '%s', '%s', '%d' ],
            [ '%d' ]
        );
        return rmbz_api_ok( [ 'registered' => true, 'updated' => true, 'id' => (int) $existing ] );
    }

    // Inserir novo
    $ok = $wpdb->insert(
        $table,
        [
            'telemovel'   => $telemovel,
            'device_id'   => $device_id,
            'fcm_token'   => $fcm_token,
            'platform'    => $platform,
            'app_version' => $app_version,
            'is_active'   => 1,
        ],
        [ '%s', '%s', '%s', '%s', '%s', '%d' ]
    );

    if ( $ok === false ) {
        return rmbz_api_error( 'Falha a registar token: ' . $wpdb->last_error, 500, 'db_error' );
    }

    return rmbz_api_ok( [ 'registered' => true, 'updated' => false, 'id' => (int) $wpdb->insert_id ] );
}

/* ============================================================================
 * POST /push/unregister-token
 *
 * Apaga o token FCM deste device (chamado no logout).
 * ============================================================================ */

function rmbz_api_handle_unregister_push_token( WP_REST_Request $request ) {
    $telemovel = (string) $request->get_param( 'rmbz_telemovel' );

    $device_id = $request->get_header( 'X-1MZ-Device-Id' );
    if ( ! $device_id ) $device_id = $request->get_header( 'x_1mz_device_id' );
    $device_id = preg_replace( '/[^a-zA-Z0-9-]/', '', (string) $device_id );

    if ( empty( $device_id ) ) {
        return rmbz_api_error( 'Device ID em falta.', 400, 'no_device_id' );
    }

    global $wpdb;
    $deleted = $wpdb->delete(
        $wpdb->prefix . 'rmbz_app_push_tokens',
        [ 'telemovel' => $telemovel, 'device_id' => $device_id ],
        [ '%s', '%s' ]
    );

    return rmbz_api_ok( [ 'unregistered' => true, 'deleted' => (int) $deleted ] );
}

/* [1.5.200] Endpoint /push/test removido — só era usado pelo botão de
 * diagnóstico em DEBUG na app, que foi também removido na versão de
 * produção (1.6.81). Se for preciso reactivar para troubleshooting,
 * recuperar do git histórico.
 */
