<?php

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


function tilfy_diag_uri_temizle( $uri ) {
	$uri = (string) $uri;
	if ( $uri === '' ) {
		return '';
	}
	return preg_replace( '/([?&])(token|sig|jeton|password|secret|access_token)=([^&]*)/i', '$1$2=***', $uri );
}

function tilfy_diag_log_dosya_yolu() {
	$dir = function_exists( 'tilfy_log_klasor_yolu' ) ? tilfy_log_klasor_yolu() : '';
	if ( $dir === '' ) {
		$upload = function_exists( 'tilfy_wp_upload_dir_ham' ) ? tilfy_wp_upload_dir_ham() : wp_upload_dir();
		if ( ! empty( $upload['error'] ) || empty( $upload['basedir'] ) ) {
			return '';
		}
		$dir = trailingslashit( $upload['basedir'] ) . 'tilfy';
		if ( ! is_dir( $dir ) ) {
			wp_mkdir_p( $dir );
		}
	}
	if ( $dir === '' || ! is_dir( $dir ) ) {
		return '';
	}
	return trailingslashit( $dir ) . 'diag.log';
}

function tilfy_diag_analiz_aktif_mi() {
	return get_option( 'tilfy_diag_analiz', '0' ) === '1';
}

function tilfy_diag_bellek_mb() {
	return round( memory_get_usage( true ) / 1048576, 1 );
}

function tilfy_diag_bellek_peak_mb() {
	return round( memory_get_peak_usage( true ) / 1048576, 1 );
}

function tilfy_diag_kaynak_topla() {
	global $wpdb;

	$aktif = (array) get_option( 'active_plugins', array() );
	$mu    = function_exists( 'get_mu_plugins' ) ? array_keys( get_mu_plugins() ) : array();
	$tema  = '';
	if ( function_exists( 'wp_get_theme' ) ) {
		$t = wp_get_theme();
		$tema = (string) $t->get( 'Name' ) . ' (' . (string) $t->get_stylesheet() . ')';
	}

	return array(
		'mem_mb'             => tilfy_diag_bellek_mb(),
		'peak_mb'            => tilfy_diag_bellek_peak_mb(),
		'ob_level'           => function_exists( 'ob_get_level' ) ? (int) ob_get_level() : 0,
		'output_buffering'   => (string) ini_get( 'output_buffering' ),
		'included_files'     => function_exists( 'get_included_files' ) ? count( get_included_files() ) : 0,
		'db_queries'         => isset( $wpdb ) && is_object( $wpdb ) ? (int) $wpdb->num_queries : 0,
		'http_calls'         => isset( $GLOBALS['tilfy_diag_http_sayac'] ) ? (int) $GLOBALS['tilfy_diag_http_sayac'] : 0,
		'plugins_n'          => count( $aktif ),
		'plugins'            => array_values( array_slice( $aktif, 0, 50 ) ),
		'mu_plugins_n'       => count( $mu ),
		'mu_plugins'         => array_values( array_slice( $mu, 0, 20 ) ),
		'theme'              => $tema,
		'hooks_n'            => isset( $GLOBALS['wp_filter'] ) && is_array( $GLOBALS['wp_filter'] ) ? count( $GLOBALS['wp_filter'] ) : 0,
		'wp_memory_limit'    => defined( 'WP_MEMORY_LIMIT' ) ? (string) WP_MEMORY_LIMIT : '',
		'wp_max_memory_limit' => defined( 'WP_MAX_MEMORY_LIMIT' ) ? (string) WP_MAX_MEMORY_LIMIT : '',
	);
}

function tilfy_diag_kaynak_delta( $bas, $son ) {
	if ( ! is_array( $bas ) || ! is_array( $son ) ) {
		return array();
	}
	return array(
		'mem_mb'         => round( (float) ( $son['mem_mb'] ?? 0 ) - (float) ( $bas['mem_mb'] ?? 0 ), 1 ),
		'peak_mb'        => round( (float) ( $son['peak_mb'] ?? 0 ) - (float) ( $bas['peak_mb'] ?? 0 ), 1 ),
		'db_queries'     => (int) ( $son['db_queries'] ?? 0 ) - (int) ( $bas['db_queries'] ?? 0 ),
		'http_calls'     => (int) ( $son['http_calls'] ?? 0 ) - (int) ( $bas['http_calls'] ?? 0 ),
		'included_files' => (int) ( $son['included_files'] ?? 0 ) - (int) ( $bas['included_files'] ?? 0 ),
	);
}

