<?php
/**
 * [1.6.117] PEDIDOS DE REMOÇÃO DE CONTENT ID — REST API (App)
 *
 * Endpoints expostos para a app Android consumir:
 *
 *   POST /1mz/v1/releases/{id}/contentid-requests       — Submeter pedido
 *   GET  /1mz/v1/releases/{id}/contentid-requests       — Listar pedidos anteriores deste release
 *   GET  /1mz/v1/releases/{id}/contentid-requests/check?video_url=…
 *                                                       — Verificar se já há pendente para vídeo
 *
 * Toda a lógica de validação (ownership, LIVE, URL) está nos helpers
 * partilhados — mesmos que o frontend AJAX usa.
 *
 * @package 1MZ_For_Artists
 * @since 1.6.117
 */

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


add_action( 'rest_api_init', 'rmbz_api_register_contentid_routes' );

function rmbz_api_register_contentid_routes() {
    register_rest_route( RMBZ_API_NAMESPACE, '/releases/(?P<id>\d+)/contentid-requests', [
        [
            'methods'             => 'GET',
            'callback'            => 'rmbz_api_handle_list_contentid_requests',
            'permission_callback' => 'rmbz_api_require_auth',
            'args' => [ 'id' => [ 'type' => 'integer', 'required' => true ] ],
        ],
        [
            'methods'             => 'POST',
            'callback'            => 'rmbz_api_handle_create_contentid_request',
            'permission_callback' => 'rmbz_api_require_auth',
            'args' => [ 'id' => [ 'type' => 'integer', 'required' => true ] ],
        ],
    ] );

    register_rest_route( RMBZ_API_NAMESPACE, '/releases/(?P<id>\d+)/contentid-requests/check', [
        'methods'             => 'GET',
        'callback'            => 'rmbz_api_handle_check_contentid_pending',
        'permission_callback' => 'rmbz_api_require_auth',
        'args' => [
            'id'        => [ 'type' => 'integer', 'required' => true ],
            'video_url' => [ 'type' => 'string',  'required' => true ],
        ],
    ] );
}


/**
 * Helper: serializa uma linha da BD para resposta JSON.
 */
function rmbz_api_contentid_serialize( $row ) {
    if ( ! $row ) return null;

    $tracks_decoded = json_decode( $row->tracks_affected ?: '[]', true );
    if ( ! is_array( $tracks_decoded ) ) $tracks_decoded = [];

    return [
        'id'              => (int) $row->id,
        'release_id'      => (int) $row->release_id,
        'video_url'       => (string) $row->video_url,
        'video_id'        => $row->video_id ?: null,
        'tracks_affected' => $tracks_decoded,  // ["all"] ou [id1, id2, ...]
        'reason'          => $row->reason ?: null,
        'status'          => (string) $row->status,             // pendente|aprovado|rejeitado
        'admin_response'  => $row->admin_response ?: null,
        'processed_at'    => $row->processed_at ? mysql_to_rfc3339( $row->processed_at ) : null,
        'created_at'      => mysql_to_rfc3339( $row->created_at ),
    ];
}


/**
 * GET — listar pedidos do release (do artista autenticado).
 */
function rmbz_api_handle_list_contentid_requests( WP_REST_Request $request ) {
    $telemovel  = (string) $request->get_param( 'rmbz_telemovel' );
    $release_id = (int) $request->get_param( 'id' );

    if ( ! rmbz_contentid_release_belongs_to_artist( $release_id, $telemovel ) ) {
        return rmbz_api_error( 'Este release não te pertence.', 403, 'not_owner' );
    }

    global $wpdb;
    $t = $wpdb->prefix . 'rmbz_contentid_requests';
    if ( $wpdb->get_var( "SHOW TABLES LIKE '$t'" ) !== $t ) {
        return rmbz_api_ok( [ 'items' => [] ] );
    }

    $rows = $wpdb->get_results( $wpdb->prepare(
        "SELECT * FROM $t
          WHERE release_id = %d AND artist_telemovel = %s
          ORDER BY id DESC
          LIMIT 20",
        $release_id, $telemovel
    ) );

    $items = array_map( 'rmbz_api_contentid_serialize', $rows ?: [] );
    return rmbz_api_ok( [ 'items' => $items ] );
}


