<?php
if (!defined('ABSPATH')) exit;

// 0A. MIGRAÇÃO — REPORTS
add_action('plugins_loaded', 'imz_migrate_reports_table');
function imz_migrate_reports_table() {
    global $wpdb; $t = $wpdb->prefix . 'imz_reports'; $c = $wpdb->get_col("DESCRIBE $t", 0);
    if (!in_array('reporter_email',$c)) $wpdb->query("ALTER TABLE $t ADD COLUMN reporter_email TEXT AFTER reporter_ip");
    else $wpdb->query("ALTER TABLE $t MODIFY reporter_email TEXT");
    if (!in_array('notify_on_resolve',$c)) $wpdb->query("ALTER TABLE $t ADD COLUMN notify_on_resolve tinyint(1) DEFAULT 0 NOT NULL AFTER reporter_email");
    if (!in_array('notified_at',$c)) $wpdb->query("ALTER TABLE $t ADD COLUMN notified_at datetime DEFAULT NULL AFTER notify_on_resolve");
}

// 0B. MIGRAÇÃO — COPYRIGHT + ARCHIVE
add_action('plugins_loaded', 'imz_migrate_copyright_table');
function imz_migrate_copyright_table() {
    global $wpdb; $ch = $wpdb->get_charset_collate();
    require_once ABSPATH.'wp-admin/includes/upgrade.php';
    $t = $wpdb->prefix.'imz_copyright_claims';
    if ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $t)) !== $t) {
        dbDelta("CREATE TABLE $t (id bigint(20) NOT NULL AUTO_INCREMENT,post_id bigint(20) NOT NULL,claim_level tinyint(1) NOT NULL DEFAULT 1,claimant_name varchar(255) NOT NULL,claimant_email varchar(255) NOT NULL,representative_name varchar(255) DEFAULT '',representative_email varchar(255) DEFAULT '',claim_type varchar(50) NOT NULL DEFAULT 'gravacao',description text NOT NULL,original_work_url varchar(500) DEFAULT '',id_document_path varchar(500) DEFAULT '',proof_document_path varchar(500) DEFAULT '',declaration_accepted tinyint(1) DEFAULT 0,status varchar(20) NOT NULL DEFAULT 'pendente',admin_notes text DEFAULT '',reporter_ip varchar(100) DEFAULT '',claim_date datetime NOT NULL,resolved_at datetime DEFAULT NULL,PRIMARY KEY(id),KEY post_id(post_id),KEY status(status)) $ch;");
    }
    $ta = $wpdb->prefix.'imz_copyright_archive';
    if ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $ta)) !== $ta) {
        dbDelta("CREATE TABLE $ta (id bigint(20) NOT NULL AUTO_INCREMENT,claim_id bigint(20) NOT NULL,post_id bigint(20) NOT NULL,data_type varchar(50) NOT NULL,data_content longtext NOT NULL,archived_at datetime NOT NULL,expires_at datetime NOT NULL,PRIMARY KEY(id),KEY claim_id(claim_id),KEY expires_at(expires_at)) $ch;");
    }
}

add_action('init', 'imz_start_session', 1);
if (!function_exists('imz_start_session')) { function imz_start_session() { if (!session_id()) @session_start(); } }

// ARQUIVO — separar dados quando copyright aceite
function imz_archive_post_data($post_id, $claim_id) {
    if (empty($post_id)) return;
    global $wpdb; $ar = $wpdb->prefix.'imz_copyright_archive'; $now = current_time('mysql'); $exp = date('Y-m-d H:i:s', strtotime('+1 year'));
    $save = function($type, $data) use ($wpdb,$ar,$claim_id,$post_id,$now,$exp) {
        if(empty($data))return; $wpdb->insert($ar,['claim_id'=>$claim_id,'post_id'=>$post_id,'data_type'=>$type,'data_content'=>is_string($data)?$data:json_encode($data,JSON_UNESCAPED_UNICODE),'archived_at'=>$now,'expires_at'=>$exp]);
    };
    foreach(['imz_analytics'=>'music_id','imz_plays'=>'music_id','imz_purchases'=>'music_id','imz_recommendations'=>'music_id','imz_reports'=>'post_id'] as $tbl=>$col) {
        $ft = $wpdb->prefix.$tbl;
        if($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $ft))===$ft){$rows=$wpdb->get_results($wpdb->prepare("SELECT * FROM $ft WHERE $col=%d",$post_id),ARRAY_A);if($rows){$save($tbl,$rows);$wpdb->delete($ft,[$col=>$post_id]);}}
    }
    $mk=['_imz_download_count','_imz_enable_download','_imz_enable_paid_download','_imz_enable_audio_player','_imz_audio_player_url','_imz_download_file_id','_imz_download_file_url','_imz_file_source_type','_imz_paid_download_price','_imz_download_limit_per_post','_imz_daily_download_limit','_imz_blocked_countries_per_post','_imz_digital_stores','_imz_quality','_imz_youtube_url','_imz_release_date','_imz_custom_audio_title','_imz_custom_audio_artist','_imz_total_earnings','_artist_earnings'];
    $mb=[]; foreach($mk as $k){$v=get_post_meta($post_id,$k,true);if($v!==''&&$v!==false)$mb[$k]=$v;} if(!empty($mb))$save('post_meta',$mb);
    $p=get_post($post_id); if($p) $save('post_content',['post_content'=>$p->post_content,'post_excerpt'=>$p->post_excerpt]);
    $th=get_post_thumbnail_id($post_id); if($th) $save('thumbnail_id',$th);
    update_post_meta($post_id,'_imz_enable_download','');update_post_meta($post_id,'_imz_enable_paid_download','');update_post_meta($post_id,'_imz_enable_audio_player','');delete_post_meta($post_id,'_imz_download_count');
    wp_update_post(['ID'=>$post_id,'post_content'=>'','post_excerpt'=>'']);delete_post_thumbnail($post_id);delete_transient('imz_pending_counts');
}

// RESTAURAR
function imz_restore_post_data($post_id, $claim_id) {
    if(empty($post_id))return; global $wpdb; $ar=$wpdb->prefix.'imz_copyright_archive';
    $rows=$wpdb->get_results($wpdb->prepare("SELECT * FROM $ar WHERE claim_id=%d AND post_id=%d",$claim_id,$post_id));if(empty($rows))return;
    foreach($rows as $row){$data=json_decode($row->data_content,true);
        if(in_array($row->data_type,['imz_analytics','imz_plays','imz_purchases','imz_recommendations','imz_reports'])){$ft=$wpdb->prefix.$row->data_type;if($data&&$wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $ft))===$ft)foreach($data as $r){unset($r['id']);$wpdb->insert($ft,$r);}}
        elseif($row->data_type==='post_meta'&&$data){foreach($data as $k=>$v)update_post_meta($post_id,$k,$v);}
        elseif($row->data_type==='post_content'&&$data){wp_update_post(['ID'=>$post_id,'post_content'=>$data['post_content']??'','post_excerpt'=>$data['post_excerpt']??'']);}
        elseif($row->data_type==='thumbnail_id'){$tid=is_array($data)?($data[0]??''):$data;if($tid)set_post_thumbnail($post_id,$tid);}
    }
    $wpdb->delete($ar,['claim_id'=>$claim_id,'post_id'=>$post_id]);delete_transient('imz_pending_counts');
}

// CRON — limpeza anual
add_action('wp','imz_schedule_archive_cleanup');
function imz_schedule_archive_cleanup(){if(!wp_next_scheduled('imz_cleanup_expired_archives'))wp_schedule_event(time(),'daily','imz_cleanup_expired_archives');}
add_action('imz_cleanup_expired_archives',function(){global $wpdb;$t=$wpdb->prefix.'imz_copyright_archive';if($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $t))===$t)$wpdb->query("DELETE FROM $t WHERE expires_at < NOW()");});

// COPYRIGHT BLOCK
function imz_check_copyright_block($post_id) {
    global $wpdb;$t=$wpdb->prefix.'imz_copyright_claims';if($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $t))!==$t)return false;
    $cl=$wpdb->get_row($wpdb->prepare("SELECT * FROM $t WHERE post_id=%d AND status='aceite' ORDER BY resolved_at DESC LIMIT 1",$post_id));if(!$cl)return false;
    $ct=['gravacao'=>'gravação (fonograma)','composicao'=>'composição (obra musical)','disponibilizacao'=>'disponibilização do arquivo','ambos'=>'gravação e disponibilização'];
    return '<div class="imz-copyright-blocked"><div class="imz-copyright-blocked-icon">&#128274;</div><h2>Conteúdo Indisponível</h2><p>Este conteúdo foi removido na sequência de uma reclamação de direitos de autor relativa à <strong>'.esc_html($ct[$cl->claim_type]??$cl->claim_type).'</strong>.</p><p>Reclamado por: <span class="imz-blocked-claimant">'.esc_html($cl->claimant_name).'</span></p><p class="imz-blocked-info">Se acredita que isto é um erro, pode contactar a administração do site.<br>Decisão aplicada em '.date_i18n('d/m/Y',strtotime($cl->resolved_at?:$cl->claim_date)).'.</p></div>';
}