function tilfy_diag_bellek_snapshot( $etiket, $ekstra = array() ) {
	if ( ! tilfy_diag_analiz_aktif_mi() ) {
		return;
	}
	$etiket = sanitize_key( (string) $etiket );
	if ( $etiket === '' ) {
		return;
	}
	$kaynak = tilfy_diag_kaynak_topla();
	$veri   = array(
		'etiket' => $etiket,
		'kaynak' => $kaynak,
	);
	if ( is_array( $ekstra ) && ! empty( $ekstra ) ) {
		$veri['ek'] = $ekstra;
	}
	tilfy_diag_log_yaz(
		'KAYNAK',
		'snapshot ' . $etiket . ' ' . wp_json_encode( $veri, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES ),
		is_array( $ekstra ) ? $ekstra : array()
	);
}

function tilfy_diag_shutdown_sorgular() {
	global $wpdb;

	if ( ! defined( 'SAVEQUERIES' ) || ! SAVEQUERIES || ! isset( $wpdb ) || ! is_object( $wpdb ) || empty( $wpdb->queries ) || ! is_array( $wpdb->queries ) ) {
		return;
	}
	$sorgular = $wpdb->queries;
	usort(
		$sorgular,
		static function ( $a, $b ) {
			return (float) ( $b[1] ?? 0 ) <=> (float) ( $a[1] ?? 0 );
		}
	);
	$ust = array_slice( $sorgular, 0, 5 );
	$liste = array();
	foreach ( $ust as $satir ) {
		$sorgu  = isset( $satir[0] ) ? preg_replace( '/\s+/', ' ', substr( (string) $satir[0], 0, 180 ) ) : '';
		$sure   = isset( $satir[1] ) ? round( (float) $satir[1], 4 ) : 0;
		$caller = isset( $satir[2] ) ? (string) $satir[2] : '';
		$liste[] = array(
			'sure_s' => $sure,
			'caller' => substr( $caller, 0, 220 ),
			'sorgu'  => $sorgu,
		);
	}
	if ( empty( $liste ) ) {
		return;
	}
	tilfy_diag_log_yaz(
		'DB',
		'yavas_sorgular ' . wp_json_encode( $liste, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES ),
		array()
	);
}

function tilfy_diag_sunucu_ozet() {
	$ini = array(
		'sapi'                 => PHP_SAPI,
		'php'                  => PHP_VERSION,
		'max_execution_time'   => (string) ini_get( 'max_execution_time' ),
		'memory_limit'         => (string) ini_get( 'memory_limit' ),
		'max_input_time'       => (string) ini_get( 'max_input_time' ),
		'default_socket_timeout' => (string) ini_get( 'default_socket_timeout' ),
		'upload_max_filesize'  => (string) ini_get( 'upload_max_filesize' ),
		'post_max_size'        => (string) ini_get( 'post_max_size' ),
		'allow_url_fopen'      => ini_get( 'allow_url_fopen' ) ? '1' : '0',
		'disable_functions'    => substr( (string) ini_get( 'disable_functions' ), 0, 200 ),
	);
	$srv = array(
		'software'    => isset( $_SERVER['SERVER_SOFTWARE'] ) ? sanitize_text_field( wp_unslash( $_SERVER['SERVER_SOFTWARE'] ) ) : '',
		'request_uri' => tilfy_diag_uri_temizle( isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '' ),
		'method'      => isset( $_SERVER['REQUEST_METHOD'] ) ? sanitize_key( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) : '',
		'remote_addr' => isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '',
	);
	if ( function_exists( 'wp_convert_hr_to_bytes' ) ) {
		$ini['wp_memory_limit'] = (string) WP_MEMORY_LIMIT;
	}
	return array(
		'ini'     => $ini,
		'server'  => $srv,
		'wp_cron' => wp_doing_cron() ? '1' : '0',
		'ajax'    => wp_doing_ajax() ? '1' : '0',
		'admin'   => is_admin() ? '1' : '0',
		'cli'     => ( defined( 'WP_CLI' ) && WP_CLI ) ? '1' : '0',
	);
}

function tilfy_diag_log_yaz( $kat, $mesaj, $ekstra = array() ) {
	if ( ! tilfy_diag_analiz_aktif_mi() ) {
		return;
	}
	tilfy_diag_log_yaz_zorla( $kat, $mesaj, $ekstra );
}

