<?php
/**
 * Mini CRM — thu thập & đánh giá Lead từ form, có truy vết nguồn (attribution).
 * Nối kết quả SEO → khách hàng thật. Require từ seo-console.php.
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

define( 'TTSEO_CRM_DBVER', '1' );

/* =========================================================================
 * BẢNG LEAD
 * ========================================================================= */
function ttseo_leads_table() {
	global $wpdb;
	return $wpdb->prefix . 'ttseo_leads';
}
function ttseo_crm_install() {
	if ( get_option( 'ttseo_crm_dbver' ) === TTSEO_CRM_DBVER ) {
		return;
	}
	global $wpdb;
	$table   = ttseo_leads_table();
	$charset = $wpdb->get_charset_collate();
	require_once ABSPATH . 'wp-admin/includes/upgrade.php';
	dbDelta( "CREATE TABLE $table (
		id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
		name VARCHAR(190) NOT NULL DEFAULT '',
		email VARCHAR(190) NOT NULL DEFAULT '',
		phone VARCHAR(60) NOT NULL DEFAULT '',
		message TEXT NULL,
		form_page VARCHAR(255) NOT NULL DEFAULT '',
		landing_page VARCHAR(255) NOT NULL DEFAULT '',
		referrer VARCHAR(255) NOT NULL DEFAULT '',
		channel VARCHAR(40) NOT NULL DEFAULT '',
		utm_source VARCHAR(100) NOT NULL DEFAULT '',
		utm_medium VARCHAR(100) NOT NULL DEFAULT '',
		utm_campaign VARCHAR(100) NOT NULL DEFAULT '',
		status VARCHAR(20) NOT NULL DEFAULT 'new',
		quality VARCHAR(20) NOT NULL DEFAULT '',
		notes TEXT NULL,
		created_at DATETIME NOT NULL DEFAULT '1970-01-01 00:00:00',
		updated_at DATETIME NOT NULL DEFAULT '1970-01-01 00:00:00',
		PRIMARY KEY (id),
		KEY status (status),
		KEY created_at (created_at)
	) $charset;" );
	update_option( 'ttseo_crm_dbver', TTSEO_CRM_DBVER );
}
add_action( 'admin_init', 'ttseo_crm_install' );

function ttseo_lead_statuses() {
	return array(
		'new'       => ttseo_t( 'Mới', 'New' ),
		'contacted' => ttseo_t( 'Đã liên hệ', 'Contacted' ),
		'qualified' => ttseo_t( 'Tiềm năng', 'Qualified' ),
		'proposal'  => ttseo_t( 'Đã báo giá', 'Proposal sent' ),
		'won'       => ttseo_t( 'Thành công', 'Won' ),
		'lost'      => ttseo_t( 'Không đạt', 'Lost' ),
	);
}
function ttseo_lead_qualities() {
	return array( 'hot' => '🔥 ' . ttseo_t( 'Nóng', 'Hot' ), 'warm' => '🌤 ' . ttseo_t( 'Ấm', 'Warm' ), 'cold' => '❄️ ' . ttseo_t( 'Lạnh', 'Cold' ) );
}
function ttseo_lead_status_color( $s ) {
	$m = array( 'new' => '#1f5c93', 'contacted' => '#c77d16', 'qualified' => '#6b3fb5', 'proposal' => '#b96712', 'won' => '#1a7f5a', 'lost' => '#c0392b' );
	return $m[ $s ] ?? '#8a8f94';
}

/* =========================================================================
 * ATTRIBUTION — cookie first-touch (trang đích đầu tiên + nguồn + UTM)
 * ========================================================================= */
add_action( 'wp_footer', function () {
	if ( is_admin() ) {
		return;
	}
	?>
	<script>
	(function(){
	  try{
	    if(document.cookie.indexOf('ttseo_attr=')!==-1) return;
	    var p=new URLSearchParams(location.search);
	    var d={l:location.pathname.substring(0,180),r:(document.referrer||'').substring(0,180),
	           s:(p.get('utm_source')||'').substring(0,60),m:(p.get('utm_medium')||'').substring(0,60),c:(p.get('utm_campaign')||'').substring(0,60)};
	    document.cookie='ttseo_attr='+encodeURIComponent(JSON.stringify(d))+';path=/;max-age=7776000;SameSite=Lax';
	  }catch(e){}
	})();
	</script>
	<?php
}, 99 );