// 1. MENUS
add_action('admin_menu', 'imz_register_reports_page');
function imz_register_reports_page() {
    $h=add_submenu_page(imz_admin_parent_slug(),'Problemas Reportados','Problemas Reportados','manage_options','imz_reports_manager','imz_render_reports_manager_page');
    add_action("load-$h",'imz_process_report_actions');
    global $wpdb;$ct=$wpdb->prefix.'imz_copyright_claims';$p=0;
    if($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $ct))===$ct)$p=(int)$wpdb->get_var("SELECT COUNT(id) FROM $ct WHERE status='pendente' AND claim_level=2");
    $l='Direitos de Autor'.($p>0?' <span class="awaiting-mod">'.$p.'</span>':'');
    $h2=add_submenu_page(imz_admin_parent_slug(),'Direitos de Autor',$l,'manage_options','imz_copyright_manager','imz_render_copyright_manager_page');
    add_action("load-$h2",'imz_process_copyright_actions');
}

// 2A. AÇÕES — REPORTS
function imz_process_report_actions() {
    global $wpdb;$t=$wpdb->prefix.'imz_reports';
    if(isset($_GET['action'],$_GET['report_id'])&&check_admin_referer('imz_report_action')){$id=absint($_GET['report_id']);$a=sanitize_key($_GET['action']);if($a==='delete'){$wpdb->delete($t,['id'=>$id]);$m='Apagado.';}elseif(in_array($a,['novo','resolvido','ignorado'],true)){$wpdb->update($t,['status'=>$a],['id'=>$id]);if($a==='resolvido'){$r=$wpdb->get_row($wpdb->prepare("SELECT * FROM $t WHERE id=%d",$id));imz_maybe_notify_reporter($r);}$m='Atualizado.';}delete_transient('imz_pending_counts');wp_redirect(add_query_arg(['page'=>'imz_reports_manager','msg'=>urlencode($m??'')],admin_url('edit.php?post_type=impulsionamento')));exit;}
    if(isset($_POST['imz_save_report_nonce'])&&wp_verify_nonce($_POST['imz_save_report_nonce'],'imz_save_report')){$id=absint($_POST['report_id']);$s=sanitize_key($_POST['report_status']);$n=sanitize_textarea_field($_POST['admin_notes']??'');$nt=isset($_POST['send_notification'])?1:0;if(!in_array($s,['novo','resolvido','ignorado'],true))$s='novo';$cur=$wpdb->get_row($wpdb->prepare("SELECT * FROM $t WHERE id=%d",$id));$wpdb->update($t,['status'=>$s,'admin_notes'=>$n],['id'=>$id]);if($nt&&$cur&&empty($cur->notified_at)){$u=$wpdb->get_row($wpdb->prepare("SELECT * FROM $t WHERE id=%d",$id));imz_maybe_notify_reporter($u,true);}delete_transient('imz_pending_counts');wp_redirect(add_query_arg(['page'=>'imz_reports_manager','view'=>$id,'msg'=>urlencode('Guardado.')],admin_url('edit.php?post_type=impulsionamento')));exit;}
}

// 2B. AÇÕES — COPYRIGHT (ARQUIVO quando aceite, RESTAURAR quando revertido)
function imz_process_copyright_actions() {
    global $wpdb;$t=$wpdb->prefix.'imz_copyright_claims';
    if(isset($_GET['action'],$_GET['claim_id'])&&check_admin_referer('imz_copyright_action')){$id=absint($_GET['claim_id']);$a=sanitize_key($_GET['action']);
        if($a==='delete'){$r=$wpdb->get_row($wpdb->prepare("SELECT * FROM $t WHERE id=%d",$id));if($r){if(!empty($r->id_document_path)&&file_exists($r->id_document_path))@unlink($r->id_document_path);if(!empty($r->proof_document_path)&&file_exists($r->proof_document_path))@unlink($r->proof_document_path);}$wpdb->delete($t,['id'=>$id]);$m='Apagada.';}
        elseif(in_array($a,['pendente','em_analise','aceite','rejeitado'],true)){$old=$wpdb->get_row($wpdb->prepare("SELECT * FROM $t WHERE id=%d",$id));$u=['status'=>$a];if(in_array($a,['aceite','rejeitado']))$u['resolved_at']=current_time('mysql');$wpdb->update($t,$u,['id'=>$id]);if($a==='aceite'&&$old&&$old->status!=='aceite')imz_archive_post_data($old->post_id,$id);if(in_array($a,['rejeitado','pendente'])&&$old&&$old->status==='aceite')imz_restore_post_data($old->post_id,$id);$r=$wpdb->get_row($wpdb->prepare("SELECT * FROM $t WHERE id=%d",$id));if($r)imz_send_copyright_status_email($r);$m=$a==='aceite'?'Aceite — conteúdo arquivado.':($a==='rejeitado'&&$old&&$old->status==='aceite'?'Rejeitado — conteúdo restaurado.':'Atualizado.');}
        wp_redirect(add_query_arg(['page'=>'imz_copyright_manager','msg'=>urlencode($m??'')],admin_url('edit.php?post_type=impulsionamento')));exit;}
    if(isset($_POST['imz_save_copyright_nonce'])&&wp_verify_nonce($_POST['imz_save_copyright_nonce'],'imz_save_copyright')){$id=absint($_POST['claim_id']);$s=sanitize_key($_POST['claim_status']);$n=sanitize_textarea_field($_POST['admin_notes']??'');if(!in_array($s,['pendente','em_analise','aceite','rejeitado'],true))$s='pendente';$old=$wpdb->get_row($wpdb->prepare("SELECT * FROM $t WHERE id=%d",$id));$u=['status'=>$s,'admin_notes'=>$n];if(in_array($s,['aceite','rejeitado']))$u['resolved_at']=current_time('mysql');$wpdb->update($t,$u,['id'=>$id]);if($s==='aceite'&&$old&&$old->status!=='aceite')imz_archive_post_data($old->post_id,$id);if(in_array($s,['rejeitado','pendente'])&&$old&&$old->status==='aceite')imz_restore_post_data($old->post_id,$id);if(isset($_POST['send_status_email'])){$r=$wpdb->get_row($wpdb->prepare("SELECT * FROM $t WHERE id=%d",$id));if($r)imz_send_copyright_status_email($r);}wp_redirect(add_query_arg(['page'=>'imz_copyright_manager','view'=>$id,'msg'=>urlencode('Guardado.'.($s==='aceite'?' Conteúdo arquivado.':''))],admin_url('edit.php?post_type=impulsionamento')));exit;}
}