function tilfy_diag_log_yaz_zorla( $kat, $mesaj, $ekstra = array() ) {
	$kat    = sanitize_key( (string) $kat );
	$mesaj  = trim( (string) $mesaj );
	if ( $mesaj === '' ) {
		return;
	}
	$ekstra = is_array( $ekstra ) ? $ekstra : array();
	$parcalar = array(
		gmdate( 'Y-m-d H:i:s' ),
		$kat,
		'mem=' . tilfy_diag_bellek_mb() . 'MB',
		'peak=' . tilfy_diag_bellek_peak_mb() . 'MB',
	);
	if ( ! empty( $ekstra['platform'] ) ) {
		$parcalar[] = sanitize_key( (string) $ekstra['platform'] );
	}
	if ( ! empty( $ekstra['paylasim_id'] ) ) {
		$parcalar[] = 'paylasim#' . (int) $ekstra['paylasim_id'];
	}
	if ( ! empty( $ekstra['icerik_id'] ) ) {
		$parcalar[] = 'icerik#' . (int) $ekstra['icerik_id'];
	}
	if ( ! empty( $ekstra['kuyruk_id'] ) ) {
		$parcalar[] = 'kuyruk#' . (int) $ekstra['kuyruk_id'];
	}
	if ( ! empty( $ekstra['sure'] ) ) {
		$parcalar[] = 'sure=' . (string) $ekstra['sure'];
	}
	if ( ! empty( $ekstra['http'] ) ) {
		$parcalar[] = 'http=' . (int) $ekstra['http'];
	}
	$parcalar[] = $mesaj;
	$satir = implode( ' | ', $parcalar ) . "\n";
	$dosya = tilfy_diag_log_dosya_yolu();
	if ( $dosya === '' ) {
		return;
	}
	$dir = dirname( $dosya );
	if ( ! is_dir( $dir ) ) {
		wp_mkdir_p( $dir );
	}
	if ( ! file_exists( $dosya ) ) {
		@touch( $dosya );
	}
	@file_put_contents( $dosya, $satir, FILE_APPEND | LOCK_EX );
}

function tilfy_diag_analiz_baslat() {
	update_option( 'tilfy_diag_analiz', '1', false );
	update_option( 'tilfy_diag_analiz_baslangic', time(), false );
	$ozet = tilfy_diag_sunucu_ozet();
	tilfy_diag_log_yaz_zorla(
		'SESSION',
		'=== Analiz basladi === ' . wp_json_encode( $ozet, JSON_UNESCAPED_UNICODE ),
		array()
	);
	tilfy_diag_log_kancalar_kaydet();
	return true;
}

function tilfy_diag_analiz_durdur() {
	tilfy_diag_log_yaz_zorla(
		'SESSION',
		'=== Analiz durduruldu === peak=' . tilfy_diag_bellek_peak_mb() . 'MB',
		array()
	);
	update_option( 'tilfy_diag_analiz', '0', false );
	delete_option( 'tilfy_diag_analiz_baslangic' );
	return true;
}

function tilfy_diag_log_dosya_bilgi() {
	$dosya = tilfy_diag_log_dosya_yolu();
	if ( ! is_file( $dosya ) ) {
		return array(
			'var'    => false,
			'boyut'  => 0,
			'satir'  => 0,
			'yol'    => $dosya,
		);
	}
	$satir = 0;
	$fh    = @fopen( $dosya, 'rb' );
	if ( $fh ) {
		while ( ! feof( $fh ) ) {
			$chunk = fread( $fh, 8192 );
			if ( $chunk === false ) {
				break;
			}
			$satir += substr_count( $chunk, "\n" );
		}
		fclose( $fh );
	}
	return array(
		'var'   => true,
		'boyut' => (int) filesize( $dosya ),
		'satir' => $satir,
		'yol'   => $dosya,
	);
}

function tilfy_diag_istek_baglam() {
	$parcalar = array();
	if ( wp_doing_cron() ) {
		$parcalar[] = 'cron';
	}
	if ( wp_doing_ajax() ) {
		$action = isset( $_REQUEST['action'] ) ? sanitize_key( wp_unslash( $_REQUEST['action'] ) ) : '';
		$parcalar[] = 'ajax' . ( $action !== '' ? ':' . $action : '' );
	}
	if ( is_admin() ) {
		$page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : '';
		$parcalar[] = 'admin' . ( $page !== '' ? ':' . $page : '' );
	}
	if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
		$parcalar[] = 'rest';
	}
	if ( empty( $parcalar ) ) {
		$parcalar[] = 'front';
	}
	return implode( ',', $parcalar );
}

