<?php

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

function tilfy_paylasim_ayar_al( $paylasim ) {
	if ( ! $paylasim ) {
		return array();
	}
	$ham = (string) ( $paylasim->platform_ayar ?? '' );
	if ( $ham === '' ) {
		return array();
	}
	$coz = json_decode( $ham, true );
	return is_array( $coz ) ? $coz : array();
}

function tilfy_paylasim_ayar_temizle( $platform, $ham ) {
	$platform = sanitize_key( $platform );
	if ( ! is_array( $ham ) ) {
		return array();
	}
	$ayar = array();
	if ( in_array( $platform, array( 'instagram', 'facebook' ), true ) ) {
		$format = sanitize_key( (string) ( $ham['format'] ?? 'reels' ) );
		$ayar['format'] = in_array( $format, array( 'reels', 'story' ), true ) ? $format : 'reels';
		$ayar['thumbnail_id'] = $ayar['format'] === 'story' ? 0 : (int) ( $ham['thumbnail_id'] ?? 0 );
	}
	if ( $platform === 'youtube' ) {
		$tur = sanitize_key( (string) ( $ham['tur'] ?? 'video' ) );
		$ayar['tur']          = $tur === 'short' ? 'short' : 'video';
		$cocuk = sanitize_key( (string) ( $ham['cocuk'] ?? 'hayir' ) );
		$ayar['cocuk']        = $cocuk === 'evet' ? 'evet' : 'hayir';
		$gizlilik             = sanitize_key( (string) ( $ham['gizlilik'] ?? 'public' ) );
		$ayar['gizlilik']     = in_array( $gizlilik, array( 'public', 'unlisted', 'private' ), true ) ? $gizlilik : 'public';
		$ayar['playlist_id']  = sanitize_text_field( (string) ( $ham['playlist_id'] ?? '' ) );
		$ayar['thumbnail_id'] = $ayar['tur'] === 'short' ? 0 : max( 0, (int) ( $ham['thumbnail_id'] ?? 0 ) );
	}
	return $ayar;
}

function tilfy_post_platform_ayar_temizle( $ham ) {
	$ham   = is_array( $ham ) ? $ham : array();
	$cikti = array();
	foreach ( $ham as $pl => $kart ) {
		$pl = sanitize_key( (string) $pl );
		if ( $pl === '' || ! is_array( $kart ) ) {
			continue;
		}
		$cikti[ $pl ] = tilfy_paylasim_ayar_temizle( $pl, $kart );
	}
	return $cikti;
}

function tilfy_post_platform_ozel_temizle( $ham ) {
	$ham   = is_array( $ham ) ? $ham : array();
	$cikti = array();
	foreach ( $ham as $pl => $kart ) {
		$pl = sanitize_key( (string) $pl );
		if ( $pl === '' || ! is_array( $kart ) ) {
			continue;
		}
		$cikti[ $pl ] = array(
			'baslik'    => sanitize_text_field( (string) ( $kart['baslik'] ?? '' ) ),
			'aciklama'  => wp_kses_post( (string) ( $kart['aciklama'] ?? '' ) ),
			'etiketler' => sanitize_textarea_field( (string) ( $kart['etiketler'] ?? '' ) ),
		);
	}
	return $cikti;
}

function tilfy_post_disk_yollar_temizle( $ham ) {
	$ham   = is_array( $ham ) ? $ham : array();
	$cikti = array();
	foreach ( $ham as $yol ) {
		if ( ! is_string( $yol ) && ! is_numeric( $yol ) ) {
			continue;
		}
		$yol = wp_normalize_path( sanitize_text_field( (string) $yol ) );
		if ( $yol !== '' ) {
			$cikti[] = $yol;
		}
	}
	return array_values( array_unique( $cikti ) );
}

function tilfy_sunucu_yukleme_limiti() {
	return (int) wp_max_upload_size();
}

function tilfy_sunucu_yukleme_limiti_metin() {
	return size_format( tilfy_sunucu_yukleme_limiti() );
}