/**
 * POST — criar pedido.
 *
 * Body JSON:
 * {
 *   "video_url": "https://...",
 *   "tracks_affected": ["all"] OU [123, 456],
 *   "reason": "texto opcional"
 * }
 */
function rmbz_api_handle_create_contentid_request( WP_REST_Request $request ) {
    $telemovel  = (string) $request->get_param( 'rmbz_telemovel' );
    $release_id = (int) $request->get_param( 'id' );

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

    $video_url  = esc_url_raw( $body['video_url'] ?? '' );
    $reason     = sanitize_textarea_field( $body['reason'] ?? '' );
    $tracks_raw = $body['tracks_affected'] ?? [];

    // Validar ownership + LIVE
    if ( ! rmbz_contentid_release_belongs_to_artist( $release_id, $telemovel ) ) {
        return rmbz_api_error( 'Este release não te pertence.', 403, 'not_owner' );
    }
    if ( ! rmbz_contentid_release_is_live( $release_id ) ) {
        return rmbz_api_error( 'Só releases LIVE podem ter pedidos de Content ID.', 400, 'not_live' );
    }

    // Validar URL
    $url_check = rmbz_contentid_validate_url( $video_url );
    if ( is_wp_error( $url_check ) ) {
        return rmbz_api_error( $url_check->get_error_message(), 400, $url_check->get_error_code() );
    }

    // Validar tracks
    if ( ! is_array( $tracks_raw ) || empty( $tracks_raw ) ) {
        return rmbz_api_error( 'Selecciona pelo menos uma faixa.', 400, 'no_tracks' );
    }
    if ( in_array( 'all', $tracks_raw, true ) ) {
        $tracks_clean = [ 'all' ];
    } else {
        $tracks_clean = array_values( array_unique( array_map( 'intval', $tracks_raw ) ) );
        $tracks_clean = array_values( array_filter( $tracks_clean, function ( $i ) { return $i > 0; } ) );
        if ( empty( $tracks_clean ) ) {
            return rmbz_api_error( 'Selecciona pelo menos uma faixa válida.', 400, 'no_valid_tracks' );
        }
    }

    // INSERT
    global $wpdb;
    $t = $wpdb->prefix . 'rmbz_contentid_requests';
    $video_id = rmbz_contentid_extract_video_id( $video_url );
    $inserted = $wpdb->insert( $t, [
        'release_id'       => $release_id,
        'artist_telemovel' => $telemovel,
        'video_url'        => $video_url,
        'video_id'         => $video_id,
        'tracks_affected'  => wp_json_encode( $tracks_clean ),
        'reason'           => $reason,
        'status'           => 'pendente',
        'created_at'       => gmdate( 'Y-m-d H:i:s' ),
    ], [ '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s' ] );

    if ( ! $inserted ) {
        return rmbz_api_error( 'Erro técnico ao gravar. Tenta de novo.', 500, 'insert_failed' );
    }

    $request_id = (int) $wpdb->insert_id;
    rmbz_contentid_notify_admin_new( $request_id );

    $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $t WHERE id = %d", $request_id ) );
    return rmbz_api_ok( [
        'request' => rmbz_api_contentid_serialize( $row ),
    ] );
}


/**
 * GET — Verifica se já existe pedido pendente para este vídeo.
 */
function rmbz_api_handle_check_contentid_pending( WP_REST_Request $request ) {
    $telemovel = (string) $request->get_param( 'rmbz_telemovel' );
    $video_url = (string) $request->get_param( 'video_url' );

    $video_id = rmbz_contentid_extract_video_id( $video_url );
    if ( empty( $video_id ) ) {
        return rmbz_api_ok( [ 'has_pending' => false, 'video_id' => null ] );
    }

    $pending_id = rmbz_contentid_get_pending_for_video( $telemovel, $video_id );
    return rmbz_api_ok( [
        'has_pending' => $pending_id !== null,
        'pending_id'  => $pending_id,
        'video_id'    => $video_id,
    ] );
}
