<?php 

/*-----------------------------------------------------------------------------------*/
# Account Page URL
/*-----------------------------------------------------------------------------------*/
function kanews_account_page_url($register = NULL) {
$page = kanews_get_option('account-page') ? kanews_get_option('account-page') : '';

if($page == '') {
	if($register == true) {
		$out = wp_registration_url();
	} else {
		$out = wp_login_url();
	}
} else { 
	if($register == true)
		$out = get_page_link($page).'?islem=kayit';
	else 
		$out = get_page_link($page);
}
return $out;
}

/*-----------------------------------------------------------------------------------*/
# Header User Btn
/*-----------------------------------------------------------------------------------*/
function kanews_header_user_btn() {

if( ! kanews_get_option('login-user-button') || ! kanews_get_option('login-system') )
return;

if(is_user_logged_in()) {
	$current_user = wp_get_current_user();
	$option3 = kanews_get_option('login-user-button-mobile', true) ? '' : 'hidden-mobile';
	$current_user_id = get_current_user_id();
	$avatar = kanews_user_avatar($current_user_id, 38);
	echo '<div class="kanews-dropdown '.$option3.'">';
		echo '<button class="header-author-btn" aria-label="Settings" data-toggle="kanews-user-dropdown">'.$avatar.'<span class="user-active"></span></button>';
		echo '<div id="kanews-user-dropdown" class="kanews-dropdown-content">';
			echo '<ul>';
				echo '<li class="kanews-dropdown-title d-flex align-items-center">
				<div class="kanews-dropdown-title-avatar">'.kanews_user_avatar(get_the_author_meta('ID', $current_user->ID),'48').'</div>
				<div><span>'.$current_user->display_name.'</span>
				<span>'.$current_user->user_email .'</span></div>
				</li>';
				if ( current_user_can('administrator') )
				echo '<li><a href="'.site_url().'/wp-admin"><i class="icon-settings"></i> '.esc_html__('Yönetici Paneli', 'kanews').'</a></li>';
				$page = kanews_get_option('account-page') ? kanews_get_option('account-page') : '';
				if($page != '')
				echo '<li><a href="'.kanews_account_page_url().'"><i class="icon-grid"></i> '.esc_html__( 'Hesabım', 'kanews' ).'</a></li>';
				echo '<li><a href="'.get_author_posts_url($current_user->ID).'"><i class="icon-user"></i> '.esc_html__( 'Profilim', 'kanews' ).'</a></li>';
				if(kanews_get_option('feed-page') != '')
				echo '<li><a href="'.get_page_link(kanews_get_option('feed-page')).'"><i class="icon-bolt"></i> '.esc_html__( 'Akışım', 'kanews' ).'</a></li>';
				echo '<li><a class="active" href="'.wp_logout_url( home_url( add_query_arg( [], $GLOBALS['wp']->request ) ) ).'"><i class="icon-logout"></i> '.esc_html__('Çıkış Yap', 'kanews').'</a></li>';
			echo '</ul>';
		echo '</div>';
	echo '</div>';
} else {
	echo '<button data-toggle="kanews-modal-login" aria-label="'.esc_html__( 'Giriş Yap', 'kanews' ).'" class="header-btn-icon"><i class="icon-user"></i></button>';
}

}