/** Suy ra kênh từ referrer + utm */
function ttseo_detect_channel( $referrer, $utm_source, $utm_medium ) {
	if ( $utm_medium ) {
		return strtolower( $utm_medium );
	}
	if ( ! $referrer ) {
		return 'direct';
	}
	$host = strtolower( (string) wp_parse_url( $referrer, PHP_URL_HOST ) );
	if ( ! $host ) {
		return 'direct';
	}
	$se = array( 'google' => 'organic-google', 'bing' => 'organic-bing', 'yahoo' => 'organic-yahoo', 'duckduckgo' => 'organic-ddg', 'yandex' => 'organic-yandex', 'baidu' => 'organic-baidu' );
	foreach ( $se as $needle => $ch ) {
		if ( false !== strpos( $host, $needle ) ) {
			return $ch;
		}
	}
	$soc = array( 'facebook', 'linkedin', 'instagram', 'youtube', 'pinterest', 'tiktok', 'zalo', 't.co', 'twitter' );
	foreach ( $soc as $needle ) {
		if ( false !== strpos( $host, $needle ) ) {
			return 'social-' . str_replace( '.co', '', $needle );
		}
	}
	if ( false !== strpos( $host, wp_parse_url( home_url(), PHP_URL_HOST ) ) ) {
		return 'internal';
	}
	return 'referral';
}

/** Ghi 1 lead */
function ttseo_save_lead( $fields, $form_page ) {
	global $wpdb;
	$attr = array();
	if ( ! empty( $_COOKIE['ttseo_attr'] ) ) {
		$attr = json_decode( wp_unslash( $_COOKIE['ttseo_attr'] ), true );
		$attr = is_array( $attr ) ? $attr : array();
	}
	$referrer = (string) ( $attr['r'] ?? '' );
	$utm_s    = (string) ( $attr['s'] ?? '' );
	$utm_m    = (string) ( $attr['m'] ?? '' );
	$now      = current_time( 'mysql' );

	$wpdb->insert( ttseo_leads_table(), array(
		'name'         => sanitize_text_field( $fields['name'] ?? '' ),
		'email'        => sanitize_email( $fields['email'] ?? '' ),
		'phone'        => sanitize_text_field( $fields['phone'] ?? '' ),
		'message'      => sanitize_textarea_field( $fields['message'] ?? '' ),
		'form_page'    => esc_url_raw( $form_page ),
		'landing_page' => sanitize_text_field( (string) ( $attr['l'] ?? '' ) ),
		'referrer'     => esc_url_raw( $referrer ),
		'channel'      => ttseo_detect_channel( $referrer, $utm_s, $utm_m ),
		'utm_source'   => sanitize_text_field( $utm_s ),
		'utm_medium'   => sanitize_text_field( $utm_m ),
		'utm_campaign' => sanitize_text_field( (string) ( $attr['c'] ?? '' ) ),
		'status'       => 'new',
		'created_at'   => $now,
		'updated_at'   => $now,
	) );
}

/* =========================================================================
 * HOOK: Contact Form 7
 * ========================================================================= */
add_action( 'wpcf7_mail_sent', function ( $contact_form ) {
	if ( ! class_exists( 'WPCF7_Submission' ) ) {
		return;
	}
	$submission = WPCF7_Submission::get_instance();
	if ( ! $submission ) {
		return;
	}
	$data = $submission->get_posted_data();
	$get  = function ( $needles ) use ( $data ) {
		foreach ( $data as $k => $v ) {
			foreach ( (array) $needles as $n ) {
				if ( false !== stripos( $k, $n ) ) {
					return is_array( $v ) ? implode( ', ', $v ) : (string) $v;
				}
			}
		}
		return '';
	};
	ttseo_save_lead( array(
		'name'    => $get( array( 'name' ) ),
		'email'   => $get( array( 'email' ) ),
		'phone'   => $get( array( 'phone', 'tel' ) ),
		'message' => $get( array( 'message', 'request', 'content', 'textarea' ) ),
	), (string) $submission->get_meta( 'url' ) );
} );

/* =========================================================================
 * HOOK: WPForms (nếu sau này tạo form)
 * ========================================================================= */