// 3A. EMAIL — REPORTS
function imz_maybe_notify_reporter($row, bool $force=false) {
    if(!$row||empty($row->reporter_email)||!$row->notify_on_resolve)return;if(!$force&&!empty($row->notified_at))return;
    $bcc=[];foreach(explode(',',$row->reporter_email) as $em){$c=sanitize_email(trim($em));if(is_email($c))$bcc[]=$c;}if(empty($bcc))return;
    $mt=get_the_title($row->post_id)?:'a música';$mu=get_permalink($row->post_id)?:home_url();$sn=get_bloginfo('name');$su=home_url();$to=get_option('admin_email');$subj='['.$sn.'] Problema resolvido! ✓';$an=!empty($row->admin_notes)?esc_html($row->admin_notes):'';$rd=date_i18n('d/m/Y',strtotime($row->report_date));
    $nb='';if(!empty($an))$nb='<div style="margin-top:20px;padding:16px 20px;background:#1a1a1a;border-left:3px solid #10b981;border-radius:0 6px 6px 0;"><p style="margin:0 0 4px;font-size:11px;font-weight:700;text-transform:uppercase;color:#888;">Nota da equipa</p><p style="margin:0;font-size:14px;color:#fff;line-height:1.6;">'.$an.'</p></div>';
    $fs='-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif';
    $body=sprintf('<!DOCTYPE html><html lang="pt"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"></head><body style="margin:0;padding:0;background:#000;font-family:%s;"><table width="100%%" cellpadding="0" cellspacing="0" style="background:#000;padding:40px 16px;"><tr><td align="center"><table width="100%%" cellpadding="0" cellspacing="0" style="max-width:560px;"><tr><td style="padding-bottom:28px;text-align:center;"><span style="font-size:22px;font-weight:800;color:#fff;">%s</span></td></tr><tr><td style="background:#141414;border:1px solid #2a2a2a;border-radius:12px;overflow:hidden;"><div style="height:3px;background:#10b981;"></div><div style="padding:36px 32px;"><div style="text-align:center;margin-bottom:24px;"><div style="display:inline-block;width:56px;height:56px;background:#0d2d1f;border:1px solid #1a4a30;border-radius:50%%;line-height:56px;font-size:24px;color:#10b981;">&#10003;</div></div><h1 style="margin:0 0 8px;font-size:22px;font-weight:700;color:#fff;text-align:center;">Problema Resolvido!</h1><p style="margin:0 0 28px;font-size:15px;color:#888;text-align:center;">Obrigado por nos ter ajudado.</p><div style="background:#1a1a1a;border:1px solid #2a2a2a;border-radius:8px;padding:20px;"><table width="100%%" cellpadding="0" cellspacing="0"><tr><td style="padding-bottom:14px;border-bottom:1px solid #2a2a2a;"><span style="font-size:11px;font-weight:700;text-transform:uppercase;color:#555;">Música</span><br><span style="font-size:15px;font-weight:600;color:#fff;">%s</span></td></tr><tr><td style="padding:14px 0;border-bottom:1px solid #2a2a2a;"><span style="font-size:11px;font-weight:700;text-transform:uppercase;color:#555;">Motivo</span><br><span style="color:#ccc;">%s</span></td></tr><tr><td style="padding-top:14px;"><span style="font-size:11px;font-weight:700;text-transform:uppercase;color:#555;">Data</span><br><span style="color:#ccc;">%s</span></td></tr></table></div>%s<div style="text-align:center;margin-top:28px;"><a href="%s" style="display:inline-block;padding:14px 36px;background:#fff;color:#000;text-decoration:none;font-weight:700;font-size:14px;border-radius:6px;">Ouvir Agora</a></div></div></td></tr><tr><td style="padding:24px 0;text-align:center;"><p style="margin:0;font-size:12px;color:#444;"><a href="%s" style="color:#555;text-decoration:none;">%s</a></p></td></tr></table></td></tr></table></body></html>',
    $fs,esc_html($sn),esc_html($mt),esc_html($row->reason),$rd,$nb,esc_url($mu),esc_url($su),esc_url($su));
    $h=['Content-Type: text/html; charset=UTF-8','From: '.$sn.' <'.get_option('admin_email').'>'];foreach($bcc as $b)$h[]='Bcc: '.$b;
    if(wp_mail($to,$subj,$body,$h)){global $wpdb;$wpdb->update($wpdb->prefix.'imz_reports',['notified_at'=>current_time('mysql')],['id'=>$row->id]);}
}

// 3B. EMAIL — COPYRIGHT
function imz_send_copyright_status_email($row) {
    if(!$row||empty($row->claimant_email))return;
    $sn=get_bloginfo('name');$su=home_url();$mt=get_the_title($row->post_id)?:'Conteúdo reclamado';$fs='-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif';
    $sl=['pendente'=>['t'=>'Pendente','c'=>'#c9a347','bg'=>'#1c1207','i'=>'&#9203;'],'em_analise'=>['t'=>'Em Análise','c'=>'#3b82f6','bg'=>'#0c1829','i'=>'&#128269;'],'aceite'=>['t'=>'Aceite','c'=>'#10b981','bg'=>'#0d2d1f','i'=>'&#10003;'],'rejeitado'=>['t'=>'Rejeitado','c'=>'#ef4444','bg'=>'#1f0a0a','i'=>'&#10005;']];
    $st=$sl[$row->status]??$sl['pendente'];$lvl=$row->claim_level==2?'Nível 2':'Nível 1';$to=sanitize_email($row->claimant_email);$subj='['.$sn.'] Atualização — Direitos de Autor';
    $nb='';if(!empty($row->admin_notes))$nb='<div style="margin-top:20px;padding:16px 20px;background:#1a1a1a;border-left:3px solid '.$st['c'].';border-radius:0 6px 6px 0;"><p style="margin:0 0 4px;font-size:11px;font-weight:700;text-transform:uppercase;color:#888;">Nota da equipa</p><p style="margin:0;font-size:14px;color:#fff;line-height:1.6;">'.esc_html($row->admin_notes).'</p></div>';
    $body=sprintf('<!DOCTYPE html><html lang="pt"><head><meta charset="UTF-8"></head><body style="margin:0;padding:0;background:#000;font-family:%s;"><table width="100%%" cellpadding="0" cellspacing="0" style="background:#000;padding:40px 16px;"><tr><td align="center"><table width="100%%" cellpadding="0" cellspacing="0" style="max-width:560px;"><tr><td style="padding-bottom:28px;text-align:center;"><span style="font-size:22px;font-weight:800;color:#fff;">%s</span></td></tr><tr><td style="background:#141414;border:1px solid #2a2a2a;border-radius:12px;overflow:hidden;"><div style="height:3px;background:%s;"></div><div style="padding:36px 32px;"><div style="text-align:center;margin-bottom:24px;"><div style="display:inline-block;width:56px;height:56px;background:%s;border:1px solid %s;border-radius:50%%;line-height:56px;font-size:24px;color:%s;">%s</div></div><h1 style="margin:0 0 8px;font-size:22px;font-weight:700;color:#fff;text-align:center;">Direitos de Autor</h1><p style="margin:0 0 6px;font-size:16px;color:%s;text-align:center;font-weight:700;">Status: %s</p><p style="margin:0 0 28px;font-size:13px;color:#888;text-align:center;">%s</p><div style="background:#1a1a1a;border:1px solid #2a2a2a;border-radius:8px;padding:20px;"><p style="margin:0 0 10px;"><span style="font-size:11px;font-weight:700;text-transform:uppercase;color:#555;">Conteúdo:</span><br><span style="color:#fff;font-weight:600;">%s</span></p><p style="margin:0;"><span style="font-size:11px;font-weight:700;text-transform:uppercase;color:#555;">Reclamante:</span><br><span style="color:#ccc;">%s</span></p></div>%s</div></td></tr><tr><td style="padding:24px 0;text-align:center;"><p style="margin:0;font-size:12px;color:#444;"><a href="%s" style="color:#555;text-decoration:none;">%s</a></p></td></tr></table></td></tr></table></body></html>',
    $fs,esc_html($sn),$st['c'],$st['bg'],$st['c'],$st['c'],$st['i'],$st['c'],$st['t'],$lvl,esc_html($mt),esc_html($row->claimant_name),$nb,esc_url($su),esc_url($su));
    $h=['Content-Type: text/html; charset=UTF-8','From: '.$sn.' <'.get_option('admin_email').'>'];wp_mail($to,$subj,$body,$h);
    if(!empty($row->representative_email)&&is_email($row->representative_email))wp_mail(sanitize_email($row->representative_email),$subj,$body,$h);
}

