<?php
/**
 * Art Tracks nativos da 1MZ.
 * Identidade, catálogo, parceria e auditoria vivem em tabelas próprias.
 * O CPT imz_artista permanece apenas como ponte de migração legada.
 */
if ( ! defined( 'ABSPATH' ) ) exit;
if ( ! defined( 'RMBZ_ART_TRACKS_NATIVE_SCHEMA' ) ) define( 'RMBZ_ART_TRACKS_NATIVE_SCHEMA', '1.0.0' );

function rmbz_art_tracks_native_tables() {
    global $wpdb;
    return [
        'tracks' => $wpdb->prefix . 'rmbz_art_tracks',
        'catalog' => $wpdb->prefix . 'rmbz_art_track_catalog',
        'applications' => $wpdb->prefix . 'rmbz_partnership_applications',
        'audit' => $wpdb->prefix . 'rmbz_partnership_audit',
    ];
}
function rmbz_art_tracks_native_ready() {
    global $wpdb; $t = rmbz_art_tracks_native_tables();
    return $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $t['tracks'] ) ) === $t['tracks'];
}
function rmbz_art_tracks_native_install() {
    global $wpdb;
    if ( ! function_exists( 'dbDelta' ) ) require_once ABSPATH . 'wp-admin/includes/upgrade.php';
    $t = rmbz_art_tracks_native_tables(); $ch = $wpdb->get_charset_collate();
    $tracks_existed = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $t['tracks'] ) ) === $t['tracks'];
    dbDelta( "CREATE TABLE {$t['tracks']} (
        id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
        legacy_post_id bigint(20) unsigned DEFAULT NULL,
        artist_name varchar(191) NOT NULL,
        slug varchar(191) NOT NULL,
        bio longtext NULL,
        genre varchar(120) NOT NULL DEFAULT '',
        country varchar(120) NOT NULL DEFAULT '',
        photo_url varchar(500) NOT NULL DEFAULT '',
        brand_color varchar(16) NOT NULL DEFAULT '#f5b900',
        verified tinyint(1) unsigned NOT NULL DEFAULT 0,
        status varchar(20) NOT NULL DEFAULT 'active',
        linked_user_id bigint(20) unsigned NOT NULL DEFAULT 0,
        linked_wallet_id bigint(20) unsigned NOT NULL DEFAULT 0,
        account_phone varchar(32) NOT NULL DEFAULT '',
        account_email varchar(191) NOT NULL DEFAULT '',
        created_from_submission_id bigint(20) unsigned NOT NULL DEFAULT 0,
        linked_at datetime DEFAULT NULL,
        created_at datetime NOT NULL,
        updated_at datetime NOT NULL,
        PRIMARY KEY  (id),
        UNIQUE KEY legacy_post_id (legacy_post_id),
        KEY account_phone (account_phone),
        KEY account_email (account_email),
        KEY linked_user_id (linked_user_id),
        KEY status (status)
    ) $ch;" );
    dbDelta( "CREATE TABLE {$t['catalog']} (
        id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
        art_track_id bigint(20) unsigned NOT NULL,
        site_post_id bigint(20) unsigned NOT NULL DEFAULT 0,
        submission_id bigint(20) unsigned NOT NULL DEFAULT 0,
        role varchar(20) NOT NULL DEFAULT 'primary',
        title_snapshot varchar(255) NOT NULL DEFAULT '',
        public_url varchar(500) NOT NULL DEFAULT '',
        publication_status varchar(20) NOT NULL DEFAULT 'published',
        verified_at datetime DEFAULT NULL,
        created_at datetime NOT NULL,
        updated_at datetime NOT NULL,
        PRIMARY KEY  (id),
        UNIQUE KEY track_post_role (art_track_id,site_post_id,role),
        KEY art_track_id (art_track_id),
        KEY site_post_id (site_post_id),
        KEY submission_id (submission_id),
        KEY publication_status (publication_status)
    ) $ch;" );
    dbDelta( "CREATE TABLE {$t['applications']} (
        id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
        art_track_id bigint(20) unsigned NOT NULL,
        account_phone varchar(32) NOT NULL DEFAULT '',
        status varchar(20) NOT NULL DEFAULT 'none',
        rights_confirmed tinyint(1) unsigned NOT NULL DEFAULT 0,
        terms_accepted tinyint(1) unsigned NOT NULL DEFAULT 0,
        applied_at datetime DEFAULT NULL,
        reviewed_at datetime DEFAULT NULL,
        reviewed_by bigint(20) unsigned NOT NULL DEFAULT 0,
        decision_reason text NULL,
        internal_note text NULL,
        risk_level varchar(20) NOT NULL DEFAULT 'low',
        security_snapshot longtext NULL,
        created_at datetime NOT NULL,
        updated_at datetime NOT NULL,
        PRIMARY KEY  (id),
        UNIQUE KEY art_track_id (art_track_id),
        KEY status (status),
        KEY account_phone (account_phone),
        KEY reviewed_by (reviewed_by)
    ) $ch;" );
    dbDelta( "CREATE TABLE {$t['audit']} (
        id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
        application_id bigint(20) unsigned NOT NULL DEFAULT 0,
        art_track_id bigint(20) unsigned NOT NULL,
        actor_user_id bigint(20) unsigned NOT NULL DEFAULT 0,
        event_type varchar(60) NOT NULL,
        from_status varchar(20) NOT NULL DEFAULT '',
        to_status varchar(20) NOT NULL DEFAULT '',
        note text NULL,
        context_json longtext NULL,
        ip_hash varchar(64) NOT NULL DEFAULT '',
        created_at datetime NOT NULL,
        PRIMARY KEY  (id),
        KEY application_id (application_id),
        KEY art_track_id (art_track_id),
        KEY event_type (event_type),
        KEY created_at (created_at)
    ) $ch;" );
    $role = get_role( 'administrator' );
    if ( $role ) $role->add_cap( 'rmbz_manage_partnerships' );
    $wpdb->query( "ALTER TABLE {$t['tracks']} AUTO_INCREMENT = 1000000" );
    if ( ! $tracks_existed ) delete_option( 'rmbz_art_tracks_native_migration_complete' );
    update_option( 'rmbz_art_tracks_native_schema', RMBZ_ART_TRACKS_NATIVE_SCHEMA, false );
}
function rmbz_art_tracks_native_maybe_install() {
    if ( get_option( 'rmbz_art_tracks_native_schema' ) !== RMBZ_ART_TRACKS_NATIVE_SCHEMA || ! rmbz_art_tracks_native_ready() ) rmbz_art_tracks_native_install();
    rmbz_art_tracks_native_migrate_legacy();
}
add_action( 'admin_init', 'rmbz_art_tracks_native_maybe_install', 1 );
if ( defined( 'RMBZ_PLUGIN_PATH' ) ) register_activation_hook( RMBZ_PLUGIN_PATH . '1mz-for-artists.php', 'rmbz_art_tracks_native_install' );

