<?php
/**
 * 1MZ For Artists — Share Info Endpoint
 *
 * Devolve à app o URL público da release + texto de partilha
 * pré-formatado para a app não ter de construir nada localmente.
 *
 * O URL aponta para a landing page pública (rota /r/{id} do
 * release-landing.php).
 *
 * ENDPOINT:
 *   GET /releases/{id}/share-info
 *
 * @package 1MZ_For_Artists
 * @since 1.6.23
 */

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

if ( ! defined( 'RMBZ_API_SHARE_VERSION' ) ) {
    define( 'RMBZ_API_SHARE_VERSION', '1.6.23.1' );
}

add_action( 'rest_api_init', 'rmbz_api_register_share_routes' );

function rmbz_api_register_share_routes() {
    register_rest_route( RMBZ_API_NAMESPACE, '/releases/(?P<id>\d+)/share-info', [
        'methods'             => 'GET',
        'callback'            => 'rmbz_api_handle_release_share_info',
        'permission_callback' => 'rmbz_api_require_auth',
        'args' => [ 'id' => [ 'type' => 'integer', 'required' => true ] ],
    ] );
}

function rmbz_api_handle_release_share_info( WP_REST_Request $request ) {
    $tel = (string) $request->get_param( 'rmbz_telemovel' );
    $id  = (int) $request->get_param( 'id' );

    global $wpdb;
    $release = $wpdb->get_row( $wpdb->prepare(
        "SELECT *
         FROM {$wpdb->prefix}rmbz_distro_releases
         WHERE id = %d AND artist_telemovel = %s",
        $id, $tel
    ) );

    if ( ! $release ) {
        return rmbz_api_error( 'Release não encontrado.', 404, 'not_found' );
    }

    // Garantir slugs (lazy-fill se release antiga sem slugs)
    if ( function_exists('rmbz_release_landing_ensure_slugs') ) {
        $release = rmbz_release_landing_ensure_slugs( $release );
    }

    $url = function_exists('rmbz_release_landing_build_public_url')
        ? rmbz_release_landing_build_public_url( $release )
        : home_url( '/r/' . (int) $release->id );

    // Determinar modo (pre-save futuro vs ouvir agora)
    $is_future = false;
    if ( ! empty( $release->release_date ) ) {
        $ts = strtotime( $release->release_date );
        $is_future = $ts && $ts > time();
    }
    $is_live = in_array( $release->status, [ 'live', 'distribuido', 'delivered' ], true );

    $mode = match( true ) {
        $is_future          => 'pre_save',
        $is_live            => 'listen_now',
        default             => 'coming_soon',
    };

    // Texto de partilha pré-formatado conforme o modo
    $artist_name = function_exists('rmbz_release_landing_get_artist_name')
        ? rmbz_release_landing_get_artist_name( $release->artist_telemovel )
        : '';
    $artist_label = $artist_name ?: 'Artista 1MZ';

    $share_text = match ( $mode ) {
        'pre_save' => sprintf(
            "🎵 EM BREVE: \"%s\" de %s\n\nMarca a data e partilha!\n%s",
            $release->title, $artist_label, $url
        ),
        'listen_now' => sprintf(
            "🔥 Ouve já \"%s\" de %s em todas as plataformas:\n%s",
            $release->title, $artist_label, $url
        ),
        default => sprintf(
            "%s — %s · 1MZ Records\n%s",
            $release->title, $artist_label, $url
        ),
    };

    // Countdown info se futuro
    $countdown_days = null;
    if ( $is_future ) {
        $countdown_days = (int) ceil(
            ( strtotime( $release->release_date ) - time() ) / 86400
        );
    }

    return rmbz_api_ok( [
        '_api_version'   => RMBZ_API_SHARE_VERSION,
        'release_id'     => (int) $release->id,
        'title'          => (string) $release->title,
        'artist_label'   => $artist_label,
        'public_url'     => $url,
        'mode'           => $mode,
        'release_date'   => $release->release_date ?: null,
        'countdown_days' => $countdown_days,
        'share_text'     => $share_text,
    ] );
}