/*-----------------------------------------------------------------------------------*/
# Login Modal
/*-----------------------------------------------------------------------------------*/
function kanews_login_modal() {

if(kanews_get_option('login-system') != true || is_user_logged_in())
return;

echo '<div id="kanews-modal-login" class="kanews-modal kanews-modal-login">';
	echo '<div data-toggle="kanews-modal-login" class="kanews-modal-close"></div>';
	echo '<div class="kanews-modal-content">';
		echo '<div class="kanews-modal-title">'.esc_html__( 'Giriş Yap', 'kanews' ).'</div>';
		echo '<div data-toggle="kanews-modal-login" class="kanews-modal-close-btn"><i class="icon-close"></i></div>';
		echo '<div class="kanews-modal-content-inner">';
			echo '<p>'.kanews_translate('login-description', sprintf( esc_html__('%s ayrıcalıklarından yararlanmak için hemen giriş yapın veya hesap oluşturun, üstelik tamamen ücretsiz!', 'kanews' ), get_bloginfo( 'name' ))).'</p>';
			echo '<div class="kanews-btn-group">';
				echo '<a href="'.kanews_account_page_url().'" class="kanews-btn">'.esc_html__( 'Giriş Yap', 'kanews' ).'</a>';
				if ( get_option( 'users_can_register' ) )
				echo '<a href="'.kanews_account_page_url(true).'" class="kanews-btn bg-dark">'.esc_html__( 'Kayıt Ol', 'kanews' ).'</a>';
			echo '</div>';
		echo '</div>';
	echo '</div>';
echo '</div>';

}

/*-----------------------------------------------------------------------------------*/
# User Badge
/*-----------------------------------------------------------------------------------*/
function user_badge($author) {
$user = new WP_User( $author );
$role = $user->roles;
if(!$role)
$role[0] = '';
$badges = kanews_get_option('user-badge');
$rank = kanews_get_option('user-badge-2');
$count = get_user_meta( $author, 'kan_user_score', true );
$out = '';

if (!empty($badges)){
	foreach($badges as $badge) {
		if ( isset($badge['title']) && !empty($badge['title']) && !empty($badge['role']) && isset($badge['role'])) {
			if($role[0] == $badge['role']){
				$out .= '<span class="kanews-user-badge"><span style="background-color: '.$badge['color'].'" class="user-rank-geo">'.$badge['title'].'</span></span>';
			}
		}
	}
}

if (!empty($rank) && kanews_get_option('scoring_system')){
	foreach($rank as $item) {
		if ( isset($item['title']) && !empty($item['title']) && !empty($item['min']) && isset($item['min']) && !empty($item['max']) && isset($item['max'])) {
			if($count>=$item['min'] && $count<=$item['max']){
				$out .= '<span class="kanews-user-badge"><span style="background-color: '.$item['color'].'" class="user-rank-geo">'.$item['title'].'</span></span>';
			}
		}
	}
}

if(!kanews_user_status($author)) {
	$out .= '<span class="kanews-user-badge"><span style="background-color: #111">'.esc_html__( 'Doğrulanmamış', 'kanews' ).'</span></span>';
}

return $out;
}


/*-----------------------------------------------------------------------------------*/
# User Status
/*-----------------------------------------------------------------------------------*/
function kanews_user_status($user_id) {
if(!kanews_get_option('email-activation'))
return true;

// if not logged in
if ( 0 == $user_id )
return true;

// if not in subscriber role
$user_meta = get_userdata($user_id);
if($user_meta->roles[0] != 'subscriber')
return true;

$activation_meta = get_the_author_meta('_kanews_user_activation', $user_id);
if( isset($activation_meta['status']) && $activation_meta['status'])
return true;

return false;
}


/*-----------------------------------------------------------------------------------*/
# Account activation
/*-----------------------------------------------------------------------------------*/
add_action( 'show_user_profile', 'kanews_user_activation_fields', 10, 2 );
add_action( 'edit_user_profile', 'kanews_user_activation_fields', 1, 2 );
function kanews_user_activation_fields( $user, $false = 'on' ) {
if ( is_admin() && $user->ID == get_current_user_id() && $false != 'off' && ! kanews_user_status($user->ID) ): ?>
	<table id="activation" class="widefat fixed">
		<tr>
			<th><label for="verification_code"><?php _e('Doğrulama Kodunuz','kanews'); ?></label></th>
			<td><input type="number" name="verification_code" class="regular-text" />
			<?php if ( false === ( get_transient( 'kanews-user-auth-cache-' . $user->ID ) ) ): ?>
				<p><?php echo sprintf(__('Doğrulama kodu almak için <a href="%s">tıklayın.</a></p>', 'kanews'), esc_url(add_query_arg( 'verification', true, admin_url('user-edit.php?user_id='.$user->ID) ) ) ); ?>
			<?php else: ?>
				<p><?php esc_html_e('Doğrulama kodu gönderilmiştir, 15 dk içerisinde tekrar talep edebilirsiniz.', 'kanews'); ?></p>
			<?php endif; ?>
			</td>
		</tr>
	</table>
<?php endif;
}