function rmbz_art_track_get( $id ) {
    global $wpdb; $id = absint( $id );
    if ( ! $id || ! rmbz_art_tracks_native_ready() ) return null;
    $t = rmbz_art_tracks_native_tables();
    return $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$t['tracks']} WHERE id=%d LIMIT 1", $id ) );
}
function rmbz_art_track_is_valid( $id, $archived = false ) {
    $row = rmbz_art_track_get( $id );
    return (bool) ( $row && ( $archived || $row->status === 'active' ) );
}
function rmbz_art_track_name( $id ) {
    $row = rmbz_art_track_get( $id );
    if ( $row ) return (string) $row->artist_name;
    return get_post_type( $id ) === 'imz_artista' ? (string) get_the_title( $id ) : '';
}
function rmbz_art_track_find_by_user( $user_id ) {
    global $wpdb; $user_id = absint( $user_id );
    if ( ! $user_id || ! rmbz_art_tracks_native_ready() ) return 0;
    $stored = absint( get_user_meta( $user_id, '_imz_art_track_id', true ) );
    if ( $stored && rmbz_art_track_is_valid( $stored, true ) ) return $stored;
    $t = rmbz_art_tracks_native_tables();
    $id = absint( $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$t['tracks']} WHERE linked_user_id=%d AND status='active' ORDER BY id LIMIT 1", $user_id ) ) );
    if ( $id ) update_user_meta( $user_id, '_imz_art_track_id', $id );
    return $id;
}
function rmbz_art_track_find_by_phone( $phone ) {
    global $wpdb;
    if ( ! rmbz_art_tracks_native_ready() ) return 0;
    $phone = function_exists( 'rmbz_artists_normalize_phone' ) ? rmbz_artists_normalize_phone( $phone ) : trim( (string) $phone );
    if ( $phone === '' ) return 0;
    $t = rmbz_art_tracks_native_tables();
    return absint( $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$t['tracks']} WHERE account_phone=%s AND status='active' ORDER BY id LIMIT 1", $phone ) ) );
}
function rmbz_art_track_find_by_email( $email ) {
    global $wpdb; $email = sanitize_email( $email );
    if ( $email === '' || ! rmbz_art_tracks_native_ready() ) return 0;
    $t = rmbz_art_tracks_native_tables();
    return absint( $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$t['tracks']} WHERE LOWER(account_email)=LOWER(%s) AND status='active' ORDER BY id LIMIT 1", $email ) ) );
}
function rmbz_art_track_identity_conflict( $phone='', $email='', $exclude_id=0 ) {
    global $wpdb; if(!rmbz_art_tracks_native_ready())return 0; $t=rmbz_art_tracks_native_tables();$exclude_id=absint($exclude_id);
    $phone=function_exists('rmbz_artists_normalize_phone')?rmbz_artists_normalize_phone($phone):sanitize_text_field($phone);$email=sanitize_email($email);
    if($phone!==''){$id=absint($wpdb->get_var($wpdb->prepare("SELECT id FROM {$t['tracks']} WHERE account_phone=%s AND id<>%d AND status='active' LIMIT 1",$phone,$exclude_id)));if($id)return $id;}
    if($email!=='')return absint($wpdb->get_var($wpdb->prepare("SELECT id FROM {$t['tracks']} WHERE LOWER(account_email)=LOWER(%s) AND id<>%d AND status='active' LIMIT 1",$email,$exclude_id)));
    return 0;
}

