<?php
/**
 * 1MZ For Artists — Release Landing Page (pre-save / share)
 *
 * Página pública de partilha de uma release acessível em:
 *
 *   https://1musicmoz.com/r/{artist-slug}/{title-slug}-{token}
 *
 * Exemplos:
 *   https://1musicmoz.com/r/ivan-martos/volta-para-mim-x7B2
 *   https://1musicmoz.com/r/azagaia/babalaze-q4Mn
 *
 * URL "bonito" (artista + título legíveis) com tag aleatório de 4 chars
 * no fim que impede adivinhação por força bruta. Quem partilha vê
 * informação (artista, música), quem só passa pela URL não consegue
 * abrir releases que não foram partilhadas com ele.
 *
 * Schema (colunas adicionadas a rmbz_distro_releases):
 *   - share_artist_slug  varchar(80)  ex: "ivan-martos"
 *   - share_title_slug   varchar(120) ex: "volta-para-mim"
 *   - share_token        varchar(8)   ex: "x7B2" (case-sensitive)
 *
 * URL antigo /r/{id} devolve 404 — não há redirect (decisão produto).
 *
 * @package 1MZ_For_Artists
 * @since 1.6.23
 */

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


/* ============================================================================
 * SCHEMA — adiciona colunas necessárias se ainda não existirem
 * ============================================================================ */

add_action( 'init', 'rmbz_release_landing_maybe_install_schema', 5 );

function rmbz_release_landing_maybe_install_schema() {
    if ( get_option( 'rmbz_release_landing_schema_v', '0' ) === '2' ) return;

    global $wpdb;
    $t = $wpdb->prefix . 'rmbz_distro_releases';
    $cols = $wpdb->get_col( "SHOW COLUMNS FROM $t", 0 );

    if ( ! in_array( 'share_artist_slug', $cols, true ) ) {
        $wpdb->query( "ALTER TABLE $t ADD COLUMN share_artist_slug varchar(80) DEFAULT NULL" );
    }
    if ( ! in_array( 'share_title_slug', $cols, true ) ) {
        $wpdb->query( "ALTER TABLE $t ADD COLUMN share_title_slug varchar(120) DEFAULT NULL" );
    }
    if ( ! in_array( 'share_token', $cols, true ) ) {
        $wpdb->query( "ALTER TABLE $t ADD COLUMN share_token varchar(8) DEFAULT NULL" );
        $wpdb->query( "ALTER TABLE $t ADD INDEX idx_share_token (share_token)" );
    }

    rmbz_release_landing_backfill_slugs();

    update_option( 'rmbz_release_landing_schema_v', '2' );
}

/**
 * Para todas as releases sem share_token, gera slugs e token único.
 */
function rmbz_release_landing_backfill_slugs() {
    global $wpdb;
    $t = $wpdb->prefix . 'rmbz_distro_releases';
    $rows = $wpdb->get_results(
        "SELECT id, title, artist_telemovel
         FROM $t
         WHERE share_token IS NULL OR share_token = ''"
    );
    foreach ( (array) $rows as $r ) {
        rmbz_release_landing_assign_slugs( (int) $r->id, $r->title, $r->artist_telemovel );
    }
}


/* ============================================================================
 * GERAÇÃO DE SLUGS
 * ============================================================================ */

function rmbz_release_landing_assign_slugs( $release_id, $title, $artist_telemovel ) {
    global $wpdb;
    $t = $wpdb->prefix . 'rmbz_distro_releases';

    $artist_name = rmbz_release_landing_get_artist_name( $artist_telemovel );
    $artist_slug = rmbz_release_landing_make_slug( $artist_name ?: 'artista', 80 );
    $title_slug  = rmbz_release_landing_make_slug( $title ?: 'release', 120 );
    $token       = rmbz_release_landing_random_token( 4 );

    $wpdb->update( $t, [
        'share_artist_slug' => $artist_slug,
        'share_title_slug'  => $title_slug,
        'share_token'       => $token,
    ], [ 'id' => (int) $release_id ], [ '%s', '%s', '%s' ], [ '%d' ] );
}

/**
 * Garante que uma release tem slugs — gera lazily se não tiver.
 */