add_action( 'personal_options_update', 'kanews_user_activation_save_fields' );
add_action( 'edit_user_profile_update', 'kanews_user_activation_save_fields' );
function kanews_user_activation_save_fields( $user_id ) {
if(!is_admin())
return false;

if ( $user_id == get_current_user_id() && ! kanews_user_status($user_id) ) {
	if( isset($_POST['verification_code']) && !empty($_POST['verification_code']) ) {
		$activation = get_user_meta($user_id, '_kanews_user_activation', true);
		if(is_array($activation) && isset($activation['token'])) {
			if($_POST['verification_code'] == $activation['token']) {
				$timediff = strtotime("now") - $activation['expired'];
				if($timediff > 30 * MINUTE_IN_SECONDS) {
					$error = esc_html__('Girdiğiniz tokenın süresi dolmuştur.', 'kanews');
				} else {
					$args = array(
						'status'    => true,
						'update'   => strtotime(date("c"))
					);
					update_user_meta($user_id, '_kanews_user_activation', $args);
					$error = esc_html__('Profiliniz doğrulanmıştır', 'kanews');
					$transient_name = 'kanews-user-auth-cache-' . $user_id;
					delete_transient( $transient_name );
				}
			} else {
				$error = esc_html__('Doğrulama kodunuz hatalı!', 'kanews');
			}
		} else {
			$error = esc_html__('Hata oluştu, tekrar deneyiniz!', 'kanews');
		}
	}
}

if(is_admin() && isset($_POST['verification_code']) && !empty($_POST['verification_code']) && kanews_get_option('email-activation') ) {
	$transient_name = 'kanews-auth-check-' . $user_id;

	$activation = get_user_meta($user_id, '_kanews_user_activation', true);
	if(is_array($activation) && isset($activation['token'])) {
		if($_POST['verification_code'] == $activation['token']) {
			$timediff = strtotime("now") - $activation['expired'];
			if($timediff > 30 * MINUTE_IN_SECONDS) {
				$error = esc_html__('Girdiğiniz tokenın süresi dolmuştur.', 'kanews');
			} else {
				$args = array(
					'status'    => true,
					'update'   => strtotime(date("c"))
				);
				update_user_meta($user_id, '_kanews_user_activation', $args);
				$transient_name = 'kanews-user-auth-cache-' . $user_id;
				delete_transient( $transient_name );
				$error = esc_html__('Profiliniz doğrulanmıştır.', 'kanews');
			}
		} else {
			$error = esc_html__('Doğrulama kodunuz hatalı!', 'kanews');
		}
	} else {
		$error = esc_html__('Hata oluştu, tekrar deneyiniz!', 'kanews');
	}	
	set_transient( $transient_name, $error);
}

}

add_action('admin_init', 'kanews_admin_send_user_activation_mail');
function kanews_admin_send_user_activation_mail() {
$user_id = get_current_user_id();
if(isset($_GET['verification']) && ! kanews_user_status($user_id)) {
	$transient_name = 'kanews-user-auth-cache-' . $user_id;
	$transient_time = 15 * MINUTE_IN_SECONDS;
	if ( false === ( $user_auth_code = get_transient( $transient_name ) ) ){
		kanews_send_user_activation_mail($user_id);
	}
}
}

add_action( 'admin_notices', 'kanews_admin_notice_send_user_activation' );
function kanews_admin_notice_send_user_activation() {
if(!kanews_get_option('email-activation'))
return;
$user_id = get_current_user_id();
$transient_name = 'kanews-auth-check-' . $user_id;
if ( '' != ( $notice = get_transient( $transient_name ) ) ){
	echo '<div class="notice notice-warning is-dismissible"><p>'.$notice.'</p></div>';
	delete_transient( $transient_name);
}
}