add_action( 'wpforms_process_complete', function ( $fields, $entry, $form_data ) {
	$out = array( 'name' => '', 'email' => '', 'phone' => '', 'message' => '' );
	foreach ( (array) $fields as $f ) {
		$type = $f['type'] ?? '';
		$val  = is_array( $f['value'] ?? '' ) ? implode( ', ', $f['value'] ) : (string) ( $f['value'] ?? '' );
		if ( 'email' === $type && ! $out['email'] ) { $out['email'] = $val; }
		elseif ( 'phone' === $type && ! $out['phone'] ) { $out['phone'] = $val; }
		elseif ( 'name' === $type && ! $out['name'] ) { $out['name'] = $val; }
		elseif ( 'textarea' === $type && ! $out['message'] ) { $out['message'] = $val; }
	}
	ttseo_save_lead( $out, wp_get_referer() ?: home_url( '/' ) );
}, 10, 3 );

/* =========================================================================
 * MENU + CRUD
 * ========================================================================= */
add_action( 'admin_menu', function () {
	$count = ttseo_lead_count_new();
	$badge = $count ? ' <span class="update-plugins count-' . $count . '"><span class="plugin-count">' . $count . '</span></span>' : '';
	if ( ttseo_module_on( 'crm' ) ) {
		add_submenu_page( 'ttseo-dashboard', ttseo_t( 'Lead & CRM', 'Leads & CRM' ), ttseo_t( 'Lead & CRM', 'Leads & CRM' ) . $badge, 'ttseo_access', 'ttseo-crm', 'ttseo_render_crm' );
	}
}, 40 );

function ttseo_lead_count_new() {
	global $wpdb;
	$t = ttseo_leads_table();
	if ( $wpdb->get_var( "SHOW TABLES LIKE '$t'" ) !== $t ) {
		return 0;
	}
	return (int) $wpdb->get_var( "SELECT COUNT(*) FROM $t WHERE status='new'" );
}

add_action( 'admin_init', function () {
	if ( ! ttseo_access() || ! function_exists( 'ttseo_is_unlocked' ) || ! ttseo_is_unlocked() ) {
		return;
	}
	global $wpdb;
	$t = ttseo_leads_table();

	if ( isset( $_GET['ttseo_lead_set'], $_GET['id'] ) ) {
		check_admin_referer( 'ttseo_lead_set' );
		$upd = array( 'updated_at' => current_time( 'mysql' ) );
		if ( isset( $_GET['status'] ) ) { $upd['status'] = sanitize_key( $_GET['status'] ); }
		if ( isset( $_GET['quality'] ) ) { $upd['quality'] = sanitize_key( $_GET['quality'] ); }
		$wpdb->update( $t, $upd, array( 'id' => (int) $_GET['id'] ) );
		wp_safe_redirect( admin_url( 'admin.php?page=ttseo-crm' ) );
		exit;
	}
	if ( isset( $_GET['ttseo_lead_del'], $_GET['id'] ) ) {
		check_admin_referer( 'ttseo_lead_del' );
		$wpdb->delete( $t, array( 'id' => (int) $_GET['id'] ) );
		wp_safe_redirect( admin_url( 'admin.php?page=ttseo-crm&deleted=1' ) );
		exit;
	}
	if ( isset( $_POST['ttseo_lead_note'], $_POST['id'] ) ) {
		check_admin_referer( 'ttseo_lead_note' );
		$wpdb->update( $t, array( 'notes' => sanitize_textarea_field( wp_unslash( $_POST['notes'] ?? '' ) ), 'updated_at' => current_time( 'mysql' ) ), array( 'id' => (int) $_POST['id'] ) );
		wp_safe_redirect( admin_url( 'admin.php?page=ttseo-crm' ) );
		exit;
	}
	// Xuất CSV
	if ( isset( $_GET['ttseo_lead_csv'] ) ) {
		check_admin_referer( 'ttseo_lead_csv' );
		$rows = $wpdb->get_results( "SELECT * FROM $t ORDER BY created_at DESC", ARRAY_A );
		header( 'Content-Type: text/csv; charset=utf-8' );
		header( 'Content-Disposition: attachment; filename=leads-' . gmdate( 'Y-m-d' ) . '.csv' );
		$out = fopen( 'php://output', 'w' );
		fwrite( $out, "\xEF\xBB\xBF" ); // BOM cho Excel
		if ( $rows ) {
			fputcsv( $out, array_keys( $rows[0] ) );
			foreach ( $rows as $r ) { fputcsv( $out, $r ); }
		}
		fclose( $out );
		exit;
	}
} );

/* =========================================================================
 * TRANG LEAD & CRM
 * ========================================================================= */