function rmbz_art_track_create( array $data ) {
    global $wpdb; if ( ! rmbz_art_tracks_native_ready() ) return 0;
    $name = trim( sanitize_text_field( $data['artist_name'] ?? '' ) ); if ( $name === '' ) return 0;
    $conflict=rmbz_art_track_identity_conflict($data['account_phone']??'',$data['account_email']??'',0);if($conflict)return $conflict;
    $now = current_time( 'mysql' ); $t = rmbz_art_tracks_native_tables();
    $row = [
        'artist_name'=>$name, 'slug'=>sanitize_title($data['slug']??$name).'-'.wp_generate_password(6,false,false),
        'bio'=>sanitize_textarea_field($data['bio']??''), 'genre'=>sanitize_text_field($data['genre']??''),
        'country'=>sanitize_text_field($data['country']??''), 'photo_url'=>esc_url_raw($data['photo_url']??''),
        'brand_color'=>sanitize_hex_color($data['brand_color']??'')?:'#f5b900', 'verified'=>empty($data['verified'])?0:1,
        'status'=>in_array($data['status']??'active',['active','archived'],true)?$data['status']:'active',
        'linked_user_id'=>absint($data['linked_user_id']??0), 'linked_wallet_id'=>absint($data['linked_wallet_id']??0),
        'account_phone'=>function_exists('rmbz_artists_normalize_phone')?rmbz_artists_normalize_phone($data['account_phone']??''):sanitize_text_field($data['account_phone']??''),
        'account_email'=>sanitize_email($data['account_email']??''), 'created_from_submission_id'=>absint($data['created_from_submission_id']??0),
        'linked_at'=>!empty($data['linked_user_id'])?$now:null, 'created_at'=>$now, 'updated_at'=>$now,
    ];
    if ( ! $wpdb->insert( $t['tracks'], $row ) ) return 0;
    $id = absint( $wpdb->insert_id );
    if ( $row['linked_user_id'] ) update_user_meta( $row['linked_user_id'], '_imz_art_track_id', $id );
    rmbz_partnership_audit_log( $id, 'art_track_created', '', 'active', 'Art Track criado na base nativa.', [ 'source'=>'native' ] );
    return $id;
}
function rmbz_art_track_update( $id, array $data ) {
    global $wpdb; $track = rmbz_art_track_get( $id ); if ( ! $track ) return false;
    $identity_phone = array_key_exists( 'account_phone', $data ) ? $data['account_phone'] : $track->account_phone;
    $identity_email = array_key_exists( 'account_email', $data ) ? $data['account_email'] : $track->account_email;
    if ( rmbz_art_track_identity_conflict( $identity_phone, $identity_email, $id ) ) return false;
    $out=[]; $types=['artist_name'=>'text','bio'=>'area','genre'=>'text','country'=>'text','photo_url'=>'url','brand_color'=>'color','account_phone'=>'phone','account_email'=>'email','status'=>'status','verified'=>'bool','linked_user_id'=>'int','linked_wallet_id'=>'int','created_from_submission_id'=>'int'];
    foreach($types as $key=>$type){ if(!array_key_exists($key,$data))continue; $v=$data[$key]; if($type==='text')$v=sanitize_text_field($v); elseif($type==='area')$v=sanitize_textarea_field($v); elseif($type==='url')$v=esc_url_raw($v); elseif($type==='color')$v=sanitize_hex_color($v)?:'#f5b900'; elseif($type==='phone')$v=function_exists('rmbz_artists_normalize_phone')?rmbz_artists_normalize_phone($v):sanitize_text_field($v); elseif($type==='email')$v=sanitize_email($v); elseif($type==='status')$v=in_array($v,['active','archived'],true)?$v:'active'; elseif($type==='bool')$v=empty($v)?0:1; else $v=absint($v); $out[$key]=$v; }
    if(isset($out['artist_name'])&&$out['artist_name']==='')return false; $out['updated_at']=current_time('mysql'); $t=rmbz_art_tracks_native_tables();
    $ok=$wpdb->update($t['tracks'],$out,['id'=>absint($id)]); if(isset($out['linked_user_id'])&&$out['linked_user_id'])update_user_meta($out['linked_user_id'],'_imz_art_track_id',absint($id)); return $ok!==false;
}
function rmbz_art_track_link_account( $id, $wallet, $user_id ) {
    if(!$wallet||!$user_id||!rmbz_art_track_is_valid($id,true))return false; $email=sanitize_email((string)$wallet->user_email); if(substr(strtolower($email),-10)==='@1mz.local')$email='';
    $ok=rmbz_art_track_update($id,['linked_user_id'=>$user_id,'linked_wallet_id'=>$wallet->id,'account_phone'=>$wallet->user_telemovel,'account_email'=>$email,'status'=>'active']);
    if($ok){global $wpdb;$t=rmbz_art_tracks_native_tables();$wpdb->update($t['tracks'],['linked_at'=>current_time('mysql')],['id'=>absint($id)]);} return $ok;
}
function rmbz_art_track_sync_music( $track_id, $post_id, $role='primary', $submission_id=0 ) {
    global $wpdb; $track_id=absint($track_id); $post_id=absint($post_id); $post=get_post($post_id);
    if(!rmbz_art_track_is_valid($track_id,true)||!$post||$post->post_type!=='post')return false; $role=$role==='featured'?'featured':'primary'; $t=rmbz_art_tracks_native_tables();
    $existing=absint($wpdb->get_var($wpdb->prepare("SELECT id FROM {$t['catalog']} WHERE art_track_id=%d AND site_post_id=%d AND role=%s LIMIT 1",$track_id,$post_id,$role)));
    $row=['art_track_id'=>$track_id,'site_post_id'=>$post_id,'submission_id'=>absint($submission_id),'role'=>$role,'title_snapshot'=>sanitize_text_field($post->post_title),'public_url'=>esc_url_raw(get_permalink($post_id)),'publication_status'=>$post->post_status==='publish'?'published':'hidden','verified_at'=>$post->post_status==='publish'?current_time('mysql'):null,'updated_at'=>current_time('mysql')];
    if($existing)return $wpdb->update($t['catalog'],$row,['id'=>$existing])!==false; $row['created_at']=current_time('mysql'); return (bool)$wpdb->insert($t['catalog'],$row);
}
function rmbz_art_track_music_ids( $track_id, $role='' ) {
    global $wpdb; if(!rmbz_art_tracks_native_ready())return []; $t=rmbz_art_tracks_native_tables(); $sql=$wpdb->prepare("SELECT site_post_id FROM {$t['catalog']} WHERE art_track_id=%d AND publication_status='published'",absint($track_id)); if(in_array($role,['primary','featured'],true))$sql.=$wpdb->prepare(' AND role=%s',$role); return array_values(array_unique(array_map('absint',$wpdb->get_col($sql))));
}
function rmbz_art_track_music_role( $track_id, $post_id ) {
    global $wpdb; if(!rmbz_art_tracks_native_ready())return ''; $t=rmbz_art_tracks_native_tables(); return (string)$wpdb->get_var($wpdb->prepare("SELECT role FROM {$t['catalog']} WHERE art_track_id=%d AND site_post_id=%d AND publication_status='published' ORDER BY role LIMIT 1",absint($track_id),absint($post_id)));
}
function rmbz_art_track_published_count( $track_id ) {
    global $wpdb; if(!rmbz_art_tracks_native_ready())return 0; $t=rmbz_art_tracks_native_tables(); return (int)$wpdb->get_var($wpdb->prepare("SELECT COUNT(DISTINCT site_post_id) FROM {$t['catalog']} WHERE art_track_id=%d AND role='primary' AND publication_status='published'",absint($track_id)));
}
function rmbz_art_track_artist_data( $id ) {
    $r=rmbz_art_track_get($id); if(!$r)return null; return ['id'=>(int)$r->id,'nome'=>(string)$r->artist_name,'bio'=>(string)$r->bio,'genero'=>(string)$r->genre,'pais'=>(string)$r->country,'photo'=>(string)$r->photo_url,'color'=>(string)$r->brand_color,'verified'=>(bool)$r->verified];
}
function rmbz_partnership_application_get( $track_id ) {
    global $wpdb; if(!rmbz_art_tracks_native_ready())return null; $t=rmbz_art_tracks_native_tables(); return $wpdb->get_row($wpdb->prepare("SELECT * FROM {$t['applications']} WHERE art_track_id=%d LIMIT 1",absint($track_id)));
}
function rmbz_partnership_application_save( $track_id, array $data ) {
    global $wpdb; $track_id=absint($track_id); if(!rmbz_art_track_is_valid($track_id,true))return false; $t=rmbz_art_tracks_native_tables(); $current=rmbz_partnership_application_get($track_id); $out=[];
    foreach(['account_phone','status','rights_confirmed','terms_accepted','applied_at','reviewed_at','reviewed_by','decision_reason','internal_note','risk_level','security_snapshot'] as $f)if(array_key_exists($f,$data))$out[$f]=$data[$f];
    if(isset($out['account_phone']))$out['account_phone']=sanitize_text_field($out['account_phone']); if(isset($out['status'])&&!in_array($out['status'],['none','pending','approved','rejected','suspended'],true))$out['status']='none'; foreach(['rights_confirmed','terms_accepted'] as $f)if(isset($out[$f]))$out[$f]=empty($out[$f])?0:1; if(isset($out['reviewed_by']))$out['reviewed_by']=absint($out['reviewed_by']); foreach(['decision_reason','internal_note'] as $f)if(isset($out[$f]))$out[$f]=sanitize_textarea_field($out[$f]); if(isset($out['risk_level'])&&!in_array($out['risk_level'],['low','medium','high'],true))$out['risk_level']='low'; if(isset($out['security_snapshot'])&&is_array($out['security_snapshot']))$out['security_snapshot']=wp_json_encode($out['security_snapshot'],JSON_UNESCAPED_UNICODE); $out['updated_at']=current_time('mysql');
    if($current)return $wpdb->update($t['applications'],$out,['art_track_id'=>$track_id])!==false; $out['art_track_id']=$track_id; $out['created_at']=current_time('mysql'); if(!isset($out['status']))$out['status']='none'; return (bool)$wpdb->insert($t['applications'],$out);
}
function rmbz_partnership_audit_log( $track_id, $event, $from='', $to='', $note='', array $context=[] ) {
    global $wpdb; if(!rmbz_art_tracks_native_ready())return false; $t=rmbz_art_tracks_native_tables(); $app=rmbz_partnership_application_get($track_id); $ip=sanitize_text_field($_SERVER['REMOTE_ADDR']??''); $hash=$ip!==''?hash_hmac('sha256',$ip,wp_salt('auth')):'';
    return (bool)$wpdb->insert($t['audit'],['application_id'=>$app?(int)$app->id:0,'art_track_id'=>absint($track_id),'actor_user_id'=>get_current_user_id(),'event_type'=>sanitize_key($event),'from_status'=>sanitize_key($from),'to_status'=>sanitize_key($to),'note'=>sanitize_textarea_field($note),'context_json'=>wp_json_encode($context,JSON_UNESCAPED_UNICODE),'ip_hash'=>$hash,'created_at'=>current_time('mysql')]);
}
function rmbz_partnership_audit_for_track( $track_id, $limit=20 ) {
    global $wpdb; if(!rmbz_art_tracks_native_ready())return []; $t=rmbz_art_tracks_native_tables(); return $wpdb->get_results($wpdb->prepare("SELECT * FROM {$t['audit']} WHERE art_track_id=%d ORDER BY id DESC LIMIT %d",absint($track_id),max(1,min(100,absint($limit)))));
}

