<?php
/**
 * 1MZ For Artists — FCM Tokens Schema (Fase 4b)
 *
 * Cria a tabela rmbz_app_push_tokens para guardar device tokens do FCM
 * (Firebase Cloud Messaging).
 *
 * Cada utilizador pode ter VÁRIOS tokens (um por device onde tem o app
 * instalado). Sempre que o app arranca e faz login, regista o token actual.
 *
 * @package 1MZ_For_Artists
 * @since 1.6.6
 */

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

add_action( 'plugins_loaded', 'rmbz_fcm_maybe_install_tables', 11 );

function rmbz_fcm_maybe_install_tables() {
    $installed = get_option( 'rmbz_fcm_schema_version', '0' );
    if ( $installed === '1.0' ) return;

    global $wpdb;
    $charset = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}rmbz_app_push_tokens (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        telemovel VARCHAR(20) NOT NULL,
        device_id VARCHAR(64) NOT NULL,
        fcm_token TEXT NOT NULL,
        platform VARCHAR(16) NOT NULL DEFAULT 'android',
        app_version VARCHAR(32) NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        last_push_sent_at DATETIME NULL,
        last_push_status VARCHAR(32) NULL,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        PRIMARY KEY (id),
        UNIQUE KEY uniq_telemovel_device (telemovel, device_id),
        KEY idx_telemovel (telemovel),
        KEY idx_active (is_active)
    ) {$charset};";

    require_once ABSPATH . 'wp-admin/includes/upgrade.php';
    dbDelta( $sql );

    update_option( 'rmbz_fcm_schema_version', '1.0' );
}