function ttseo_render_crm() {
	if ( function_exists( 'ttseo_is_unlocked' ) && ! ttseo_is_unlocked() ) { ttseo_render_gate(); return; }
	ttseo_styles();
	if ( ! ttseo_is_pro() ) {
		echo '<div class="wrap ttseo-wrap">'; ttseo_brand_header();
		ttseo_render_upgrade_notice( ttseo_t( 'Lead & CRM', 'Leads & CRM' ) );
		ttseo_brand_footer(); echo '</div>';
		return;
	}
	global $wpdb;
	$t     = ttseo_leads_table();
	$fs    = sanitize_key( $_GET['fs'] ?? 'all' );
	$where = 'all' === $fs ? '' : $wpdb->prepare( ' WHERE status=%s', $fs );
	$leads = $wpdb->get_results( "SELECT * FROM $t" . $where . ' ORDER BY created_at DESC LIMIT 300' );
	$all   = $wpdb->get_results( "SELECT status, quality, channel, form_page, landing_page, created_at FROM $t" );

	echo '<div class="wrap ttseo-wrap">';
	ttseo_brand_header();
	echo '<h1>👥 ' . esc_html( ttseo_t( 'Lead & CRM', 'Leads & CRM' ) ) . ' <a href="' . esc_url( wp_nonce_url( admin_url( 'admin.php?page=ttseo-crm&ttseo_lead_csv=1' ), 'ttseo_lead_csv' ) ) . '" class="button" style="margin-left:10px;">⬇ ' . esc_html( ttseo_t( 'Xuất CSV', 'Export CSV' ) ) . '</a></h1>';
	echo '<p class="ttseo-subtle" style="margin-left:0;">' . esc_html( ttseo_t( 'Mọi form gửi đi được lưu tự động kèm truy vết nguồn (trang đích đầu tiên, kênh, UTM) — nối kết quả SEO với khách hàng thật.', 'Every form submission is saved automatically with source attribution (first landing page, channel, UTM) — connecting SEO results to real customers.' ) ) . '</p>';
	if ( isset( $_GET['deleted'] ) ) { echo '<div class="notice notice-success is-dismissible"><p>' . esc_html( ttseo_t( 'Đã xóa lead.', 'Lead deleted.' ) ) . '</p></div>'; }

	// Thống kê
	$total = count( $all );
	$month = 0; $won = 0; $newc = 0;
	$by_status = array(); $by_channel = array(); $by_landing = array();
	$cm = gmdate( 'Y-m' );
	foreach ( $all as $l ) {
		if ( substr( $l->created_at, 0, 7 ) === $cm ) { $month++; }
		if ( 'won' === $l->status ) { $won++; }
		if ( 'new' === $l->status ) { $newc++; }
		$by_status[ $l->status ] = ( $by_status[ $l->status ] ?? 0 ) + 1;
		$ch = $l->channel ?: 'direct';
		$by_channel[ $ch ] = ( $by_channel[ $ch ] ?? 0 ) + 1;
		$lp = $l->landing_page ?: '/';
		$by_landing[ $lp ] = ( $by_landing[ $lp ] ?? 0 ) + 1;
	}
	$winrate = $total ? round( $won / $total * 100, 1 ) : 0;

	echo '<div class="ttseo-strip">';
	ttseo_kpi( ttseo_t( 'Tổng lead', 'Total leads' ), ttseo_num( $total ), ttseo_t( 'từ khi bật', 'since enabled' ), '#1f5c93' );
	ttseo_kpi( ttseo_t( 'Lead tháng này', 'Leads this month' ), ttseo_num( $month ), gmdate( 'm/Y' ), '#6b3fb5' );
	ttseo_kpi( ttseo_t( 'Chưa xử lý', 'Unprocessed' ), ttseo_num( $newc ), ttseo_t( 'cần liên hệ', 'needs contact' ), $newc ? '#c0392b' : '#1a7f5a' );
	ttseo_kpi( ttseo_t( 'Thành công', 'Won' ), ttseo_num( $won ), ttseo_t( 'đã chốt', 'closed' ), '#1a7f5a' );
	ttseo_kpi( ttseo_t( 'Tỷ lệ chốt', 'Win rate' ), $winrate . '%', 'won/' . ttseo_t( 'tổng', 'total' ), '#1a7f5a' );
	echo '</div>';

	if ( 0 === $total ) {
		echo '<div class="ttseo-ins opp" style="margin:14px 0;"><div class="ic">💡</div><div><div class="t">' . esc_html( ttseo_t( 'Chưa có lead nào được ghi — hệ thống vừa được bật', 'No leads recorded yet — the system was just enabled' ) ) . '</div><div class="d">' . esc_html( ttseo_t(
			'Từ giờ, mỗi lượt gửi form sẽ tự động lưu vào đây kèm nguồn truy cập. Lead cũ trước thời điểm này chỉ tồn tại trong email nên không khôi phục được.',
			'From now on, every form submission is saved here automatically with source data. Leads from before this point only exist in email and cannot be recovered.'
		) ) . '</div></div></div>';
	}

	// Phễu trạng thái
	if ( $total ) {
		echo '<h2 class="ttseo-sec" style="--b:#1f5c93;">' . esc_html( ttseo_t( 'Phễu bán hàng', 'Sales funnel' ) ) . '</h2><div class="ttseo-strip">';
		foreach ( ttseo_lead_statuses() as $k => $lab ) {
			$n = $by_status[ $k ] ?? 0;
			ttseo_kpi( $lab, ttseo_num( $n ), $total ? round( $n / $total * 100 ) . '%' : '', ttseo_lead_status_color( $k ) );
		}
		echo '</div>';

		// Nguồn & trang đích — nối SEO với lead
		echo '<h2 class="ttseo-sec" style="--b:#1a7f5a;">' . esc_html( ttseo_t( 'Lead theo kênh & trang đích (SEO → khách hàng)', 'Leads by channel & landing page (SEO → customer)' ) ) . '</h2>';
		echo '<div style="display:flex;gap:16px;flex-wrap:wrap;">';
		arsort( $by_channel ); arsort( $by_landing );
		echo '<div style="flex:1;min-width:280px;"><h3 style="margin-top:0;">' . esc_html( ttseo_t( 'Theo kênh', 'By channel' ) ) . '</h3><div class="ttseo-table"><table><thead><tr><th>' . esc_html( ttseo_t( 'Kênh', 'Channel' ) ) . '</th><th>' . esc_html( ttseo_t( 'Lead', 'Leads' ) ) . '</th><th>%</th></tr></thead><tbody>';
		foreach ( array_slice( $by_channel, 0, 10, true ) as $k => $n ) {
			echo '<tr><td>' . esc_html( $k ) . '</td><td>' . ttseo_num( $n ) . '</td><td>' . round( $n / $total * 100 ) . '%</td></tr>';
		}
		echo '</tbody></table></div></div>';
		echo '<div style="flex:1;min-width:280px;"><h3 style="margin-top:0;">' . esc_html( ttseo_t( 'Theo trang đích đầu tiên', 'By first landing page' ) ) . '</h3><div class="ttseo-table"><table><thead><tr><th>' . esc_html( ttseo_t( 'Trang', 'Page' ) ) . '</th><th>' . esc_html( ttseo_t( 'Lead', 'Leads' ) ) . '</th></tr></thead><tbody>';
		foreach ( array_slice( $by_landing, 0, 10, true ) as $k => $n ) {
			echo '<tr><td>' . esc_html( $k ) . '</td><td>' . ttseo_num( $n ) . '</td></tr>';
		}
		echo '</tbody></table></div></div>';
		echo '</div>';
	}

	// Bộ lọc
	echo '<h2 class="ttseo-sec" style="--b:#c77d16;">' . esc_html( ttseo_t( 'Danh sách lead', 'Lead list' ) ) . '</h2><p style="margin:0 0 10px 15px;">';
	$filters = array_merge( array( 'all' => ttseo_t( 'Tất cả', 'All' ) ), ttseo_lead_statuses() );
	foreach ( $filters as $k => $lab ) {
		$cls = $k === $fs ? 'button button-primary' : 'button';
		$n   = 'all' === $k ? $total : ( $by_status[ $k ] ?? 0 );
		echo '<a class="' . $cls . '" style="margin-right:5px;" href="' . esc_url( admin_url( 'admin.php?page=ttseo-crm&fs=' . $k ) ) . '">' . esc_html( $lab ) . ' (' . $n . ')</a>';
	}
	echo '</p>';

	if ( empty( $leads ) ) {
		echo '<p class="ttseo-subtle">' . esc_html( ttseo_t( 'Không có lead nào.', 'No leads.' ) ) . '</p>';
	} else {
		echo '<div class="ttseo-table" style="max-height:640px;overflow:auto;"><table><thead><tr><th>' . esc_html( ttseo_t( 'Ngày', 'Date' ) ) . '</th><th>' . esc_html( ttseo_t( 'Khách hàng', 'Customer' ) ) . '</th><th>' . esc_html( ttseo_t( 'Liên hệ', 'Contact' ) ) . '</th><th>' . esc_html( ttseo_t( 'Yêu cầu', 'Message' ) ) . '</th><th>' . esc_html( ttseo_t( 'Nguồn', 'Source' ) ) . '</th><th>' . esc_html( ttseo_t( 'Trạng thái', 'Status' ) ) . '</th><th>' . esc_html( ttseo_t( 'Chất lượng', 'Quality' ) ) . '</th><th></th></tr></thead><tbody>';
		foreach ( $leads as $l ) {
			$del = wp_nonce_url( admin_url( 'admin.php?page=ttseo-crm&ttseo_lead_del=1&id=' . $l->id ), 'ttseo_lead_del' );
			echo '<tr>';
			echo '<td style="white-space:nowrap;color:#646970;font-size:12px;">' . esc_html( mysql2date( 'd/m/y H:i', $l->created_at ) ) . '</td>';
			echo '<td><b>' . esc_html( $l->name ?: ttseo_t( '(không tên)', '(no name)' ) ) . '</b></td>';
			echo '<td style="font-size:12px;">' . ( $l->email ? '<a href="mailto:' . esc_attr( $l->email ) . '">' . esc_html( $l->email ) . '</a><br>' : '' ) . ( $l->phone ? '<a href="tel:' . esc_attr( $l->phone ) . '">' . esc_html( $l->phone ) . '</a>' : '' ) . '</td>';
			echo '<td style="max-width:260px;font-size:12px;color:#50575e;">' . esc_html( wp_trim_words( (string) $l->message, 18 ) ) . '</td>';
			echo '<td style="font-size:11px;"><b>' . esc_html( $l->channel ?: 'direct' ) . '</b><br><span style="color:#8a8f94;">' . esc_html( $l->landing_page ?: '—' ) . '</span></td>';
			// status
			echo '<td style="white-space:nowrap;">';
			$col = ttseo_lead_status_color( $l->status );
			echo '<span style="display:inline-block;font-size:11px;font-weight:700;color:' . $col . ';border:1px solid ' . $col . '33;background:' . $col . '14;border-radius:12px;padding:2px 9px;">' . esc_html( ttseo_lead_statuses()[ $l->status ] ?? $l->status ) . '</span><br>';
			foreach ( ttseo_lead_statuses() as $sk => $sl ) {
				if ( $sk === $l->status ) { continue; }
				$u = wp_nonce_url( admin_url( 'admin.php?page=ttseo-crm&ttseo_lead_set=1&id=' . $l->id . '&status=' . $sk ), 'ttseo_lead_set' );
				echo '<a href="' . esc_url( $u ) . '" style="font-size:10px;color:#646970;margin-right:4px;">' . esc_html( $sl ) . '</a>';
			}
			echo '</td>';
			// quality
			echo '<td style="white-space:nowrap;font-size:11px;">';
			foreach ( ttseo_lead_qualities() as $qk => $ql ) {
				$sel = $l->quality === $qk ? 'font-weight:700;' : 'opacity:.45;';
				$u   = wp_nonce_url( admin_url( 'admin.php?page=ttseo-crm&ttseo_lead_set=1&id=' . $l->id . '&quality=' . $qk ), 'ttseo_lead_set' );
				echo '<a href="' . esc_url( $u ) . '" style="' . $sel . 'display:block;text-decoration:none;">' . esc_html( $ql ) . '</a>';
			}
			echo '</td>';
			echo '<td><a href="' . esc_url( $del ) . '" onclick="return confirm(\'' . esc_js( ttseo_t( 'Xóa lead này?', 'Delete this lead?' ) ) . '\')" style="color:#c0392b;font-size:12px;">' . esc_html( ttseo_t( 'Xóa', 'Delete' ) ) . '</a></td>';
			echo '</tr>';
			if ( $l->notes ) {
				echo '<tr><td></td><td colspan="7" style="background:#fafbfc;font-size:12px;color:#50575e;border-top:none;">📝 ' . esc_html( $l->notes ) . '</td></tr>';
			}
		}
		echo '</tbody></table></div>';
	}

	ttseo_brand_footer();
	echo '</div>';
}
