<?php

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

function tilfy_wordpress_post_medya( $post_id ) {
	$post_id  = (int) $post_id;
	$thumb_id = (int) get_post_thumbnail_id( $post_id );
	$kapak    = '';
	if ( $thumb_id > 0 ) {
		$kapak = (string) wp_get_attachment_image_url( $thumb_id, 'large' );
		if ( $kapak === '' ) {
			$kapak = (string) wp_get_attachment_url( $thumb_id );
		}
	}
	return array(
		'kapak_url'  => esc_url_raw( $kapak ),
		'medya_url'  => esc_url_raw( $kapak ),
		'medya_tipi' => 'image',
	);
}

function tilfy_wordpress_aciklama_hazirla( $ham ) {
	$ham = (string) $ham;
	if ( $ham === '' ) {
		return '';
	}
	if ( function_exists( 'has_blocks' ) && has_blocks( $ham ) && function_exists( 'do_blocks' ) ) {
		$ham = do_blocks( $ham );
	}
	$ham = preg_replace( '/<!--[\s\S]*?-->/', '', $ham );
	$ham = preg_replace( '/<\/(p|div|h[1-6]|li|tr|blockquote)>/i', "\n", $ham );
	$ham = preg_replace( '/<(br|hr)\s*\/?>/i', "\n", $ham );
	$ham = preg_replace( '/<\/(ul|ol)>/i', "\n", $ham );
	$ham = wp_strip_all_tags( $ham );
	$ham = html_entity_decode( $ham, ENT_QUOTES | ENT_HTML5, 'UTF-8' );
	$ham = preg_replace( "/[ \t]+/u", ' ', $ham );
	$ham = preg_replace( "/\n[ \t]+/u", "\n", $ham );
	$ham = preg_replace( "/\n{3,}/u", "\n\n", $ham );
	return trim( $ham );
}

function tilfy_wordpress_post_veri( $post ) {
	if ( ! $post instanceof WP_Post ) {
		$post = get_post( $post );
	}
	if ( ! $post || $post->post_type !== 'post' ) {
		return null;
	}
	$medya = tilfy_wordpress_post_medya( (int) $post->ID );
	return array(
		'kaynak_platform' => 'wordpress',
		'kaynak_id'       => (string) $post->ID,
		'baslik'          => (string) $post->post_title,
		'aciklama'        => tilfy_wordpress_aciklama_hazirla( (string) $post->post_content ),
		'medya_tipi'      => $medya['medya_tipi'],
		'medya_url'       => $medya['medya_url'],
		'medya_dosya_id'  => 0,
		'kapak_url'       => $medya['kapak_url'],
		'kapak_dosya_id'  => 0,
		'kaynak_url'      => (string) get_permalink( $post ),
		'kaynak_tarihi'   => (string) ( $post->post_date_gmt && $post->post_date_gmt !== '0000-00-00 00:00:00' ? $post->post_date_gmt : $post->post_date ),
		'durum'           => 'senkron',
	);
}

function tilfy_wordpress_icerik_canli_yenile( $icerik ) {
	global $wpdb;
	if ( ! $icerik || sanitize_key( (string) ( $icerik->kaynak_platform ?? '' ) ) !== 'wordpress' ) {
		return $icerik;
	}
	$post_id = (int) ( $icerik->kaynak_id ?? 0 );
	if ( $post_id <= 0 ) {
		return $icerik;
	}
	$veri = tilfy_wordpress_post_veri( $post_id );
	if ( ! $veri ) {
		return $icerik;
	}
	$guncelle = array(
		'baslik'     => $veri['baslik'],
		'aciklama'   => wp_kses_post( $veri['aciklama'] ),
		'kaynak_url' => $veri['kaynak_url'],
		'guncelleme' => current_time( 'mysql' ),
	);
	if ( function_exists( 'tilfy_mysql_tarih_al' ) ) {
		$kt = tilfy_mysql_tarih_al( $veri['kaynak_tarihi'] );
		if ( $kt ) {
			$guncelle['kaynak_tarihi'] = $kt;
		}
	}
	$wpdb->update( tilfy_tablo( 'icerik' ), $guncelle, array( 'id' => (int) $icerik->id ) );
	$yenilenmis = $wpdb->get_row(
		$wpdb->prepare( 'SELECT * FROM ' . tilfy_tablo( 'icerik' ) . ' WHERE id = %d', (int) $icerik->id )
	);
	return $yenilenmis ? $yenilenmis : $icerik;
}

