<?php

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

function tilfy_senkron_mod_normalize( $mod ) {
	$mod = sanitize_key( (string) $mod );
	return $mod === 'tam' ? 'tam' : 'yeni';
}

function tilfy_senkron_modu() {
	return tilfy_senkron_mod_normalize( tilfy_ayar_al( 'senkron_modu', 'yeni' ) );
}

function tilfy_icerik_kaynak_mevcut_mu( $platform, $kaynak_id ) {
	global $wpdb;
	$platform  = sanitize_key( (string) $platform );
	$kaynak_id = sanitize_text_field( (string) $kaynak_id );
	if ( $platform === '' || $kaynak_id === '' ) {
		return false;
	}
	$id = (int) $wpdb->get_var(
		$wpdb->prepare(
			'SELECT id FROM ' . tilfy_tablo( 'icerik' ) . ' WHERE kaynak_platform = %s AND kaynak_id = %s LIMIT 1',
			$platform,
			$kaynak_id
		)
	);
	return $id > 0;
}

function tilfy_senkron_son_zaman_al( $platform ) {
	$platform = sanitize_key( (string) $platform );
	if ( $platform === '' ) {
		return '';
	}
	$opts = get_option( 'tilfy_senkron_son', array() );
	if ( ! is_array( $opts ) ) {
		return '';
	}
	$zaman = sanitize_text_field( (string) ( $opts[ $platform ] ?? '' ) );
	return $zaman;
}

function tilfy_senkron_son_zaman_kaydet( $platform, $zaman = '' ) {
	$platform = sanitize_key( (string) $platform );
	if ( $platform === '' ) {
		return;
	}
	$zaman = sanitize_text_field( (string) $zaman );
	if ( $zaman === '' ) {
		$zaman = current_time( 'mysql' );
	}
	$opts = get_option( 'tilfy_senkron_son', array() );
	if ( ! is_array( $opts ) ) {
		$opts = array();
	}
	$opts[ $platform ] = $zaman;
	update_option( 'tilfy_senkron_son', $opts, false );
}

function tilfy_medya_tilfy_dosyasi_mi( $attachment_id ) {
	$attachment_id = (int) $attachment_id;
	if ( $attachment_id <= 0 ) {
		return false;
	}
	if ( get_post_meta( $attachment_id, '_tilfy_gecici_medya', true ) === '1' ) {
		return true;
	}
	if ( get_post_meta( $attachment_id, '_tilfy_kapak_kalici', true ) === '1' ) {
		return true;
	}
	$yol = get_attached_file( $attachment_id );
	if ( ! is_string( $yol ) || $yol === '' ) {
		return false;
	}
	$adi = basename( $yol );
	return ( strpos( $adi, 'tilfy-' ) === 0 || strpos( $adi, 'tilfy-kapak-' ) === 0 );
}