function tilfy_diag_request_basla() {
	if ( ! tilfy_diag_analiz_aktif_mi() ) {
		return;
	}
	$GLOBALS['tilfy_diag_istek_basla'] = microtime( true );
	$GLOBALS['tilfy_diag_http_sayac']  = 0;
	$GLOBALS['tilfy_diag_kaynak_bas']  = tilfy_diag_kaynak_topla();
	tilfy_diag_log_yaz(
		'REQUEST',
		'Basladi ' . tilfy_diag_istek_baglam() . ' uri=' . tilfy_diag_uri_temizle( isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '' ),
		array()
	);
	tilfy_diag_bellek_snapshot( 'istek_basla' );
}

function tilfy_diag_http_args( $args, $url ) {
	if ( ! tilfy_diag_analiz_aktif_mi() ) {
		return $args;
	}
	$anahtar = md5( (string) $url . microtime( true ) . wp_rand() );
	if ( ! isset( $GLOBALS['tilfy_diag_http'] ) || ! is_array( $GLOBALS['tilfy_diag_http'] ) ) {
		$GLOBALS['tilfy_diag_http'] = array();
	}
	$GLOBALS['tilfy_diag_http'][ $anahtar ] = array(
		'url'     => (string) $url,
		'basla'   => microtime( true ),
		'method'  => (string) ( $args['method'] ?? 'GET' ),
		'timeout' => (int) ( $args['timeout'] ?? 5 ),
	);
	$args['_tilfy_diag_http_key'] = $anahtar;
	if ( ! isset( $GLOBALS['tilfy_diag_http_sayac'] ) ) {
		$GLOBALS['tilfy_diag_http_sayac'] = 0;
	}
	++$GLOBALS['tilfy_diag_http_sayac'];
	$host = wp_parse_url( (string) $url, PHP_URL_HOST );
	tilfy_diag_log_yaz(
		'HTTP_OUT',
		'-> ' . (string) ( $args['method'] ?? 'GET' ) . ' host=' . ( is_string( $host ) ? $host : '?' ) . ' timeout=' . (int) ( $args['timeout'] ?? 5 ),
		array()
	);
	return $args;
}

function tilfy_diag_http_response( $response, $args, $url ) {
	if ( ! tilfy_diag_analiz_aktif_mi() ) {
		return $response;
	}
	$anahtar = (string) ( $args['_tilfy_diag_http_key'] ?? '' );
	$sure    = '';
	if ( $anahtar !== '' && ! empty( $GLOBALS['tilfy_diag_http'][ $anahtar ]['basla'] ) ) {
		$sure = round( microtime( true ) - (float) $GLOBALS['tilfy_diag_http'][ $anahtar ]['basla'], 3 ) . 's';
		unset( $GLOBALS['tilfy_diag_http'][ $anahtar ] );
	}
	$http = 0;
	$mesaj = '';
	if ( is_wp_error( $response ) ) {
		$mesaj = $response->get_error_code() . ': ' . $response->get_error_message();
	} else {
		$http  = (int) wp_remote_retrieve_response_code( $response );
		$len   = wp_remote_retrieve_header( $response, 'content-length' );
		$type  = wp_remote_retrieve_header( $response, 'content-type' );
		$mesaj = 'code=' . $http . ' len=' . ( $len !== '' ? $len : '?' ) . ' type=' . ( $type !== '' ? $type : '?' );
	}
	$host = wp_parse_url( (string) $url, PHP_URL_HOST );
	tilfy_diag_log_yaz(
		'HTTP_IN',
		'<- host=' . ( is_string( $host ) ? $host : '?' ) . ' ' . $mesaj,
		array(
			'sure' => $sure,
			'http' => $http,
		)
	);
	return $response;
}

function tilfy_diag_error_handler( $errno, $errstr, $errfile, $errline ) {
	if ( ! tilfy_diag_analiz_aktif_mi() ) {
		return false;
	}
	if ( ! ( error_reporting() & $errno ) ) {
		return false;
	}
	tilfy_diag_log_yaz(
		'PHP',
		'[' . (int) $errno . '] ' . $errstr . ' @ ' . basename( (string) $errfile ) . ':' . (int) $errline,
		array()
	);
	return false;
}