function rmbz_art_tracks_native_migrate_legacy() {
    global $wpdb; if(!rmbz_art_tracks_native_ready()||!post_type_exists('imz_artista')||get_option('rmbz_art_tracks_native_migration_complete')||get_transient('rmbz_native_tracks_migrating'))return; set_transient('rmbz_native_tracks_migrating',1,5*MINUTE_IN_SECONDS); $t=rmbz_art_tracks_native_tables();
    $posts=get_posts(['post_type'=>'imz_artista','post_status'=>['publish','draft','pending','private','future'],'posts_per_page'=>-1,'orderby'=>'ID','order'=>'ASC','no_found_rows'=>true]);
    foreach($posts as $post){
        $existing=$wpdb->get_row($wpdb->prepare("SELECT * FROM {$t['tracks']} WHERE legacy_post_id=%d LIMIT 1",$post->ID)); $photo=(string)get_post_meta($post->ID,'_imz_artista_photo_url',true); if($photo==='')$photo=(string)get_the_post_thumbnail_url($post->ID,'medium');
        $data=['legacy_post_id'=>(int)$post->ID,'artist_name'=>sanitize_text_field($post->post_title?:'Art Track #'.$post->ID),'slug'=>sanitize_title($post->post_name?:$post->post_title).'-'.$post->ID,'bio'=>(string)get_post_meta($post->ID,'_imz_artista_bio',true),'genre'=>(string)get_post_meta($post->ID,'_imz_artista_genero',true),'country'=>(string)get_post_meta($post->ID,'_imz_artista_pais',true),'photo_url'=>esc_url_raw($photo),'brand_color'=>sanitize_hex_color(get_post_meta($post->ID,'_imz_artista_color',true))?:'#f5b900','verified'=>get_post_meta($post->ID,'_imz_artista_verified',true)==='1'?1:0,'status'=>'active','linked_user_id'=>absint(get_post_meta($post->ID,'_imz_artista_linked_user_id',true)),'linked_wallet_id'=>absint(get_post_meta($post->ID,'_imz_artista_linked_wallet_id',true)),'account_phone'=>function_exists('rmbz_artists_normalize_phone')?rmbz_artists_normalize_phone(get_post_meta($post->ID,'_imz_artista_account_phone',true)):(string)get_post_meta($post->ID,'_imz_artista_account_phone',true),'account_email'=>sanitize_email(get_post_meta($post->ID,'_imz_artista_account_email',true)),'created_from_submission_id'=>absint(get_post_meta($post->ID,'_imz_artista_created_from_submission',true)),'linked_at'=>get_post_meta($post->ID,'_imz_artista_linked_at',true)?:null,'updated_at'=>current_time('mysql')];
        if($existing){$wpdb->update($t['tracks'],$data,['id'=>(int)$existing->id]);$track_id=(int)$existing->id;}else{$data['id']=(int)$post->ID;$data['created_at']=$post->post_date?:current_time('mysql');if(!$wpdb->insert($t['tracks'],$data)){unset($data['id']);$wpdb->insert($t['tracks'],$data);}$track_id=absint($wpdb->insert_id?:$post->ID);} update_post_meta($post->ID,'_rmbz_native_art_track_id',$track_id); if($data['linked_user_id'])update_user_meta($data['linked_user_id'],'_imz_art_track_id',$track_id);
        $music_ids=function_exists('imz_get_ids_musicas_do_artista')?imz_get_ids_musicas_do_artista($post->ID):get_posts(['post_type'=>'post','post_status'=>'publish','posts_per_page'=>-1,'fields'=>'ids','meta_key'=>'_imz_artista_id','meta_value'=>$post->ID,'no_found_rows'=>true]); foreach(array_map('absint',(array)$music_ids) as $mid){$role=(int)get_post_meta($mid,'_imz_artista_id',true)===(int)$post->ID?'primary':'featured';rmbz_art_track_sync_music($track_id,$mid,$role,absint(get_post_meta($mid,'_rmbz_site_submission_id',true)));}
        $status=sanitize_key((string)get_post_meta($post->ID,'_imz_partnership_status',true));$rights=(bool)get_post_meta($post->ID,'_imz_partnership_rights_confirmed',true);$terms=(bool)get_post_meta($post->ID,'_imz_partnership_terms_accepted',true);if($status!==''||$rights||$terms)rmbz_partnership_application_save($track_id,['account_phone'=>$data['account_phone'],'status'=>$status?:'none','rights_confirmed'=>$rights,'terms_accepted'=>$terms,'applied_at'=>get_post_meta($post->ID,'_imz_partnership_applied_at',true)?:null,'reviewed_at'=>get_post_meta($post->ID,'_imz_partnership_reviewed_at',true)?:null,'reviewed_by'=>absint(get_post_meta($post->ID,'_imz_partnership_reviewed_by',true)),'decision_reason'=>(string)get_post_meta($post->ID,'_imz_partnership_rejection_reason',true)]);
    }
    update_option('rmbz_art_tracks_native_migrated_at',current_time('mysql'),false);update_option('rmbz_art_tracks_native_migration_complete',1,false);delete_transient('rmbz_native_tracks_migrating');
}
function rmbz_art_tracks_native_admin_menu() {
    $parent=function_exists('imz_admin_parent_slug')?imz_admin_parent_slug():'edit.php?post_type=impulsionamento';
    add_submenu_page($parent,'Art Tracks','Art Tracks','manage_options','imz-native-art-tracks','rmbz_art_tracks_native_admin_page');
}
add_action('admin_menu','rmbz_art_tracks_native_admin_menu',34);
function rmbz_art_tracks_native_admin_save() {
    if(!current_user_can('manage_options'))wp_die('Sem permissão.');check_admin_referer('rmbz_native_art_track_save');$id=absint($_POST['track_id']??0);
    $data=['artist_name'=>wp_unslash($_POST['artist_name']??''),'bio'=>wp_unslash($_POST['bio']??''),'genre'=>wp_unslash($_POST['genre']??''),'country'=>wp_unslash($_POST['country']??''),'photo_url'=>wp_unslash($_POST['photo_url']??''),'brand_color'=>wp_unslash($_POST['brand_color']??''),'account_phone'=>wp_unslash($_POST['account_phone']??''),'account_email'=>wp_unslash($_POST['account_email']??''),'verified'=>empty($_POST['verified'])?0:1,'status'=>sanitize_key(wp_unslash($_POST['status']??'active'))];
    $conflict = rmbz_art_track_identity_conflict( $data['account_phone'], $data['account_email'], $id );
    if ( $conflict ) {
        wp_safe_redirect( add_query_arg( [ 'post_type'=>'impulsionamento', 'page'=>'imz-native-art-tracks', 'track_id'=>$id, 'native_notice'=>'identity', 'conflict_id'=>$conflict ], admin_url( 'edit.php' ) ) );
        exit;
    }
    $ok=$id?rmbz_art_track_update($id,$data):($id=rmbz_art_track_create($data));if($ok&&$id)rmbz_partnership_audit_log($id,'art_track_updated','','','Dados do Art Track atualizados.',['fields'=>array_keys($data)]);
    wp_safe_redirect(add_query_arg(['post_type'=>'impulsionamento','page'=>'imz-native-art-tracks','track_id'=>$id,'native_notice'=>$ok?'saved':'error'],admin_url('edit.php')));exit;
}
add_action('admin_post_rmbz_native_art_track_save','rmbz_art_tracks_native_admin_save');
function rmbz_art_tracks_native_admin_page() {
    if(!current_user_can('manage_options'))wp_die('Sem permissão.');global $wpdb;$t=rmbz_art_tracks_native_tables();$search=sanitize_text_field(wp_unslash($_GET['s']??''));$status=sanitize_key(wp_unslash($_GET['track_status']??'active'));if(!in_array($status,['all','active','archived'],true))$status='active';$where='1=1';$params=[];
    if($status!=='all'){$where.=' AND t.status=%s';$params[]=$status;}if($search!==''){$like='%'.$wpdb->esc_like($search).'%';$where.=' AND (t.artist_name LIKE %s OR t.account_phone LIKE %s OR t.account_email LIKE %s)';array_push($params,$like,$like,$like);}
    $sql="SELECT t.*,COUNT(DISTINCT c.site_post_id) catalog_count FROM {$t['tracks']} t LEFT JOIN {$t['catalog']} c ON c.art_track_id=t.id AND c.publication_status='published' WHERE $where GROUP BY t.id ORDER BY t.updated_at DESC LIMIT 200";$tracks=$params?$wpdb->get_results($wpdb->prepare($sql,$params)):$wpdb->get_results($sql);$selected_id=absint($_GET['track_id']??0);$selected=$selected_id?rmbz_art_track_get($selected_id):null;$edit=$selected?:(object)['id'=>0,'artist_name'=>'','bio'=>'','genre'=>'','country'=>'','photo_url'=>'','brand_color'=>'#f5b900','account_phone'=>'','account_email'=>'','verified'=>0,'status'=>'active','linked_user_id'=>0,'linked_wallet_id'=>0,'legacy_post_id'=>0];$catalog=$selected?rmbz_art_track_music_ids($selected->id):[];$total=(int)$wpdb->get_var("SELECT COUNT(*) FROM {$t['tracks']}");$linked=(int)$wpdb->get_var("SELECT COUNT(*) FROM {$t['tracks']} WHERE linked_user_id>0");$verified=(int)$wpdb->get_var("SELECT COUNT(*) FROM {$t['tracks']} WHERE verified=1");
    ?>
    <div class="wrap rmbz-native-tracks"><style>
    .rmbz-native-tracks{--ink:#171a18;--muted:#68706b;--line:#dfe4e0;--soft:#f4f7f5;--green:#123f31;--gold:#f5b900;max-width:none;margin:0 20px 0 2px;padding:26px 24px 60px;color:var(--ink)}.rmbz-nt-head{display:flex;align-items:flex-start;justify-content:space-between;gap:20px}.rmbz-nt-head h1{margin:0;font-size:30px}.rmbz-nt-head p{margin:6px 0 0;color:var(--muted)}.rmbz-nt-new{display:inline-flex;align-items:center;gap:8px;padding:11px 16px;border-radius:999px;background:var(--gold);color:#17130a;text-decoration:none;font-weight:800}.rmbz-nt-metrics{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px;margin:22px 0}.rmbz-nt-metric{padding:17px;border:1px solid var(--line);border-radius:18px;background:#fff}.rmbz-nt-metric small{display:block;color:var(--muted);font-weight:700}.rmbz-nt-metric strong{display:block;margin-top:7px;font-size:25px}.rmbz-nt-layout{display:grid;grid-template-columns:minmax(0,1.35fr) minmax(360px,.65fr);gap:18px}.rmbz-nt-panel{padding:18px;border:1px solid var(--line);border-radius:22px;background:#fff}.rmbz-nt-tools{display:flex;gap:10px;margin-bottom:15px}.rmbz-nt-tools input,.rmbz-nt-tools select,.rmbz-nt-form input,.rmbz-nt-form textarea,.rmbz-nt-form select{min-height:43px;border:1px solid var(--line);border-radius:12px;background:var(--soft);box-shadow:none}.rmbz-nt-tools input{flex:1}.rmbz-nt-list{display:grid;gap:9px}.rmbz-nt-row{display:grid;grid-template-columns:44px minmax(0,1fr) auto auto;gap:12px;align-items:center;padding:12px;border:1px solid var(--line);border-radius:15px;color:inherit;text-decoration:none}.rmbz-nt-row:hover{border-color:#8aa69a;background:#f8fbf9}.rmbz-nt-avatar{width:44px;height:44px;display:grid;place-items:center;overflow:hidden;border-radius:14px;background:#f7e8ad;font-weight:850}.rmbz-nt-avatar img{width:100%;height:100%;object-fit:cover}.rmbz-nt-copy strong,.rmbz-nt-copy small{display:block}.rmbz-nt-copy small{margin-top:3px;color:var(--muted)}.rmbz-nt-chip{padding:6px 9px;border-radius:999px;background:#e5f4ed;color:#087451;font-size:11px;font-weight:750}.rmbz-nt-count{font:700 12px monospace;color:var(--muted)}.rmbz-nt-form{display:grid;gap:12px}.rmbz-nt-form h2{margin:0}.rmbz-nt-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px}.rmbz-nt-field{display:grid;gap:5px}.rmbz-nt-field.full{grid-column:1/-1}.rmbz-nt-field label{font-size:11px;font-weight:750;color:var(--muted)}.rmbz-nt-form textarea{min-height:90px}.rmbz-nt-switch{display:flex;align-items:center;gap:8px;padding:11px;border-radius:12px;background:var(--soft)}.rmbz-nt-save{min-height:46px;border:0;border-radius:999px;background:var(--green);color:#fff;font-weight:800;cursor:pointer}.rmbz-nt-native{padding:10px 12px;border-radius:12px;background:#e7f5ee;color:#087451;font-size:11px}.rmbz-nt-catalog{margin-top:14px;padding-top:14px;border-top:1px solid var(--line)}.rmbz-nt-empty{padding:25px;text-align:center;color:var(--muted)}@media(max-width:1100px){.rmbz-nt-layout{grid-template-columns:1fr}.rmbz-nt-metrics{grid-template-columns:1fr 1fr}}@media(max-width:650px){.rmbz-native-tracks{padding:18px 10px}.rmbz-nt-head,.rmbz-nt-tools{display:grid}.rmbz-nt-metrics,.rmbz-nt-grid{grid-template-columns:1fr}.rmbz-nt-row{grid-template-columns:44px 1fr}.rmbz-nt-chip,.rmbz-nt-count{grid-column:2}}
    </style>
    <header class="rmbz-nt-head"><div><h1>Art Tracks</h1><p>Identidades e catálogos guardados na infraestrutura própria da 1MZ.</p></div><a class="rmbz-nt-new" href="<?php echo esc_url(add_query_arg(['post_type'=>'impulsionamento','page'=>'imz-native-art-tracks'],admin_url('edit.php')));?>"><span class="dashicons dashicons-plus-alt2"></span>Novo Art Track</a></header>
    <?php $native_notice=sanitize_key(wp_unslash($_GET['native_notice']??''));if($native_notice==='saved'):?><div class="notice notice-success is-dismissible"><p>Art Track guardado com segurança.</p></div><?php elseif($native_notice==='identity'):$conflict_id=absint($_GET['conflict_id']??0);?><div class="notice notice-error is-dismissible"><p>Este telefone ou email já pertence ao Art Track nativo #<?php echo $conflict_id;?>. Abre esse registo para evitar identidades duplicadas.</p></div><?php elseif($native_notice==='error'):?><div class="notice notice-error is-dismissible"><p>Não foi possível guardar o Art Track. Confirma os dados e tenta novamente.</p></div><?php endif;?>
    <section class="rmbz-nt-metrics"><article class="rmbz-nt-metric"><small>TOTAL</small><strong><?php echo $total;?></strong></article><article class="rmbz-nt-metric"><small>CONTAS LIGADAS</small><strong><?php echo $linked;?></strong></article><article class="rmbz-nt-metric"><small>VERIFICADOS</small><strong><?php echo $verified;?></strong></article><article class="rmbz-nt-metric"><small>ARQUITETURA</small><strong>Nativa</strong></article></section>
    <div class="rmbz-nt-layout"><section class="rmbz-nt-panel"><form class="rmbz-nt-tools" method="get"><input type="hidden" name="post_type" value="impulsionamento"><input type="hidden" name="page" value="imz-native-art-tracks"><input type="search" name="s" value="<?php echo esc_attr($search);?>" placeholder="Pesquisar nome, telefone ou email"><select name="track_status"><option value="active" <?php selected($status,'active');?>>Ativos</option><option value="archived" <?php selected($status,'archived');?>>Arquivados</option><option value="all" <?php selected($status,'all');?>>Todos</option></select><button class="button">Pesquisar</button></form><div class="rmbz-nt-list">
    <?php if(!$tracks):?><div class="rmbz-nt-empty">Nenhum Art Track encontrado.</div><?php endif;foreach($tracks as $track):$initial=function_exists('mb_substr')?mb_substr($track->artist_name,0,1):substr($track->artist_name,0,1);?><a class="rmbz-nt-row" href="<?php echo esc_url(add_query_arg(['post_type'=>'impulsionamento','page'=>'imz-native-art-tracks','track_id'=>$track->id],admin_url('edit.php')));?>"><span class="rmbz-nt-avatar"><?php if($track->photo_url):?><img src="<?php echo esc_url($track->photo_url);?>" alt=""><?php else:echo esc_html(strtoupper($initial));endif;?></span><span class="rmbz-nt-copy"><strong><?php echo esc_html($track->artist_name);?></strong><small><?php echo esc_html($track->account_phone?:'Conta ainda não ligada');?></small></span><span class="rmbz-nt-chip"><?php echo $track->verified?'Verificado':($track->status==='archived'?'Arquivado':'Ativo');?></span><span class="rmbz-nt-count"><?php echo (int)$track->catalog_count;?> músicas</span></a><?php endforeach;?></div></section>
    <aside class="rmbz-nt-panel"><form class="rmbz-nt-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php'));?>"><input type="hidden" name="action" value="rmbz_native_art_track_save"><input type="hidden" name="track_id" value="<?php echo (int)$edit->id;?>"><?php wp_nonce_field('rmbz_native_art_track_save');?><div><h2><?php echo $edit->id?'Detalhes do Art Track':'Criar Art Track';?></h2><p class="description"><?php echo $edit->id?'ID nativo #'.(int)$edit->id:'Nova identidade independente de posts WordPress.';?></p></div><div class="rmbz-nt-native">Base nativa 1MZ<?php echo $edit->legacy_post_id?' · Migrado do registo legado #'.(int)$edit->legacy_post_id:'';?></div><div class="rmbz-nt-grid"><div class="rmbz-nt-field full"><label>Nome artístico</label><input name="artist_name" required value="<?php echo esc_attr($edit->artist_name);?>"></div><div class="rmbz-nt-field"><label>Género</label><input name="genre" value="<?php echo esc_attr($edit->genre);?>"></div><div class="rmbz-nt-field"><label>País / província</label><input name="country" value="<?php echo esc_attr($edit->country);?>"></div><div class="rmbz-nt-field"><label>Telemóvel da conta</label><input name="account_phone" value="<?php echo esc_attr($edit->account_phone);?>"></div><div class="rmbz-nt-field"><label>Email da conta</label><input type="email" name="account_email" value="<?php echo esc_attr($edit->account_email);?>"></div><div class="rmbz-nt-field full"><label>Imagem</label><input type="url" name="photo_url" value="<?php echo esc_attr($edit->photo_url);?>"></div><div class="rmbz-nt-field full"><label>Biografia</label><textarea name="bio"><?php echo esc_textarea($edit->bio);?></textarea></div><div class="rmbz-nt-field"><label>Estado</label><select name="status"><option value="active" <?php selected($edit->status,'active');?>>Ativo</option><option value="archived" <?php selected($edit->status,'archived');?>>Arquivado</option></select></div><div class="rmbz-nt-field"><label>Cor</label><input type="color" name="brand_color" value="<?php echo esc_attr($edit->brand_color);?>"></div></div><label class="rmbz-nt-switch"><input type="checkbox" name="verified" value="1" <?php checked($edit->verified,1);?>>Identidade verificada pela 1MZ</label><button class="rmbz-nt-save" type="submit">Guardar Art Track</button></form><?php if($selected):?><div class="rmbz-nt-catalog"><strong>Catálogo associado</strong><?php if(!$catalog):?><p class="description">Ainda não existem publicações.</p><?php else:?><ul><?php foreach($catalog as $mid):?><li><a href="<?php echo esc_url(get_permalink($mid));?>" target="_blank" rel="noopener"><?php echo esc_html(get_the_title($mid));?></a></li><?php endforeach;?></ul><?php endif;?></div><?php endif;?></aside></div></div><?php
}