function rmbz_release_landing_ensure_slugs( $release ) {
    if ( ! empty( $release->share_token ) ) return $release;

    rmbz_release_landing_assign_slugs(
        (int) $release->id, $release->title, $release->artist_telemovel
    );

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

function rmbz_release_landing_make_slug( $text, $max_len = 80 ) {
    $slug = sanitize_title( (string) $text );
    if ( mb_strlen( $slug ) > $max_len ) {
        $slug = mb_substr( $slug, 0, $max_len );
    }
    return $slug ?: 'untitled';
}

/**
 * Token aleatório case-sensitive (sem chars confundíveis: 0/O, 1/I/l).
 * 4 chars de [A-HJ-NP-Za-km-z2-9] = ~7M combinações. Suficiente.
 */
function rmbz_release_landing_random_token( $len = 4 ) {
    $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789';
    $max = strlen( $chars ) - 1;
    $out = '';
    for ( $i = 0; $i < $len; $i++ ) {
        $out .= $chars[ random_int( 0, $max ) ];
    }
    return $out;
}

/**
 * Constrói o URL público completo de uma release.
 */
function rmbz_release_landing_build_public_url( $release ) {
    if ( empty( $release->share_token ) ) {
        $release = rmbz_release_landing_ensure_slugs( $release );
    }
    $artist = $release->share_artist_slug ?: 'artista';
    $title  = $release->share_title_slug  ?: 'release';
    $token  = $release->share_token       ?: '0000';
    return home_url( "/r/{$artist}/{$title}-{$token}" );
}


/* ============================================================================
 * REWRITE RULES
 * ============================================================================ */

add_action( 'init', 'rmbz_release_landing_register_rewrite' );

function rmbz_release_landing_register_rewrite() {
    add_rewrite_rule(
        '^r/([^/]+)/([^/]+)/?$',
        'index.php?rmbz_landing_artist=$matches[1]&rmbz_landing_slug=$matches[2]',
        'top'
    );
    add_rewrite_tag( '%rmbz_landing_artist%', '([^&]+)' );
    add_rewrite_tag( '%rmbz_landing_slug%',   '([^&]+)' );

    // Mantém a tag antiga registada para que /r/16 entre no nosso handler
    // (que devolve 404 conforme decidido).
    add_rewrite_tag( '%rmbz_release_landing%', '([0-9]+)' );
}

/**
 * Auto-flush das rewrite rules. Bumpada para v3 para forçar re-flush
 * porque a estrutura de URLs mudou nesta versão.
 */
add_action( 'init', 'rmbz_release_landing_maybe_flush_rewrite', 99 );
function rmbz_release_landing_maybe_flush_rewrite() {
    if ( get_option( 'rmbz_release_landing_rewrite_v', '0' ) !== '3' ) {
        flush_rewrite_rules( false );
        update_option( 'rmbz_release_landing_rewrite_v', '3' );
    }
}


/* ============================================================================
 * HANDLER PRINCIPAL
 * ============================================================================ */

add_action( 'template_redirect', 'rmbz_release_landing_maybe_render' );

function rmbz_release_landing_maybe_render() {
    $artist_slug = (string) get_query_var( 'rmbz_landing_artist' );
    $full_slug   = (string) get_query_var( 'rmbz_landing_slug' );

    // ----- ROTA NOVA: /r/{artist}/{title}-{token} -----
    if ( $artist_slug !== '' && $full_slug !== '' ) {
        rmbz_release_landing_handle_new_route( $artist_slug, $full_slug );
        return;
    }

    // ----- ROTA ANTIGA: /r/{id} → 404 (sem redirect) -----
    $old_id = (int) get_query_var( 'rmbz_release_landing' );
    if ( $old_id > 0 ) {
        status_header( 404 );
        nocache_headers();
        rmbz_release_landing_render_not_found();
        exit;
    }
}

function rmbz_release_landing_handle_new_route( $artist_slug, $full_slug ) {
    $last_dash = strrpos( $full_slug, '-' );
    if ( $last_dash === false ) {
        status_header( 404 );
        nocache_headers();
        rmbz_release_landing_render_not_found();
        exit;
    }

    $title_slug = substr( $full_slug, 0, $last_dash );
    $token      = substr( $full_slug, $last_dash + 1 );

    if ( $title_slug === '' || $token === '' || strlen( $token ) < 3 ) {
        status_header( 404 );
        nocache_headers();
        rmbz_release_landing_render_not_found();
        exit;
    }

    global $wpdb;
    $release = $wpdb->get_row( $wpdb->prepare(
        "SELECT * FROM {$wpdb->prefix}rmbz_distro_releases
         WHERE share_artist_slug = %s
           AND share_title_slug  = %s
           AND BINARY share_token = %s
         LIMIT 1",
        $artist_slug, $title_slug, $token
    ) );

    if ( ! $release ) {
        status_header( 404 );
        nocache_headers();
        rmbz_release_landing_render_not_found();
        exit;
    }

    if ( function_exists('rmbz_origin_track_landing_view') ) {
        rmbz_origin_track_landing_view( (int) $release->id );
    }

    rmbz_release_landing_render( $release );
    exit;
}


/* ============================================================================
 * HELPERS
 * ============================================================================ */

function rmbz_release_landing_get_artist_name( $telemovel ) {
    if ( empty( $telemovel ) ) return '';

    if ( function_exists( 'rmbz_get_artist_nome_by_telemovel' ) ) {
        $name = rmbz_get_artist_nome_by_telemovel( $telemovel );
        if ( ! empty( $name ) ) return $name;
    }

    global $wpdb;
    $wallet_t = $wpdb->prefix . 'rmbz_wallets';
    if ( $wpdb->get_var( "SHOW TABLES LIKE '$wallet_t'" ) === $wallet_t ) {
        $name = $wpdb->get_var( $wpdb->prepare(
            "SELECT user_nome FROM $wallet_t WHERE user_telemovel = %s LIMIT 1",
            $telemovel
        ) );
        if ( ! empty( $name ) ) return $name;
    }

    return '';
}

function rmbz_release_landing_is_future( $release ) {
    if ( empty( $release->release_date ) ) return false;
    $ts = strtotime( $release->release_date );
    return $ts && $ts > time();
}

function rmbz_release_landing_is_live( $release ) {
    return in_array( $release->status, [ 'live', 'distribuido', 'delivered' ], true );
}


/* ============================================================================
 * RENDER PRINCIPAL
 * ============================================================================ */

function rmbz_release_landing_render( $release ) {
    $is_future = rmbz_release_landing_is_future( $release );
    $is_live   = rmbz_release_landing_is_live( $release );
    $artist    = rmbz_release_landing_get_artist_name( $release->artist_telemovel );

    $title  = esc_html( $release->title );
    $artist_safe = esc_html( $artist ?: 'Artista 1MZ' );
    $cover  = $release->cover_image ?: '';
    $cover_url = $cover ? esc_url( $cover ) : '';
    $page_url  = rmbz_release_landing_build_public_url( $release );

    $heading = $is_future
        ? 'EM BREVE'
        : ( $is_live ? 'JÁ DISPONÍVEL' : 'PRÓXIMO LANÇAMENTO' );

    $share_text = sprintf( '%s — %s · 1MZ Records', $title, $artist_safe );

    $dsp_links = [];
    if ( $is_live && function_exists('rmbz_release_get_links_for_tracker') ) {
        $dsp_links = (array) rmbz_release_get_links_for_tracker( $release );
    }

    $gcal_url = null;
    if ( $is_future && ! empty( $release->release_date ) ) {
        $gcal_url = rmbz_release_landing_build_gcal_url(
            $release->title, $artist_safe, $release->release_date, $page_url
        );
    }

    $description = $is_future
        ? sprintf( 'Novo lançamento de %s. Marca a data!', $artist_safe )
        : sprintf( 'Ouve "%s" de %s — disponível em todas as plataformas.', $title, $artist_safe );

    ?><!DOCTYPE html>
<html lang="pt">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $title; ?> — <?php echo $artist_safe; ?> · 1MZ</title>

    <meta property="og:type" content="music.song">
    <meta property="og:title" content="<?php echo $title; ?> — <?php echo $artist_safe; ?>">
    <meta property="og:description" content="<?php echo esc_attr( $description ); ?>">
    <?php if ( $cover_url ): ?>
    <meta property="og:image" content="<?php echo $cover_url; ?>">
    <meta property="og:image:width" content="1400">
    <meta property="og:image:height" content="1400">
    <?php endif; ?>
    <meta property="og:url" content="<?php echo esc_url( $page_url ); ?>">
    <meta property="og:site_name" content="1MZ Records">

    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:title" content="<?php echo $title; ?>">
    <meta name="twitter:description" content="<?php echo esc_attr( $description ); ?>">
    <?php if ( $cover_url ): ?>
    <meta name="twitter:image" content="<?php echo $cover_url; ?>">
    <?php endif; ?>

    <link rel="canonical" href="<?php echo esc_url( $page_url ); ?>">

    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
               background: linear-gradient(135deg, #0a0a0a 0%, #1a0a00 100%);
               color: #fff; min-height: 100vh; padding: 20px;
               display: flex; flex-direction: column; align-items: center; }
        .container { max-width: 480px; width: 100%; margin: 30px auto; text-align: center; }
        .badge { display: inline-block; padding: 6px 14px; background: #ff6b00; color: #fff;
                 font-size: 11px; font-weight: 700; letter-spacing: 1.5px; border-radius: 50px;
                 margin-bottom: 20px; }
        .cover { width: 100%; aspect-ratio: 1; border-radius: 12px; background: #2a2a2a;
                 background-size: cover; background-position: center;
                 box-shadow: 0 20px 60px rgba(255, 107, 0, 0.15); margin-bottom: 24px; }
        h1 { font-size: 28px; font-weight: 800; margin-bottom: 6px; line-height: 1.2; }
        .artist { font-size: 16px; color: #ff9c5b; font-weight: 600; margin-bottom: 8px; }
        .release-date { font-size: 13px; color: #aaa; margin-bottom: 28px; }
        .countdown { font-size: 14px; color: #ff6b00; font-weight: 700; margin-bottom: 28px; }
        .btn { display: flex; align-items: center; justify-content: center; width: 100%;
               padding: 14px 18px; background: #1a1a1a; border: 1px solid #333; border-radius: 10px;
               color: #fff; text-decoration: none; font-size: 14px; font-weight: 600;
               margin-bottom: 10px; transition: all 0.15s; cursor: pointer; }
        .btn:hover { background: #2a2a2a; border-color: #ff6b00; }
        .btn-primary { background: #ff6b00; border-color: #ff6b00; }
        .btn-primary:hover { background: #ff8520; }
        .btn-icon { width: 22px; height: 22px; border-radius: 50%; margin-right: 12px;
                    display: inline-flex; align-items: center; justify-content: center;
                    font-size: 11px; font-weight: 700; color: #fff; flex-shrink: 0; }
        .footer { margin-top: 40px; font-size: 11px; color: #555; text-align: center; }
        .footer a { color: #ff6b00; text-decoration: none; }
        .section-label { font-size: 11px; font-weight: 700; color: #888;
                         letter-spacing: 1.5px; margin: 24px 0 10px; }
    </style>
</head>
<body>
    <div class="container">
        <span class="badge"><?php echo esc_html( $heading ); ?></span>

        <div class="cover" <?php if ( $cover_url ): ?>style="background-image:url('<?php echo $cover_url; ?>')"<?php endif; ?>></div>

        <h1><?php echo $title; ?></h1>
        <p class="artist"><?php echo $artist_safe; ?></p>

        <?php if ( $is_future ): ?>
            <p class="release-date">
                Lançamento:
                <strong><?php echo esc_html( date_i18n( 'j \d\e F \d\e Y', strtotime( $release->release_date ) ) ); ?></strong>
            </p>
            <?php
            $days_left = ceil( ( strtotime( $release->release_date ) - time() ) / 86400 );
            if ( $days_left > 0 ): ?>
                <p class="countdown">
                    <?php echo $days_left === 1 ? 'Falta 1 dia' : 'Faltam ' . $days_left . ' dias'; ?>
                </p>
            <?php endif; ?>

            <?php if ( $gcal_url ): ?>
                <a href="<?php echo esc_url( $gcal_url ); ?>" target="_blank" rel="noopener" class="btn btn-primary">
                    📅 Adicionar ao Google Calendar
                </a>
            <?php endif; ?>

            <button class="btn" onclick="sharePage()">
                🔗 Partilhar com amigos
            </button>

        <?php elseif ( $is_live && ! empty( $dsp_links ) ): ?>

            <div class="section-label">OUVIR AGORA EM</div>

            <?php
            $catalog = function_exists('rmbz_release_links_dsp_catalog')
                ? rmbz_release_links_dsp_catalog()
                : [];
            foreach ( $dsp_links as $slug => $link ):
                if ( ! is_array( $link ) || empty( $link['url'] ) ) continue;
                $cat   = $catalog[ $slug ] ?? [];
                $label = $cat['label']   ?? ucfirst( $slug );
                $initial = $cat['initial'] ?? strtoupper( mb_substr( $label, 0, 1 ) );
                $color = $cat['color']   ?? '#ff6b00';
                $url   = $link['url'];
                $is_exact = ! empty( $link['is_exact'] );
            ?>
                <a href="<?php echo esc_url( $url ); ?>" target="_blank" rel="noopener" class="btn">
                    <span class="btn-icon" style="background:<?php echo esc_attr( $color ); ?>;"><?php echo esc_html( $initial ); ?></span>
                    <span style="flex:1;text-align:left;">
                        <?php echo esc_html( $label ); ?>
                        <?php if ( ! $is_exact ): ?>
                            <span style="font-size:10px;color:#888;font-weight:400;margin-left:6px;">(pesquisar)</span>
                        <?php endif; ?>
                    </span>
                </a>
            <?php endforeach; ?>

            <button class="btn" onclick="sharePage()" style="margin-top:16px;">
                🔗 Partilhar
            </button>

        <?php else: ?>
            <p class="release-date">Disponível em breve.</p>
            <button class="btn btn-primary" onclick="sharePage()">
                🔗 Partilhar
            </button>
        <?php endif; ?>

        <div class="footer">
            Distribuído por <a href="https://1musicmoz.com" target="_blank">1MZ Records</a>
        </div>
    </div>

    <script>
    function sharePage() {
        const data = {
            title: <?php echo wp_json_encode( $title . ' — ' . $artist_safe ); ?>,
            text: <?php echo wp_json_encode( $share_text ); ?>,
            url: <?php echo wp_json_encode( $page_url ); ?>
        };
        if (navigator.share) {
            navigator.share(data).catch(() => {});
        } else {
            navigator.clipboard.writeText(data.url).then(
                () => alert('Link copiado!'),
                () => prompt('Copia o link:', data.url)
            );
        }
    }
    </script>
</body>
</html>
    <?php
}


/* ============================================================================
 * 404
 * ============================================================================ */

function rmbz_release_landing_render_not_found() {
    ?><!DOCTYPE html>
<html lang="pt">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Release não encontrado · 1MZ</title>
    <style>
        body { font-family:-apple-system,sans-serif; background:#0a0a0a; color:#fff;
               min-height:100vh; display:flex; align-items:center; justify-content:center; }
        div { text-align:center; padding:20px; }
        h1 { color:#ff6b00; font-size:48px; margin-bottom:10px; }
        a { color:#ff6b00; text-decoration:none; }
    </style>
</head>
<body>
    <div>
        <h1>404</h1>
        <p>Release não encontrado.</p>
        <p style="margin-top:20px;"><a href="https://1musicmoz.com">Voltar à 1MZ</a></p>
    </div>
</body>
</html>
    <?php
}


/* ============================================================================
 * Helper: Google Calendar URL
 * ============================================================================ */

function rmbz_release_landing_build_gcal_url( $title, $artist, $release_date, $page_url ) {
    $start = gmdate( 'Ymd\THis\Z', strtotime( $release_date . ' 00:00:00 UTC' ) );
    $end   = gmdate( 'Ymd\THis\Z', strtotime( $release_date . ' 01:00:00 UTC' ) );

    $params = http_build_query( [
        'action'   => 'TEMPLATE',
        'text'     => '🎵 ' . $title . ' — ' . $artist,
        'dates'    => $start . '/' . $end,
        'details'  => 'Lançamento de "' . $title . '" por ' . $artist . '. Mais info: ' . $page_url,
        'sf'       => 'true',
        'output'   => 'xml',
    ] );

    return 'https://calendar.google.com/calendar/render?' . $params;
}