function tilfy_diag_shutdown() {
	if ( ! tilfy_diag_analiz_aktif_mi() ) {
		return;
	}
	$sure = '';
	if ( ! empty( $GLOBALS['tilfy_diag_istek_basla'] ) ) {
		$sure = round( microtime( true ) - (float) $GLOBALS['tilfy_diag_istek_basla'], 3 ) . 's';
	}
	$err = error_get_last();
	$ek  = array(
		'aborted=' . ( function_exists( 'connection_aborted' ) && connection_aborted() ? '1' : '0' ),
		'status=' . ( function_exists( 'connection_status' ) ? (string) connection_status() : '?' ),
		'headers_sent=' . ( headers_sent() ? '1' : '0' ),
		'medya_indiriyor=' . ( ! empty( $GLOBALS['tilfy_medya_indiriyor'] ) ? '1' : '0' ),
	);
	if ( $err ) {
		$ek[] = 'last_error=[' . (int) $err['type'] . '] ' . (string) ( $err['message'] ?? '' ) . ' @ ' . basename( (string) ( $err['file'] ?? '' ) ) . ':' . (int) ( $err['line'] ?? 0 );
	}
	if ( ! empty( $GLOBALS['tilfy_medya_indirme_izle'] ) && is_array( $GLOBALS['tilfy_medya_indirme_izle'] ) ) {
		$iz = $GLOBALS['tilfy_medya_indirme_izle'];
		$ek[] = 'medya_izle=' . wp_json_encode(
			array(
				'kuyruk_id'   => (int) ( $iz['kuyruk_id'] ?? 0 ),
				'icerik_id'   => (int) ( $iz['icerik_id'] ?? 0 ),
				'basladi'     => ! empty( $iz['basladi'] ),
				'tamamlandi'  => ! empty( $iz['tamamlandi'] ),
			)
		);
	}
	$son_kaynak = tilfy_diag_kaynak_topla();
	$bas_kaynak = ! empty( $GLOBALS['tilfy_diag_kaynak_bas'] ) && is_array( $GLOBALS['tilfy_diag_kaynak_bas'] ) ? $GLOBALS['tilfy_diag_kaynak_bas'] : null;
	$delta      = tilfy_diag_kaynak_delta( $bas_kaynak, $son_kaynak );
	tilfy_diag_shutdown_sorgular();
	tilfy_diag_log_yaz(
		'KAYNAK',
		'shutdown ' . wp_json_encode(
			array(
				'son'   => $son_kaynak,
				'delta' => $delta,
			),
			JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
		),
		array( 'sure' => $sure )
	);
	tilfy_diag_log_yaz(
		'SHUTDOWN',
		'Istek bitti ' . tilfy_diag_istek_baglam() . ' ' . implode( ' ', $ek ),
		array( 'sure' => $sure )
	);
}

function tilfy_diag_medya_indir_sonuc( $icerik_id, $tmp, $sure ) {
	$icerik_id = (int) $icerik_id;
	$sure      = round( (float) $sure, 3 );
	if ( is_wp_error( $tmp ) ) {
		tilfy_diag_log_yaz(
			'MEDYA',
			'indir FAIL sure=' . $sure . 's code=' . $tmp->get_error_code() . ' msg=' . $tmp->get_error_message(),
			array( 'icerik_id' => $icerik_id )
		);
		return;
	}
	$boyut = is_string( $tmp ) && file_exists( $tmp ) ? (int) filesize( $tmp ) : 0;
	tilfy_diag_log_yaz(
		'MEDYA',
		'indir OK sure=' . $sure . 's size=' . $boyut . ' tmp=' . (string) $tmp,
		array( 'icerik_id' => $icerik_id )
	);
}

function tilfy_diag_kuyruk_calistir( $olay ) {
	tilfy_diag_log_yaz( 'KUYRUK', 'kuyruk_calistir ' . $olay, array() );
}

function tilfy_diag_log_kancalar_kaydet() {
	static $kayitli = false;
	if ( $kayitli ) {
		return;
	}
	$kayitli = true;
	if ( did_action( 'init' ) ) {
		tilfy_diag_request_basla();
	} else {
		add_action( 'init', 'tilfy_diag_request_basla', 0 );
	}
	add_filter( 'http_request_args', 'tilfy_diag_http_args', 9999, 2 );
	add_filter( 'http_response', 'tilfy_diag_http_response', 9999, 3 );
	add_action( 'shutdown', 'tilfy_diag_shutdown', 0 );
	set_error_handler( 'tilfy_diag_error_handler' );
}

if ( tilfy_diag_analiz_aktif_mi() ) {
	tilfy_diag_log_kancalar_kaydet();
}