function tilfy_wordpress_icerikleri_cek( $opts = array() ) {
	if ( ! function_exists( 'tilfy_wordpress_kaynak_aktif_mi' ) || ! tilfy_wordpress_kaynak_aktif_mi() ) {
		return array( 'ok' => false, 'mesaj' => 'WordPress kaynagi kapali' );
	}
	$opts = is_array( $opts ) ? $opts : array();
	$mod  = ! empty( $opts['mod'] ) ? (string) $opts['mod'] : ( function_exists( 'tilfy_senkron_modu' ) ? tilfy_senkron_modu() : 'yeni' );
	$mod  = function_exists( 'tilfy_senkron_mod_normalize' ) ? tilfy_senkron_mod_normalize( $mod ) : ( $mod === 'tam' ? 'tam' : 'yeni' );
	$adet      = 0;
	$sayfa     = max( 1, (int) ( $opts['sayfa'] ?? 1 ) );
	$per_page  = 50;
	$max_sayfa = $mod === 'yeni' ? 10 : 40;
	$args_base = array(
		'post_type'              => 'post',
		'post_status'            => 'publish',
		'posts_per_page'         => $per_page,
		'orderby'                => 'date',
		'order'                  => 'DESC',
		'ignore_sticky_posts'    => true,
		'no_found_rows'          => false,
		'update_post_meta_cache' => true,
		'update_post_term_cache' => false,
	);
	if ( $mod === 'yeni' && function_exists( 'tilfy_senkron_son_zaman_al' ) ) {
		$son = tilfy_senkron_son_zaman_al( 'wordpress' );
		if ( $son !== '' ) {
			$args_base['date_query'] = array(
				array(
					'after'     => $son,
					'inclusive' => false,
					'column'    => 'post_date',
				),
			);
		}
	}
	do {
		$args          = $args_base;
		$args['paged'] = $sayfa;
		$sorgu         = new WP_Query( $args );
		foreach ( (array) $sorgu->posts as $post ) {
			$veri = tilfy_wordpress_post_veri( $post );
			if ( ! $veri ) {
				continue;
			}
			if ( $mod === 'yeni' && function_exists( 'tilfy_icerik_kaynak_mevcut_mu' ) && tilfy_icerik_kaynak_mevcut_mu( 'wordpress', $veri['kaynak_id'] ) ) {
				continue;
			}
			$medya_tipi = $veri['medya_tipi'];
			if ( function_exists( 'tilfy_senkron_medya_uygun_mu' ) && ! tilfy_senkron_medya_uygun_mu( $medya_tipi ) ) {
				$senkron_mod = function_exists( 'tilfy_senkron_medya_modu' ) ? tilfy_senkron_medya_modu() : 'both';
				if ( $senkron_mod === 'video' ) {
					continue;
				}
			}
			tilfy_icerik_upsert( $veri );
			++$adet;
		}
		$toplam_sayfa = max( 1, (int) $sorgu->max_num_pages );
		wp_reset_postdata();
		++$sayfa;
		if ( $sayfa > $toplam_sayfa || $sayfa > $max_sayfa ) {
			break;
		}
	} while ( true );

	if ( function_exists( 'tilfy_senkron_son_zaman_kaydet' ) ) {
		tilfy_senkron_son_zaman_kaydet( 'wordpress' );
	}

	return array(
		'ok'    => true,
		'adet'  => $adet,
		'mesaj' => $adet . ' WordPress yazisi senkron (' . $mod . ')',
	);
}

function tilfy_wordpress_yazi_import( $post_id ) {
	$post_id = (int) $post_id;
	if ( $post_id <= 0 ) {
		return new WP_Error( 'tilfy_wp', 'Gecersiz yazi' );
	}
	if ( ! function_exists( 'tilfy_wordpress_kaynak_aktif_mi' ) || ! tilfy_wordpress_kaynak_aktif_mi() ) {
		return new WP_Error( 'tilfy_wp', 'WordPress kaynagi kapali' );
	}
	$veri = tilfy_wordpress_post_veri( $post_id );
	if ( ! $veri ) {
		return new WP_Error( 'tilfy_wp', 'Yazi bulunamadi' );
	}
	$icerik_id = tilfy_icerik_upsert( $veri );
	return array(
		'icerik_id'      => (int) $icerik_id,
		'baslik'         => $veri['baslik'],
		'aciklama'       => $veri['aciklama'],
		'medya_dosya_id' => 0,
		'medya_url'      => $veri['medya_url'],
		'kapak_url'      => $veri['kapak_url'],
		'kaynak_url'     => $veri['kaynak_url'],
		'kaynak_id'      => $veri['kaynak_id'],
		'kapaksiz'       => ( trim( (string) $veri['kapak_url'] ) === '' && trim( (string) $veri['medya_url'] ) === '' ),
	);
}

function tilfy_wordpress_yazi_ara( $arama = '', $limit = 20, $opts = array() ) {
	$limit    = max( 1, min( 50, (int) $limit ) );
	$sayfa    = max( 1, (int) ( $opts['sayfa'] ?? 1 ) );
	$kategori = max( 0, (int) ( $opts['kategori'] ?? 0 ) );
	$args     = array(
		'post_type'              => 'post',
		'post_status'            => 'publish',
		'posts_per_page'         => $limit,
		'paged'                  => $sayfa,
		'orderby'                => 'date',
		'order'                  => 'DESC',
		'ignore_sticky_posts'    => true,
		'no_found_rows'          => false,
		'update_post_meta_cache' => true,
		'update_post_term_cache' => false,
	);
	$arama = sanitize_text_field( (string) $arama );
	if ( $arama !== '' ) {
		$args['s'] = $arama;
	}
	if ( $kategori > 0 ) {
		$args['cat'] = $kategori;
	}
	$sorgu = new WP_Query( $args );
	$cikti = array();
	foreach ( (array) $sorgu->posts as $post ) {
		$medya   = tilfy_wordpress_post_medya( (int) $post->ID );
		$cikti[] = array(
			'id'        => (int) $post->ID,
			'baslik'    => (string) $post->post_title,
			'ozet'      => wp_trim_words( wp_strip_all_tags( (string) $post->post_content ), 18, '…' ),
			'kapak_url' => $medya['kapak_url'],
			'tarih'     => mysql2date( 'd.m.Y', $post->post_date ),
			'permalink' => (string) get_permalink( $post ),
		);
	}
	$toplam       = (int) $sorgu->found_posts;
	$sayfa_sayisi = max( 1, (int) $sorgu->max_num_pages );
	if ( $sayfa > $sayfa_sayisi ) {
		$sayfa = $sayfa_sayisi;
	}
	wp_reset_postdata();
	return array(
		'yazilar'     => $cikti,
		'toplam'      => $toplam,
		'sayfa'       => $sayfa,
		'sayfa_sayisi'=> $sayfa_sayisi,
		'limit'       => $limit,
		'kategori'    => $kategori,
	);
}