add_action('user_register', 'kanews_send_user_activation_mail');
function kanews_send_user_activation_mail($user_id){
	if(!kanews_get_option('email-activation'))
	return;
		
	$user_token = random_int(100000, 999999);
	$args2 = array(
		'token'    => $user_token,
		'expired'  => strtotime(date("c", strtotime("+15 minutes"))),
		'update'   => strtotime(date("c"))
	);
	update_user_meta($user_id, '_kanews_user_activation', $args2);

	$nickname = get_the_author_meta('nickname', $user_id );
	$email = get_the_author_meta('email', $user_id );
	$site_name = get_bloginfo( 'name' );
	$primary_color = !empty(kanews_get_option('primary-color')) ? kanews_get_option('primary-color') : '#d7050f';

	$settings_url = kanews_get_option('account-page');
	if ($settings_url != '') {
		$page = get_page_link($settings_url);
	} else {
		$page = get_edit_user_link();
	}

	$email_args = [		
		'title' =>  sprintf(esc_html__( '%s hesabın için doğrulama kodu!', 'kanews' ), $site_name),
		'subtitle' =>'',
		'body_title' => sprintf(esc_html__( 'Merhaba, %s', 'kanews'), $nickname),
		'body_excerpt' =>  sprintf(__('Hesabınızı doğrulayarak üyeliğinizi etkinleştirin, %s doğrulama kodunuz:<div style="%s">%s</div>', 'kanews'), $site_name, 'display: block;font-weight:bold;text-align:left;font-size:3em;margin:20px 0;border-radius:100px;color:#000;text-align:center;background: rgb(250, 249, 250);border: 1px solid rgb(218, 216, 222);padding: 5px;', $user_token),
		'button_text' =>  esc_html__('Hesabımı Doğrula', 'kanews'),
		'button_link' => esc_url($page),
		'copyright' => sprintf(esc_html__( 'Copyright © 2021 %s Tüm Hakları Saklıdır', 'kanews' ), $site_name),
		'color' => $primary_color
	];
	kan_send_mail($email, sprintf(esc_html__( '%s hesabın için doğrulama kodu!', 'kanews' ), $site_name), $email_args, 'activation', $user_id);

	$transient_name = 'kanews-user-auth-cache-' . $user_id;
	$transient_time = 15 * MINUTE_IN_SECONDS;
	set_transient( $transient_name, true, $transient_time);
}

/*-----------------------------------------------------------------------------------*/
#  Earn scores for posts
/*-----------------------------------------------------------------------------------*/

add_action( 'transition_post_status', function ( $new_status, $old_status, $post )
{

	if( 'publish' == $new_status && 'publish' != $old_status && kanews_get_option('scoring_system')  && get_post_meta($post->ID, '_kan_entry_scored', true) != '1' && ( $post->post_type == 'post' || $post->post_type == 'columist'  )) {

		$author = $post->post_author;
		$points = get_user_meta( $author, 'kan_user_score', true ) ? get_user_meta( $author, 'kan_user_score', true ) : 0;
		$points = (int)$points + (int)kanews_get_option('entry_score', 50);
		update_user_meta( $author, 'kan_user_score', $points); 
		update_post_meta( $author, '_kan_entry_scored', '1'); 

		date_default_timezone_set('Europe/Istanbul');
		Kanews\Members\Notifications::message( $author , array(
			'points'  => 'post',
			'date' => current_time( 'timestamp', 1 )
		), false );

	}
}, 10, 3 );