// 4A. ADMIN — REPORTS
function imz_render_reports_manager_page() {
    global $wpdb;$t=$wpdb->prefix.'imz_reports';$cols=$wpdb->get_col("DESCRIBE $t",0);if(!in_array('admin_notes',$cols))$wpdb->query("ALTER TABLE $t ADD COLUMN admin_notes text DEFAULT '' NOT NULL");
    if(isset($_GET['view'])&&$id=absint($_GET['view'])){$row=$wpdb->get_row($wpdb->prepare("SELECT * FROM $t WHERE id=%d",$id));if(!$row){echo'<div class="wrap"><p>Não encontrado.</p></div>';return;}$mt=get_the_title($row->post_id)?:'(Apagada)';$ml=get_permalink($row->post_id);$el=get_edit_post_link($row->post_id);$ea=array_filter(array_map('trim',explode(',',$row->reporter_email)));?><div class="wrap"><h1><a href="<?php echo admin_url('edit.php?post_type=impulsionamento&page=imz_reports_manager');?>" style="text-decoration:none;color:#1d2327;font-size:14px;">← Todos os reportes</a><br>Grupo de Reportes #<?php echo $row->id;?> — <?php echo esc_html($mt);?></h1><?php if(isset($_GET['msg'])):?><div class="notice notice-success is-dismissible"><p><?php echo esc_html($_GET['msg']);?></p></div><?php endif;?><div style="display:grid;grid-template-columns:1fr 320px;gap:24px;margin-top:20px;align-items:start;"><div><div class="postbox"><div class="postbox-header"><h2 class="hndle">Detalhes da Reclamação</h2></div><div class="inside"><table class="form-table" style="margin:0;"><tr><th>Música</th><td><strong><?php echo esc_html($mt);?></strong><br><a href="<?php echo esc_url($ml);?>" target="_blank">Ver página</a><?php if($el):?> · <a href="<?php echo esc_url($el);?>" target="_blank">Editar</a><?php endif;?></td></tr><tr><th>Motivo</th><td><strong style="color:#b91c1c;font-size:15px;"><?php echo esc_html($row->reason);?></strong></td></tr><?php if(!empty($row->comments)):?><tr><th>Comentários Agrupados</th><td><div style="background:#f8fafc;border:1px solid #e2e8f0;padding:12px;border-radius:6px;"><?php echo nl2br(esc_html($row->comments));?></div></td></tr><?php endif;?><tr><th>Última Ocorrência</th><td><?php echo date_i18n('d/m/Y \à\s H:i',strtotime($row->report_date));?></td></tr><?php if(!empty($ea)):?><tr><th>Utilizadores (<?php echo count($ea);?>)</th><td><div style="max-height:120px;overflow-y:auto;background:#fff;border:1px solid #ccc;padding:6px;border-radius:4px;"><?php foreach($ea as $e):?><div style="margin-bottom:2px;"><code><?php echo esc_html($e);?></code></div><?php endforeach;?></div><?php if($row->notify_on_resolve):?><span style="background:#dbeafe;color:#1e40af;padding:3px 8px;border-radius:99px;font-size:11px;font-weight:600;margin-top:8px;display:inline-block;">Inscritos para Notificação</span><?php endif;?><?php if(!empty($row->notified_at)):?><br><small style="color:#16a34a;font-weight:600;">✓ Notificados em <?php echo date_i18n('d/m/Y H:i',strtotime($row->notified_at));?></small><?php endif;?></td></tr><?php else:?><tr><th>Emails</th><td><em style="color:#888;">Nenhum.</em></td></tr><?php endif;?></table></div></div><div class="postbox" style="margin-top:16px;"><div class="postbox-header"><h2 class="hndle">Gerir</h2></div><div class="inside"><form method="POST"><?php wp_nonce_field('imz_save_report','imz_save_report_nonce');?><input type="hidden" name="report_id" value="<?php echo $row->id;?>"><table class="form-table" style="margin:0;"><tr><th>Status</th><td><select name="report_status"><option value="novo" <?php selected($row->status,'novo');?>>Pendente</option><option value="resolvido" <?php selected($row->status,'resolvido');?>>Resolvido</option><option value="ignorado" <?php selected($row->status,'ignorado');?>>Ignorado</option></select></td></tr><tr><th>Nota interna</th><td><textarea name="admin_notes" rows="4" class="large-text"><?php echo esc_textarea($row->admin_notes??'');?></textarea><p class="description">Será enviada no email de notificação.</p></td></tr><?php if(!empty($ea)&&$row->notify_on_resolve&&empty($row->notified_at)):?><tr><th>Notificar</th><td><label><input type="checkbox" name="send_notification" value="1"> Enviar email para <?php echo count($ea);?> utilizadores</label></td></tr><?php endif;?></table><div style="margin-top:16px;display:flex;gap:10px;"><button type="submit" class="button button-primary button-large">Guardar</button><a href="<?php echo wp_nonce_url(add_query_arg(['page'=>'imz_reports_manager','action'=>'delete','report_id'=>$row->id],admin_url('edit.php?post_type=impulsionamento')),'imz_report_action');?>" class="button button-link-delete" onclick="return confirm('Apagar?');">Apagar</a></div></form></div></div></div><div><div class="postbox"><div class="postbox-header"><h2 class="hndle">Ações Rápidas</h2></div><div class="inside" style="display:flex;flex-direction:column;gap:8px;"><?php $qn=wp_create_nonce('imz_report_action');if($row->status!=='resolvido'):?><a href="<?php echo esc_url(add_query_arg(['page'=>'imz_reports_manager','action'=>'resolvido','report_id'=>$row->id,'_wpnonce'=>$qn],admin_url('edit.php?post_type=impulsionamento')));?>" class="button button-primary" style="width:100%;text-align:center;">✓ Resolvido</a><?php endif;if($row->status!=='ignorado'):?><a href="<?php echo esc_url(add_query_arg(['page'=>'imz_reports_manager','action'=>'ignorado','report_id'=>$row->id,'_wpnonce'=>$qn],admin_url('edit.php?post_type=impulsionamento')));?>" class="button" style="width:100%;text-align:center;">Ignorar</a><?php endif;if($el):?><a href="<?php echo esc_url($el);?>" target="_blank" class="button" style="width:100%;text-align:center;">✎ Editar</a><?php endif;?></div></div></div></div></div><?php return;}
    $pp=20;$pg=max(1,intval($_GET['paged']??1));$off=($pg-1)*$pp;$tot=(int)$wpdb->get_var("SELECT COUNT(id) FROM $t");$tp=(int)ceil($tot/$pp);$rows=$wpdb->get_results($wpdb->prepare("SELECT * FROM $t ORDER BY report_date DESC LIMIT %d OFFSET %d",$pp,$off));$sl=['novo'=>['l'=>'Pendente','c'=>'#854d0e','bg'=>'#fef9c3'],'resolvido'=>['l'=>'Resolvido','c'=>'#166534','bg'=>'#dcfce7'],'ignorado'=>['l'=>'Ignorado','c'=>'#374151','bg'=>'#f3f4f6']];?><div class="wrap"><h1>Problemas Reportados (Agrupados)</h1><?php if(isset($_GET['msg'])):?><div class="notice notice-success is-dismissible"><p><?php echo esc_html($_GET['msg']);?></p></div><?php endif;?><table class="wp-list-table widefat fixed striped" style="margin-top:16px;"><thead><tr><th width="40">#</th><th width="120">Data</th><th>Música</th><th>Motivo</th><th width="80">Users</th><th width="90">Status</th><th width="80">Ações</th></tr></thead><tbody><?php if($rows):foreach($rows as $row):$mt=get_the_title($row->post_id)?:'(Apagada)';$s=$sl[$row->status]??['l'=>$row->status,'c'=>'#000','bg'=>'#eee'];$du=admin_url('edit.php?post_type=impulsionamento&page=imz_reports_manager&view='.$row->id);$ec=count(array_filter(array_map('trim',explode(',',$row->reporter_email))));?><tr><td><?php echo $row->id;?></td><td style="font-size:12px;"><?php echo date_i18n('d/m/y H:i',strtotime($row->report_date));?></td><td><a href="<?php echo esc_url($du);?>" style="font-weight:600;"><?php echo esc_html($mt);?></a></td><td><strong style="color:#b91c1c;"><?php echo esc_html($row->reason);?></strong></td><td style="text-align:center;"><?php echo $ec>0?$ec:'0';?></td><td><span style="background:<?php echo $s['bg'];?>;color:<?php echo $s['c'];?>;padding:3px 8px;border-radius:99px;font-size:11px;font-weight:700;text-transform:uppercase;"><?php echo $s['l'];?></span></td><td><a href="<?php echo esc_url($du);?>" class="button button-small">Ver</a></td></tr><?php endforeach;else:?><tr><td colspan="7" style="text-align:center;padding:30px;">Nenhum reporte.</td></tr><?php endif;?></tbody></table><?php if($tp>1):?><div class="tablenav bottom"><div class="tablenav-pages"><?php echo paginate_links(['base'=>add_query_arg('paged','%#%'),'total'=>$tp,'current'=>$pg]);?></div></div><?php endif;?></div><?php
}

// 4B. ADMIN — COPYRIGHT
function imz_render_copyright_manager_page() {
    global $wpdb;$t=$wpdb->prefix.'imz_copyright_claims';$sl=['pendente'=>['l'=>'Pendente','c'=>'#854d0e','bg'=>'#fef9c3','i'=>'⏳'],'em_analise'=>['l'=>'Em Análise','c'=>'#1e40af','bg'=>'#dbeafe','i'=>'🔍'],'aceite'=>['l'=>'Aceite','c'=>'#166534','bg'=>'#dcfce7','i'=>'✓'],'rejeitado'=>['l'=>'Rejeitado','c'=>'#991b1b','bg'=>'#fee2e2','i'=>'✕']];$ctl=['gravacao'=>'Gravação (fonograma)','composicao'=>'Composição','disponibilizacao'=>'Disponibilização','ambos'=>'Gravação e Disponibilização'];
    if(isset($_GET['view'])&&$id=absint($_GET['view'])){$row=$wpdb->get_row($wpdb->prepare("SELECT * FROM $t WHERE id=%d",$id));if(!$row){echo'<div class="wrap"><p>Não encontrada.</p></div>';return;}$mt=get_the_title($row->post_id)?:'(Removido)';$ml=get_permalink($row->post_id);$el=get_edit_post_link($row->post_id);$st=$sl[$row->status]??$sl['pendente'];?><div class="wrap"><h1><a href="<?php echo admin_url('edit.php?post_type=impulsionamento&page=imz_copyright_manager');?>" style="text-decoration:none;color:#1d2327;font-size:14px;">← Voltar</a><br>Reclamação #<?php echo $row->id;?> — <?php echo esc_html($mt);?> <?php echo $row->claim_level==2?'<span style="background:#fee2e2;color:#991b1b;padding:4px 10px;border-radius:99px;font-size:12px;font-weight:700;margin-left:8px;">⚠ NÍVEL 2</span>':'<span style="background:#dbeafe;color:#1e40af;padding:4px 10px;border-radius:99px;font-size:12px;font-weight:700;margin-left:8px;">NÍVEL 1</span>';?></h1><?php if(isset($_GET['msg'])):?><div class="notice notice-success is-dismissible"><p><?php echo esc_html($_GET['msg']);?></p></div><?php endif;?><div style="display:grid;grid-template-columns:1fr 320px;gap:24px;margin-top:20px;align-items:start;"><div><div class="postbox"><div class="postbox-header"><h2 class="hndle">Detalhes</h2></div><div class="inside"><table class="form-table" style="margin:0;"><tr><th>Conteúdo</th><td><strong><?php echo esc_html($mt);?></strong><br><?php if($ml):?><a href="<?php echo esc_url($ml);?>" target="_blank">Ver</a><?php endif;?><?php if($el):?> · <a href="<?php echo esc_url($el);?>" target="_blank">Editar</a><?php endif;?></td></tr><tr><th>Tipo</th><td><strong style="color:#b91c1c;"><?php echo esc_html($ctl[$row->claim_type]??$row->claim_type);?></strong></td></tr><tr><th>Reclamante</th><td><?php echo esc_html($row->claimant_name);?><br><a href="mailto:<?php echo esc_attr($row->claimant_email);?>"><?php echo esc_html($row->claimant_email);?></a></td></tr><?php if(!empty($row->representative_name)):?><tr><th>Representante</th><td><?php echo esc_html($row->representative_name);?><?php if(!empty($row->representative_email)):?><br><a href="mailto:<?php echo esc_attr($row->representative_email);?>"><?php echo esc_html($row->representative_email);?></a><?php endif;?></td></tr><?php endif;?><tr><th>Descrição</th><td><div style="background:#f8fafc;border:1px solid #e2e8f0;padding:12px;border-radius:6px;white-space:pre-wrap;"><?php echo esc_html($row->description);?></div></td></tr><?php if(!empty($row->original_work_url)):?><tr><th>Obra Original</th><td><a href="<?php echo esc_url($row->original_work_url);?>" target="_blank"><?php echo esc_html($row->original_work_url);?></a></td></tr><?php endif;?><tr><th>Data</th><td><?php echo date_i18n('d/m/Y H:i',strtotime($row->claim_date));?></td></tr><tr><th>IP</th><td><code><?php echo esc_html($row->reporter_ip);?></code></td></tr></table></div></div><?php if($row->claim_level==2):$ud=wp_upload_dir();?><div class="postbox" style="margin-top:16px;border-left:3px solid #991b1b;"><div class="postbox-header"><h2 class="hndle">📎 Documentos (Nível 2)</h2></div><div class="inside"><table class="form-table" style="margin:0;"><?php if(!empty($row->id_document_path)):$iu=str_replace($ud['basedir'],$ud['baseurl'],$row->id_document_path);$ie=strtolower(pathinfo($row->id_document_path,PATHINFO_EXTENSION));?><tr><th>BI</th><td><?php if(in_array($ie,['jpg','jpeg','png','webp'])):?><a href="<?php echo esc_url($iu);?>" target="_blank"><img src="<?php echo esc_url($iu);?>" style="max-width:300px;border-radius:8px;border:1px solid #ddd;"></a><?php else:?><a href="<?php echo esc_url($iu);?>" target="_blank" class="button">⬇ (<?php echo strtoupper($ie);?>)</a><?php endif;?></td></tr><?php endif;if(!empty($row->proof_document_path)):$pu=str_replace($ud['basedir'],$ud['baseurl'],$row->proof_document_path);$pe=strtolower(pathinfo($row->proof_document_path,PATHINFO_EXTENSION));?><tr><th>Prova</th><td><?php if(in_array($pe,['jpg','jpeg','png','webp'])):?><a href="<?php echo esc_url($pu);?>" target="_blank"><img src="<?php echo esc_url($pu);?>" style="max-width:300px;border-radius:8px;border:1px solid #ddd;"></a><?php else:?><a href="<?php echo esc_url($pu);?>" target="_blank" class="button">⬇ (<?php echo strtoupper($pe);?>)</a><?php endif;?></td></tr><?php endif;?><tr><th>Declaração</th><td><?php echo $row->declaration_accepted?'<span style="color:#166534;font-weight:600;">✓ Aceite</span>':'<span style="color:#991b1b;">✕ Não aceite</span>';?></td></tr></table></div></div><?php endif;?><div class="postbox" style="margin-top:16px;"><div class="postbox-header"><h2 class="hndle">Gerir</h2></div><div class="inside"><form method="POST"><?php wp_nonce_field('imz_save_copyright','imz_save_copyright_nonce');?><input type="hidden" name="claim_id" value="<?php echo $row->id;?>"><table class="form-table" style="margin:0;"><tr><th>Status</th><td><select name="claim_status"><option value="pendente" <?php selected($row->status,'pendente');?>>Pendente</option><option value="em_analise" <?php selected($row->status,'em_analise');?>>Em Análise</option><option value="aceite" <?php selected($row->status,'aceite');?>>Aceite — Arquivar e Ocultar</option><option value="rejeitado" <?php selected($row->status,'rejeitado');?>>Rejeitado<?php echo $row->status==='aceite'?' — Restaurar':'';?></option></select><p class="description">Ao aceitar, os dados são <strong>arquivados</strong> durante 1 ano. Se rejeitado depois, tudo é restaurado.</p></td></tr><tr><th>Nota</th><td><textarea name="admin_notes" rows="4" class="large-text"><?php echo esc_textarea($row->admin_notes??'');?></textarea></td></tr><tr><th>Notificar</th><td><label><input type="checkbox" name="send_status_email" value="1" checked> Enviar email ao reclamante</label></td></tr></table><div style="margin-top:16px;display:flex;gap:10px;"><button type="submit" class="button button-primary button-large">Guardar</button><a href="<?php echo wp_nonce_url(add_query_arg(['page'=>'imz_copyright_manager','action'=>'delete','claim_id'=>$row->id],admin_url('edit.php?post_type=impulsionamento')),'imz_copyright_action');?>" class="button button-link-delete" onclick="return confirm('Apagar?');">Apagar</a></div></form></div></div></div><div><div class="postbox"><div class="postbox-header"><h2 class="hndle">Status</h2></div><div class="inside" style="text-align:center;padding:20px;"><span style="background:<?php echo $st['bg'];?>;color:<?php echo $st['c'];?>;padding:6px 16px;border-radius:99px;font-size:14px;font-weight:700;"><?php echo $st['i'].' '.$st['l'];?></span></div></div><div class="postbox" style="margin-top:12px;"><div class="postbox-header"><h2 class="hndle">Ações</h2></div><div class="inside" style="display:flex;flex-direction:column;gap:8px;"><?php $qn=wp_create_nonce('imz_copyright_action');if($row->status!=='em_analise'):?><a href="<?php echo esc_url(add_query_arg(['page'=>'imz_copyright_manager','action'=>'em_analise','claim_id'=>$row->id,'_wpnonce'=>$qn],admin_url('edit.php?post_type=impulsionamento')));?>" class="button" style="width:100%;text-align:center;">🔍 Em Análise</a><?php endif;if($row->status!=='aceite'):?><a href="<?php echo esc_url(add_query_arg(['page'=>'imz_copyright_manager','action'=>'aceite','claim_id'=>$row->id,'_wpnonce'=>$qn],admin_url('edit.php?post_type=impulsionamento')));?>" class="button button-primary" style="width:100%;text-align:center;" onclick="return confirm('Arquivar e ocultar conteúdo?');">✓ Aceitar (Arquivar)</a><?php endif;if($row->status==='aceite'):?><a href="<?php echo esc_url(add_query_arg(['page'=>'imz_copyright_manager','action'=>'rejeitado','claim_id'=>$row->id,'_wpnonce'=>$qn],admin_url('edit.php?post_type=impulsionamento')));?>" class="button" style="width:100%;text-align:center;color:#2563eb;" onclick="return confirm('Restaurar todo o conteúdo?');">↩ Restaurar Conteúdo</a><?php endif;if($row->status!=='rejeitado'&&$row->status!=='aceite'):?><a href="<?php echo esc_url(add_query_arg(['page'=>'imz_copyright_manager','action'=>'rejeitado','claim_id'=>$row->id,'_wpnonce'=>$qn],admin_url('edit.php?post_type=impulsionamento')));?>" class="button" style="width:100%;text-align:center;color:#991b1b;">✕ Rejeitar</a><?php endif;?></div></div></div></div></div><?php return;}
    // LISTA
    $pp=20;$pg=max(1,intval($_GET['paged']??1));$off=($pg-1)*$pp;$fl=isset($_GET['level'])?absint($_GET['level']):0;$fst=isset($_GET['status'])?sanitize_key($_GET['status']):'';$w="WHERE 1=1";if($fl)$w.=$wpdb->prepare(" AND claim_level=%d",$fl);if($fst)$w.=$wpdb->prepare(" AND status=%s",$fst);$tot=(int)$wpdb->get_var("SELECT COUNT(id) FROM $t $w");$tp=(int)ceil($tot/$pp);$rows=$wpdb->get_results($wpdb->prepare("SELECT * FROM $t $w ORDER BY claim_level DESC,claim_date DESC LIMIT %d OFFSET %d",$pp,$off));$cl2=(int)$wpdb->get_var("SELECT COUNT(id) FROM $t WHERE claim_level=2 AND status='pendente'");$cts=['gravacao'=>'Gravação','composicao'=>'Composição','disponibilizacao'=>'Disponibilização','ambos'=>'Grav.+Disp.'];?><div class="wrap"><h1>Direitos de Autor<?php if($cl2>0):?> <span style="background:#fee2e2;color:#991b1b;padding:4px 12px;border-radius:99px;font-size:13px;font-weight:700;">⚠ <?php echo $cl2;?> Nível 2</span><?php endif;?></h1><?php if(isset($_GET['msg'])):?><div class="notice notice-success is-dismissible"><p><?php echo esc_html($_GET['msg']);?></p></div><?php endif;?><div style="margin:16px 0;display:flex;gap:8px;flex-wrap:wrap;"><a href="<?php echo admin_url('edit.php?post_type=impulsionamento&page=imz_copyright_manager');?>" class="button <?php echo(!$fl&&!$fst)?'button-primary':'';?>">Todos</a><a href="<?php echo add_query_arg('level',2,admin_url('edit.php?post_type=impulsionamento&page=imz_copyright_manager'));?>" class="button <?php echo $fl==2?'button-primary':'';?>">⚠ Nível 2</a><a href="<?php echo add_query_arg('level',1,admin_url('edit.php?post_type=impulsionamento&page=imz_copyright_manager'));?>" class="button <?php echo $fl==1?'button-primary':'';?>">Nível 1</a><span style="border-left:1px solid #ccc;margin:0 4px;"></span><a href="<?php echo add_query_arg('status','pendente',admin_url('edit.php?post_type=impulsionamento&page=imz_copyright_manager'));?>" class="button <?php echo $fst==='pendente'?'button-primary':'';?>">Pendentes</a><a href="<?php echo add_query_arg('status','em_analise',admin_url('edit.php?post_type=impulsionamento&page=imz_copyright_manager'));?>" class="button <?php echo $fst==='em_analise'?'button-primary':'';?>">Em Análise</a></div><table class="wp-list-table widefat fixed striped" style="margin-top:8px;"><thead><tr><th width="40">#</th><th width="55">Nível</th><th width="100">Data</th><th>Conteúdo</th><th>Reclamante</th><th width="110">Tipo</th><th width="90">Status</th><th width="60"></th></tr></thead><tbody><?php if($rows):foreach($rows as $row):$mt=get_the_title($row->post_id)?:'(Apagado)';$s=$sl[$row->status]??$sl['pendente'];$du=admin_url('edit.php?post_type=impulsionamento&page=imz_copyright_manager&view='.$row->id);?><tr <?php echo($row->claim_level==2&&$row->status==='pendente')?'style="background:#fffbeb;"':'';?>><td><?php echo $row->id;?></td><td><?php echo $row->claim_level==2?'<span style="background:#fee2e2;color:#991b1b;padding:2px 8px;border-radius:99px;font-size:11px;font-weight:700;">N2 ⚠</span>':'<span style="background:#dbeafe;color:#1e40af;padding:2px 8px;border-radius:99px;font-size:11px;font-weight:700;">N1</span>';?></td><td style="font-size:12px;"><?php echo date_i18n('d/m/y H:i',strtotime($row->claim_date));?></td><td><a href="<?php echo esc_url($du);?>" style="font-weight:600;"><?php echo esc_html($mt);?></a></td><td><?php echo esc_html($row->claimant_name);?><br><small style="color:#888;"><?php echo esc_html($row->claimant_email);?></small></td><td style="font-size:12px;"><?php echo esc_html($cts[$row->claim_type]??$row->claim_type);?></td><td><span style="background:<?php echo $s['bg'];?>;color:<?php echo $s['c'];?>;padding:3px 8px;border-radius:99px;font-size:11px;font-weight:700;"><?php echo $s['l'];?></span></td><td><a href="<?php echo esc_url($du);?>" class="button button-small">Ver</a></td></tr><?php endforeach;else:?><tr><td colspan="8" style="text-align:center;padding:30px;">Nenhuma reclamação.</td></tr><?php endif;?></tbody></table><?php if($tp>1):?><div class="tablenav bottom"><div class="tablenav-pages"><?php echo paginate_links(['base'=>add_query_arg('paged','%#%'),'total'=>$tp,'current'=>$pg]);?></div></div><?php endif;?></div><?php
}

// 5. FRONTEND — MODAL UNIFICADO
function imz_get_report_modal_html($current_post_id = null) {
    global $post;if(is_null($current_post_id)&&isset($post))$current_post_id=$post->ID;if(empty($current_post_id))return'';
    $dr="Link de download quebrado\nÁudio com má qualidade\nInformações incorretas\nConteúdo ofensivo\nOutro";$reasons=explode("\n",trim(get_option('imz_report_reasons',$dr)));
    remove_filter('the_title','imz_add_verified_badge_to_title',10,2);$music_title=get_the_title($current_post_id);add_filter('the_title','imz_add_verified_badge_to_title',10,2);$sk=get_option('imz_recaptcha_site_key');ob_start();?>
    <div id="imz-report-modal-overlay" class="imz-modal-hidden"><div id="imz-report-modal-content"><button id="imz-close-report-modal" class="imz-modal-close-btn" aria-label="Fechar"><svg viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="1" y1="1" x2="13" y2="13"/><line x1="13" y1="1" x2="1" y2="13"/></svg></button>
        <div class="imz-report-panel active" data-panel="choice"><h3>O que pretende fazer?</h3><p>Música: <strong><?php echo esc_html($music_title);?></strong></p><div class="imz-report-choice"><button type="button" class="imz-report-choice-btn" data-goto="report"><div class="imz-choice-icon">&#9888;&#65039;</div><div class="imz-choice-text"><strong>Relatar um Problema</strong><span>Link de download partido, áudio com má qualidade, informações incorretas, conteúdo ofensivo, etc.</span></div></button><button type="button" class="imz-report-choice-btn" data-goto="copyright"><div class="imz-choice-icon">&#9878;&#65039;</div><div class="imz-choice-text"><strong>Reclamar Direitos de Autor</strong><span>O conteúdo pertence-lhe ou ao seu cliente e não foi autorizado a ser disponibilizado.</span></div></button></div></div>
        <div class="imz-report-panel" data-panel="report"><button type="button" class="imz-back-btn" data-goto="choice">&#8592; Voltar</button><h3>Relatar um Problema</h3><p>Música: <strong><?php echo esc_html($music_title);?></strong></p><form id="imz-report-form"><input type="hidden" name="post_id" value="<?php echo esc_attr($current_post_id);?>"><?php wp_nonce_field('imz_submit_report_nonce','nonce');?><div class="imz-form-group"><label for="report_reason">Qual o problema?</label><select name="report_reason" id="report_reason" required><option value="">-- Selecione --</option><?php foreach($reasons as $r):?><option value="<?php echo esc_attr(trim($r));?>"><?php echo esc_html(trim($r));?></option><?php endforeach;?></select></div><div class="imz-form-group"><label for="report_comments">Detalhes (opcional)</label><textarea name="report_comments" id="report_comments" rows="3" placeholder="Descreva o problema com mais detalhe..."></textarea></div><div class="imz-form-group"><label for="report_notify_check" style="display:flex;align-items:center;gap:10px;cursor:pointer;font-size:13px;font-weight:500;"><input type="checkbox" id="report_notify_check" name="notify_on_resolve" value="1" style="width:16px;height:16px;accent-color:#fff;flex-shrink:0;">Quero ser notificado por email quando o problema for resolvido</label></div><div id="imz-email-field-wrapper" style="display:none;"><div class="imz-form-group"><label for="reporter_email">O seu email</label><input type="email" name="reporter_email" id="reporter_email" placeholder="exemplo@email.com" autocomplete="email"><small style="color:#555;font-size:12px;margin-top:4px;display:block;">Usado apenas para notificá-lo. Não será partilhado.</small></div></div><?php if(!empty($sk)):?><div class="imz-form-group" style="display:flex;justify-content:center;"><div id="imz-report-recaptcha" class="g-recaptcha" data-sitekey="<?php echo esc_attr($sk);?>"></div></div><?php endif;?><button type="submit" class="imz-botao-principal" style="width:100%;margin-top:10px;">Enviar Reporte</button></form><div id="imz-report-messages"></div></div>
        <div class="imz-report-panel" data-panel="copyright"><button type="button" class="imz-back-btn" data-goto="choice">&#8592; Voltar</button><h3>&#9878; Reclamação de Direitos de Autor</h3><p style="color:#888;font-size:14px;margin-bottom:16px;">Música: <strong style="color:#fff;"><?php echo esc_html($music_title);?></strong></p><div class="imz-copyright-tabs"><button type="button" class="imz-copyright-tab active" data-lvl="1"><span class="imz-tab-ico">&#128221;</span>Nível 1 — Informativo</button><button type="button" class="imz-copyright-tab" data-lvl="2"><span class="imz-tab-ico">&#128206;</span>Nível 2 — Com Documentos</button></div>
            <div class="imz-copyright-lvl active" data-lvl-panel="1"><div class="imz-info-box"><strong>Nível 1 — Reclamação Informativa</strong><br>Preencha o formulário para nos informar sobre uma possível violação de direitos de autor.</div><form id="imz-copyright-form-l1" class="imz-copyright-form"><input type="hidden" name="post_id" value="<?php echo esc_attr($current_post_id);?>"><input type="hidden" name="claim_level" value="1"><?php wp_nonce_field('imz_submit_copyright_nonce','copyright_nonce');?><div class="imz-form-group"><label>O que está a ser afetado? <span class="imz-req">*</span></label><select name="claim_type" required><option value="">-- Selecione --</option><option value="gravacao">Gravação (fonograma)</option><option value="composicao">Composição (obra musical)</option><option value="disponibilizacao">Disponibilização do arquivo</option><option value="ambos">Gravação e Disponibilização</option></select></div><div class="imz-form-group"><label>Explique o motivo da reclamação <span class="imz-req">*</span></label><textarea name="description" rows="4" placeholder="Descreva detalhadamente..." required></textarea></div><div class="imz-form-group"><label>Link da obra original (se disponível)</label><input type="url" name="original_work_url" placeholder="https://..."></div><div class="imz-form-row"><div class="imz-form-group"><label>O seu nome completo <span class="imz-req">*</span></label><input type="text" name="claimant_name" required placeholder="Nome completo"></div><div class="imz-form-group"><label>O seu email <span class="imz-req">*</span></label><input type="email" name="claimant_email" required placeholder="email@exemplo.com"></div></div><div class="imz-form-row"><div class="imz-form-group"><label>Nome do representante</label><input type="text" name="representative_name" placeholder="(Se aplicável)"></div><div class="imz-form-group"><label>Email do representante</label><input type="email" name="representative_email" placeholder="(Se aplicável)"></div></div><?php if(!empty($sk)):?><div class="imz-form-group" style="display:flex;justify-content:center;"><div id="imz-copyright-recaptcha-l1" class="g-recaptcha" data-sitekey="<?php echo esc_attr($sk);?>"></div></div><?php endif;?><button type="submit" class="imz-botao-principal" style="width:100%;margin-top:10px;">Submeter Reclamação</button></form></div>
            <div class="imz-copyright-lvl" data-lvl-panel="2"><div class="imz-warn-box"><strong>&#9888; Nível 2 — Reclamação Formal</strong><br>Requer Bilhete de Identificação e prova de propriedade. Enviada à administração.</div><form id="imz-copyright-form-l2" class="imz-copyright-form" enctype="multipart/form-data"><input type="hidden" name="post_id" value="<?php echo esc_attr($current_post_id);?>"><input type="hidden" name="claim_level" value="2"><?php wp_nonce_field('imz_submit_copyright_nonce','copyright_nonce');?><div class="imz-form-group"><label>O que está a ser afetado? <span class="imz-req">*</span></label><select name="claim_type" required><option value="">-- Selecione --</option><option value="gravacao">Gravação (fonograma)</option><option value="composicao">Composição (obra musical)</option><option value="disponibilizacao">Disponibilização do arquivo</option><option value="ambos">Gravação e Disponibilização</option></select></div><div class="imz-form-group"><label>Explique o motivo da reclamação <span class="imz-req">*</span></label><textarea name="description" rows="4" placeholder="Descreva detalhadamente..." required></textarea></div><div class="imz-form-group"><label>Link da obra original (se disponível)</label><input type="url" name="original_work_url" placeholder="https://..."></div><div class="imz-form-row"><div class="imz-form-group"><label>O seu nome completo <span class="imz-req">*</span></label><input type="text" name="claimant_name" required placeholder="Nome completo"></div><div class="imz-form-group"><label>O seu email <span class="imz-req">*</span></label><input type="email" name="claimant_email" required placeholder="email@exemplo.com"></div></div><div class="imz-form-row"><div class="imz-form-group"><label>Nome do representante</label><input type="text" name="representative_name" placeholder="(Se aplicável)"></div><div class="imz-form-group"><label>Email do representante</label><input type="email" name="representative_email" placeholder="(Se aplicável)"></div></div><div class="imz-form-group"><label>Bilhete de Identificação <span class="imz-req">*</span></label><div class="imz-file-drop" id="imz-drop-id"><div class="imz-file-drop-ico">&#129706;</div><div class="imz-file-drop-txt"><strong>Clique para enviar</strong> ou arraste<br><small>JPG, PNG ou PDF — máx. 5MB</small></div><div class="imz-file-drop-name" id="imz-fname-id"></div><input type="file" name="id_document" id="imz-finput-id" accept=".jpg,.jpeg,.png,.pdf" style="display:none;" required></div></div><div class="imz-form-group"><label>Prova de Propriedade <span class="imz-req">*</span></label><div class="imz-file-drop" id="imz-drop-proof"><div class="imz-file-drop-ico">&#128196;</div><div class="imz-file-drop-txt"><strong>Clique para enviar</strong> ou arraste<br><small>Contrato, registo, certificado — máx. 5MB</small></div><div class="imz-file-drop-name" id="imz-fname-proof"></div><input type="file" name="proof_document" id="imz-finput-proof" accept=".jpg,.jpeg,.png,.pdf" style="display:none;" required></div></div><div class="imz-form-group"><label class="imz-chk-label"><input type="checkbox" name="declaration_accepted" value="1" required><span>Declaro sob pena de perjúrio que as informações são verdadeiras, que sou o titular dos direitos de autor ou estou autorizado a agir em nome do titular, e que o uso não é autorizado.</span></label></div><?php if(!empty($sk)):?><div class="imz-form-group" style="display:flex;justify-content:center;"><div id="imz-copyright-recaptcha-l2" class="g-recaptcha" data-sitekey="<?php echo esc_attr($sk);?>"></div></div><?php endif;?><button type="submit" class="imz-botao-principal" style="width:100%;margin-top:10px;">&#9888; Submeter Reclamação Formal</button></form></div>
            <div id="imz-copyright-messages"></div></div>
    </div></div>
    <?php return ob_get_clean();
}

// 6A. AJAX — REPORTS
add_action('wp_ajax_imz_submit_report','imz_handle_report_submission');add_action('wp_ajax_nopriv_imz_submit_report','imz_handle_report_submission');
function imz_handle_report_submission() {
    check_ajax_referer('imz_submit_report_nonce','nonce');$ip=imz_get_user_ip();$tk='imz_report_ip_'.md5($ip);if(get_transient($tk))wp_send_json_error(['message'=>'Aguarde um momento.']);$rc=isset($_POST['g-recaptcha-response'])?sanitize_text_field($_POST['g-recaptcha-response']):'';if(function_exists('imz_verify_recaptcha')&&!imz_verify_recaptcha($rc))wp_send_json_error(['message'=>'Verificação falhou.']);$pid=absint($_POST['post_id']??0);$reason=sanitize_text_field($_POST['report_reason']??'');$comments=sanitize_textarea_field($_POST['report_comments']??'');$email=sanitize_email($_POST['reporter_email']??'');$notify=!empty($_POST['notify_on_resolve'])&&!empty($email)?1:0;if(!$pid||!$reason)wp_send_json_error(['message'=>'Selecione um motivo.']);if($notify&&!is_email($email))wp_send_json_error(['message'=>'Email inválido.']);global $wpdb;$t=$wpdb->prefix.'imz_reports';$ex=$wpdb->get_row($wpdb->prepare("SELECT * FROM $t WHERE post_id=%d AND reason=%s AND status='novo' LIMIT 1",$pid,$reason));if($ex){$nc=$ex->comments;if(!empty($comments))$nc.=(empty($nc)?'':"\n\n---\n\n")."• ".$comments;$ea=!empty($ex->reporter_email)?array_map('trim',explode(',',$ex->reporter_email)):[];if($notify&&is_email($email)&&!in_array($email,$ea))$ea[]=$email;$wpdb->update($t,['comments'=>$nc,'reporter_email'=>implode(',',$ea),'notify_on_resolve'=>($ex->notify_on_resolve||$notify)?1:0,'report_date'=>current_time('mysql')],['id'=>$ex->id]);set_transient($tk,true,60);delete_transient('imz_pending_counts');wp_send_json_success(['message'=>'Obrigado! Reporte registado.']);return;}$wpdb->insert($t,['post_id'=>$pid,'reason'=>$reason,'comments'=>$comments,'reporter_ip'=>$ip,'reporter_email'=>$email,'notify_on_resolve'=>$notify,'status'=>'novo','report_date'=>current_time('mysql')],['%d','%s','%s','%s','%s','%d','%s','%s']);if($wpdb->insert_id){set_transient($tk,true,60);delete_transient('imz_pending_counts');wp_send_json_success(['message'=>$notify?'Obrigado! Será notificado por email.':'Obrigado! Reporte registado.']);}else wp_send_json_error(['message'=>'Erro.']);
}

// 6B. AJAX — COPYRIGHT
add_action('wp_ajax_imz_submit_copyright_claim','imz_handle_copyright_submission');add_action('wp_ajax_nopriv_imz_submit_copyright_claim','imz_handle_copyright_submission');
function imz_handle_copyright_submission() {
    check_ajax_referer('imz_submit_copyright_nonce','copyright_nonce');$rc=isset($_POST['g-recaptcha-response'])?sanitize_text_field($_POST['g-recaptcha-response']):'';if(function_exists('imz_verify_recaptcha')&&!imz_verify_recaptcha($rc))wp_send_json_error(['message'=>'Complete "Não sou um robô".']);$ip=imz_get_user_ip();$tk='imz_copyright_ip_'.md5($ip);if(get_transient($tk))wp_send_json_error(['message'=>'Aguarde 5 minutos.']);$pid=absint($_POST['post_id']??0);$lvl=absint($_POST['claim_level']??1);$ct=sanitize_key($_POST['claim_type']??'');$desc=sanitize_textarea_field($_POST['description']??'');$ourl=esc_url_raw($_POST['original_work_url']??'');$cn=sanitize_text_field($_POST['claimant_name']??'');$ce=sanitize_email($_POST['claimant_email']??'');$rn=sanitize_text_field($_POST['representative_name']??'');$re=sanitize_email($_POST['representative_email']??'');if(!$pid)wp_send_json_error(['message'=>'Conteúdo não identificado.']);if(!in_array($ct,['gravacao','composicao','disponibilizacao','ambos']))wp_send_json_error(['message'=>'Selecione o tipo.']);if(strlen($desc)<20)wp_send_json_error(['message'=>'Mín. 20 caracteres.']);if(!$cn)wp_send_json_error(['message'=>'Nome obrigatório.']);if(!is_email($ce))wp_send_json_error(['message'=>'Email inválido.']);$idp='';$pp='';
    if($lvl==2){if(empty($_POST['declaration_accepted']))wp_send_json_error(['message'=>'Aceite a declaração.']);if(empty($_FILES['id_document'])||$_FILES['id_document']['error']!==UPLOAD_ERR_OK)wp_send_json_error(['message'=>'Envie o BI.']);if(empty($_FILES['proof_document'])||$_FILES['proof_document']['error']!==UPLOAD_ERR_OK)wp_send_json_error(['message'=>'Envie a prova.']);$at=['image/jpeg','image/png','application/pdf'];$mx=5242880;if(!in_array($_FILES['id_document']['type'],$at))wp_send_json_error(['message'=>'BI: formato inválido.']);if($_FILES['id_document']['size']>$mx)wp_send_json_error(['message'=>'BI: máx. 5MB.']);if(!in_array($_FILES['proof_document']['type'],$at))wp_send_json_error(['message'=>'Prova: formato inválido.']);if($_FILES['proof_document']['size']>$mx)wp_send_json_error(['message'=>'Prova: máx. 5MB.']);$ud=wp_upload_dir();$dir=$ud['basedir'].'/imz-copyright-claims/'.date('Y/m');if(!file_exists($dir)){wp_mkdir_p($dir);file_put_contents($dir.'/.htaccess',"Order deny,allow\nDeny from all");file_put_contents($dir.'/index.php','<?php // Silence');}$idp=$dir.'/bi_'.wp_generate_uuid4().'.'.pathinfo($_FILES['id_document']['name'],PATHINFO_EXTENSION);if(!move_uploaded_file($_FILES['id_document']['tmp_name'],$idp))wp_send_json_error(['message'=>'Erro upload BI.']);$pp=$dir.'/prova_'.wp_generate_uuid4().'.'.pathinfo($_FILES['proof_document']['name'],PATHINFO_EXTENSION);if(!move_uploaded_file($_FILES['proof_document']['tmp_name'],$pp)){@unlink($idp);wp_send_json_error(['message'=>'Erro upload prova.']);}}
    global $wpdb;$t=$wpdb->prefix.'imz_copyright_claims';$ins=$wpdb->insert($t,['post_id'=>$pid,'claim_level'=>$lvl,'claimant_name'=>$cn,'claimant_email'=>$ce,'representative_name'=>$rn,'representative_email'=>$re,'claim_type'=>$ct,'description'=>$desc,'original_work_url'=>$ourl,'id_document_path'=>$idp,'proof_document_path'=>$pp,'declaration_accepted'=>($lvl==2&&!empty($_POST['declaration_accepted']))?1:0,'status'=>'pendente','reporter_ip'=>$ip,'claim_date'=>current_time('mysql')]);
    if($ins){set_transient($tk,true,300);if($lvl==2){$mt=get_the_title($pid)?:'#'.$pid;$sn=get_bloginfo('name');$ae=get_option('admin_email');$au=admin_url('edit.php?post_type=impulsionamento&page=imz_copyright_manager&view='.$wpdb->insert_id);$ctl=['gravacao'=>'Gravação','composicao'=>'Composição','disponibilizacao'=>'Disponibilização','ambos'=>'Grav.+Disp.'];$ab=sprintf('<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body style="margin:0;padding:0;background:#000;font-family:-apple-system,sans-serif;"><table width="100%%" cellpadding="0" cellspacing="0" style="background:#000;padding:40px 16px;"><tr><td align="center"><table width="100%%" cellpadding="0" cellspacing="0" style="max-width:560px;"><tr><td style="padding-bottom:28px;text-align:center;"><span style="font-size:22px;font-weight:800;color:#fff;">%s</span></td></tr><tr><td style="background:#141414;border:1px solid #2a2a2a;border-radius:12px;overflow:hidden;"><div style="height:3px;background:#ef4444;"></div><div style="padding:36px 32px;"><div style="text-align:center;margin-bottom:24px;"><div style="display:inline-block;width:56px;height:56px;background:#1f0a0a;border:1px solid #ef4444;border-radius:50%%;line-height:56px;font-size:24px;color:#ef4444;">&#9888;</div></div><h1 style="margin:0 0 8px;font-size:20px;font-weight:700;color:#fff;text-align:center;">Reclamação NÍVEL 2</h1><p style="margin:0 0 28px;font-size:14px;color:#888;text-align:center;">Com documentação.</p><div style="background:#1a1a1a;border:1px solid #2a2a2a;border-radius:8px;padding:20px;"><p style="margin:0 0 10px;"><span style="font-size:11px;font-weight:700;text-transform:uppercase;color:#555;">Conteúdo:</span><br><span style="color:#fff;font-weight:600;">%s</span></p><p style="margin:0;"><span style="font-size:11px;font-weight:700;text-transform:uppercase;color:#555;">Reclamante:</span><br><span style="color:#ccc;">%s (%s) — %s</span></p></div><div style="text-align:center;margin-top:28px;"><a href="%s" style="display:inline-block;padding:14px 36px;background:#ef4444;color:#fff;text-decoration:none;font-weight:700;border-radius:6px;text-transform:uppercase;">Ver Reclamação</a></div></div></td></tr></table></td></tr></table></body></html>',esc_html($sn),esc_html($mt),esc_html($cn),esc_html($ce),esc_html($ctl[$ct]??$ct),esc_url($au));wp_mail($ae,'⚠ ['.$sn.'] Reclamação NÍVEL 2',$ab,['Content-Type: text/html; charset=UTF-8','From: '.$sn.' <'.$ae.'>']);}wp_send_json_success(['message'=>$lvl==2?'Reclamação formal submetida. Administração notificada.':'Reclamação registada.']);}else{if(!empty($idp)&&file_exists($idp))@unlink($idp);if(!empty($pp)&&file_exists($pp))@unlink($pp);wp_send_json_error(['message'=>'Erro.']);}
}