/*-----------------------------------------------------------------------------------*/
#  Earn scores for comments
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'comment_published_add_points' ) ) {
function comment_published_add_points( $comment_ID, $comment_approved ) {
	$comment = get_comment( $comment_ID );
	$comment_author_id = $comment -> user_id;
	if( kanews_get_option('scoring_system')  && $comment_approved === 1 && get_comment_meta($comment_ID, '_kan_comment_scored', true) != '1') {
		$points = get_user_meta( $comment_author_id, 'kan_user_score', true ) ? get_user_meta( $comment_author_id, 'kan_user_score', true ) : 0;
		$points += kanews_get_option('comment_score', 25);
		update_user_meta( $comment_author_id, 'kan_user_score', $points); 
		update_comment_meta( $comment_ID, '_kan_comment_scored', '1'); 

			date_default_timezone_set('Europe/Istanbul');
			Kanews\Members\Notifications::message( $comment_author_id , array(
				'points'  => 'comment',
				'date' => current_time( 'timestamp', 1 )
			), false );
		
	}
}
}
add_action( 'comment_post', 'comment_published_add_points', 10, 2 );


/**
 * Get user's rank information based on their score
 */
function kanews_get_rank_info($user_id) {
	// Get the actual user score instead of hardcoded value
	// $current_score = get_user_meta($user_id, 'kan_user_score', true) ? (int)get_user_meta($user_id, 'kan_user_score', true) : 0;
	$current_score = 10;
	$rank_badges = kanews_get_option('user-badge-2');
	
	if (!is_array($rank_badges)) {
			return array(
					'current_rank' => 'beginner',
					'previous_rank' => null,
					'next_rank' => null,
					'current_score' => $current_score,
					'next_rank_score' => 0,
					'progress' => 0
			);
	}
	
	// Filter out badges without min/max values
	$valid_badges = array();
	foreach ($rank_badges as $badge_key => $badge) {
			if (isset($badge['min']) && isset($badge['max']) && is_numeric($badge['min']) && is_numeric($badge['max'])) {
					$valid_badges[$badge_key] = $badge;
			}
	}
	
	if (empty($valid_badges)) {
			return array(
					'current_rank' => 'beginner',
					'previous_rank' => null,
					'next_rank' => null,
					'current_score' => $current_score,
					'next_rank_score' => 0,
					'progress' => 0
			);
	}
	
	// Sort badges by min score
	uasort($valid_badges, function($a, $b) {
			return (int)$a['min'] - (int)$b['min'];
	});
	
	$current_rank = 'beginner';
	$previous_rank = null;
	$next_rank = null;
	$next_rank_score = 0;
	
	// Determine current, previous and next ranks
	foreach ($valid_badges as $badge_key => $badge) {
			$min_score = (int)$badge['min'];
			$max_score = (int)$badge['max'];
			
			if ($current_score >= $min_score && $current_score <= $max_score) {
					$current_rank = $badge_key;
			} elseif ($current_score < $min_score) {
					$next_rank = $badge_key;
					$next_rank_score = $min_score;
					break;
			} else {
					$previous_rank = $badge_key;
			}
	}
	
	// Calculate progress to next rank
	$progress = 0;
	if ($next_rank && isset($valid_badges[$current_rank])) {
			$current_min = (int)$valid_badges[$current_rank]['min'];
			$current_max = (int)$valid_badges[$current_rank]['max'];
			$score_needed = $next_rank_score - $current_min;
			$score_gained = $current_score - $current_min;
			$progress = round(($score_gained / $score_needed) * 100);
	}
	
	return array(
			'current_rank' => $current_rank,
			'previous_rank' => $previous_rank,
			'next_rank' => $next_rank,
			'current_score' => $current_score,
			'next_rank_score' => $next_rank_score,
			'progress' => $progress
	);
}

/**
 * Generate HTML for rank badge
 */
function kanews_get_rank_badge_html($rank) {
	$rank_badges = kanews_get_option('user-badge-2');
	
	if ($rank === 'beginner' || !isset($rank_badges[$rank])) {
			return sprintf(
					'<span class="kanews-user-badge kanews-user-badge-beginner">%s</span>',
					esc_html__('Başlangıç', 'kanews')
			);
	}
	
	$badge = $rank_badges[$rank];
	$name = isset($badge['title']) ? $badge['title'] : $rank;
	$color = isset($badge['color']) ? $badge['color'] : '#6c757d';
	
	return sprintf(
			'<span class="kanews-user-badge"><span style="background-color: %s">%s</span></span>',
			esc_attr($color),
			esc_html($name)
	);
} 