<?php
namespace Kanews\Members;
use WP_User;

class Users {

	private static $instance;

	public static function getInstance() {
		if ( null === static::$instance ) {
			static::$instance = new static();
		}
		return static::$instance;
	}

	private $author;
	
	/**
	 * Security questions for contact form
	 * 
	 * @var array
	 */
	private static $security_questions = [
		'0' => ['question' => '3*3=?', 'answer' => '9'],
		'1' => ['question' => '1*3=?', 'answer' => '3'],
		'2' => ['question' => '2+2=?', 'answer' => '4'],
		'3' => ['question' => '1+8=?', 'answer' => '9'],
		'4' => ['question' => '5*0=?', 'answer' => '0'],
		'5' => ['question' => '2+2=?', 'answer' => '4'],
		'6' => ['question' => 'Türkiye\'nin Başkenti?', 'answer' => 'Ankara'],
	];

	/**
	 * Default insights period in hours
	 */
	private const DEFAULT_INSIGHTS_HOURS = 24;

	/**
	 * Minimum password length
	 */
	private const MIN_PASSWORD_LENGTH = 8;
	
	public function __construct() {
		$this->possibly_redirect();
		
		// Filters
		add_filter( 'manage_users_columns', array( $this, 'admin_user_column' ), 1 );
		add_filter( 'manage_users_custom_column', array( $this, 'admin_user_column_content'), 10, 3);

		// Account
		add_filter( 'wp_ajax_nopriv_kanews_ajax_login', array( $this, 'kanews_ajax_login' ) );
		add_filter( 'wp_ajax_nopriv_kanews_ajax_register', array( $this, 'kanews_ajax_register' ) );
		add_filter( 'wp_ajax_kanews_ajax_profile', array( $this, 'kanews_ajax_profile' ) );
		add_filter( 'wp_ajax_kanews_ajax_subscribe_category', array( $this, 'kanews_ajax_subscribe_category' ) );
		add_filter( 'wp_ajax_kanews_ilan_ilan_update', array( $this, 'kanews_ilan_ilan_update' ) );

		// Archives
		add_filter( 'template_redirect', array( $this, 'disable_author_page' ) );
		add_filter( 'wp_ajax_nopriv_kanews_ajax_contact', array( $this, 'kanews_ajax_contact' ) );
		add_filter( 'wp_ajax_kanews_ajax_contact', array( $this, 'kanews_ajax_contact' ) );
		
		// Extra Fields
		add_action( 'show_user_profile', array( $this, 'add_user_profile_fields'  ) );
		add_action( 'edit_user_profile', array( $this, 'add_user_profile_fields'  ) );
		add_action( 'personal_options_update', array( $this, 'save_user_profile_fields'  ) );
		add_action( 'edit_user_profile_update', array( $this, 'save_user_profile_fields'  ) );

		add_action( 'transition_post_status', array( $this, 'set_publish_date' ), 10, 3 );
	}

	/**
	 * Validate reCAPTCHA and Turnstile responses
	 * 
	 * @return bool|\WP_Error True if valid, \WP_Error on failure
	 */
	private function validate_captcha() {
		if ( isset( $_POST['g-recaptcha-response'] ) && $_POST['g-recaptcha-response'] == 0 ) {
			return new \WP_Error( 'captcha_failed', esc_html__( 'Güvenlik doğrulamasını gerçekleştirin!', 'kanews' ) );
		}

		if ( isset( $_POST['cf-turnstile-response'] ) && empty( $_POST['cf-turnstile-response'] ) ) {
			return new \WP_Error( 'captcha_failed', esc_html__( 'Güvenlik doğrulamasını gerçekleştirin!', 'kanews' ) );
		}

		return true;
	}

	/**
	 * Validate password strength
	 * 
	 * @param string $password Password to validate
	 * @return bool|\WP_Error True if valid, \WP_Error on failure
	 */
	private function validate_password_strength( $password ) {
		if ( strlen( $password ) < self::MIN_PASSWORD_LENGTH ) {
			return new \WP_Error( 
				'weak_password', 
				esc_html__( 'Şifreniz en az 8 karakter uzunluğunda olmalı ve en az bir büyük harf, bir rakam ve bir özel karakter içermelidir.', 'kanews' ) 
			);
		}

		$uppercase = preg_match( '@[A-Z]@', $password );
		$number = preg_match( '@[0-9]@', $password );
		$special_chars = preg_match( '@[^\w]@', $password );

		if ( ! $uppercase || ! $number || ! $special_chars ) {
			return new \WP_Error( 
				'weak_password', 
				esc_html__( 'Şifreniz en az 8 karakter uzunluğunda olmalı ve en az bir büyük harf, bir rakam ve bir özel karakter içermelidir.', 'kanews' ) 
			);
		}

		return true;
	}

	/**
	 * Validate security question answer
	 * 
	 * @param string $answer User's answer
	 * @param string|int $question_index Question index
	 * @return bool
	 */
	private function validate_security_question( $answer, $question_index ) {
		if ( ! isset( self::$security_questions[ $question_index ] ) ) {
			return false;
		}

		$expected_answer = self::$security_questions[ $question_index ]['answer'];
		return sanitize_text_field( $answer ) === $expected_answer;
	}

	/**
	 * Update user social media profiles
	 * 
	 * @param int $user_id User ID
	 * @param array $profiles Array of profile fields
	 * @return void
	 */
	private function update_user_social_profiles( $user_id, $profiles ) {
		$social_fields = [
			'my_city',
			'facebook_profile',
			'twitter_profile',
			'instagram_profile',
			'linkedin_profile',
			'youtube_profile',
			'telegram_profile',
			'description',
		];

		foreach ( $social_fields as $field ) {
			if ( isset( $profiles[ $field ] ) ) {
				$value = ( $field === 'description' ) 
					? esc_html( $profiles[ $field ] ) 
					: esc_attr( $profiles[ $field ] );
				update_user_meta( $user_id, $field, $value );
			}
		}
	}

	/**
	 * Award social media score points if eligible
	 * 
	 * @param int $user_id User ID
	 * @param array $profiles Array of profile fields
	 * @return void
	 */
	private function award_social_score( $user_id, $profiles ) {
		if ( get_the_author_meta( '_kan_social_scored', $user_id ) == '1' ) {
			return;
		}

		if ( ! kanews_get_option( 'scoring_system' ) ) {
			return;
		}

		$has_social = ! empty( $profiles['facebook_profile'] ) 
			|| ! empty( $profiles['twitter_profile'] ) 
			|| ! empty( $profiles['instagram_profile'] ) 
			|| ! empty( $profiles['linkedin_profile'] ) 
			|| ! empty( $profiles['youtube_profile'] ) 
			|| ! empty( $profiles['telegram_profile'] );

		if ( ! $has_social ) {
			return;
		}

		$points = (int) get_user_meta( $user_id, 'kan_user_score', true );
		$points += (int) kanews_get_option( 'social_score', 5 );
		
		update_user_meta( $user_id, 'kan_user_score', $points );
		update_user_meta( $user_id, '_kan_social_scored', '1' );

		if ( kanews_get_option( 'notifications' ) ) {
			date_default_timezone_set( 'Europe/Istanbul' );
			Notifications::message( 
				$user_id, 
				[
					'points' => 'social',
					'date' => current_time( 'timestamp', 1 )
				],
				0
			);
		}
	}

	/**
	 * Post publish date
	 * 
	 * @param string $new_status New post status
	 * @param string $old_status Old post status
	 * @param \WP_Post $post Post object
	 * @return void
	 */
	public function set_publish_date( $new_status, $old_status, $post ) {
		if ( $new_status !== 'publish' || $old_status === 'publish' ) {
			return;
		}

		if ( ! in_array( $post->post_type, [ 'post', 'columist' ], true ) ) {
			return;
		}

		$author = get_userdata( $post->post_author );
		if ( ! $author || ! $author->ID ) {
			return;
		}

		update_user_meta( $author->ID, 'last_post_publish_date4', current_time( 'timestamp', 1 ) );
	}
	
	/**
	 * User ID Column
	 *
	 * @since 1.0.0
	 * @param array $columns Existing columns
	 * @return array Modified columns
	 */
	public function admin_user_column( $columns ) {
		$columns['user_id'] = 'ID';
		$columns['user_badge'] = esc_html__( 'Rozetler', 'kanews' );
		return $columns;
	}

	/**
	 * User ID Column Content
	 *
	 * @since 1.0.0
	 * @param string $value Column value
	 * @param string $column_name Column name
	 * @param int $user_id User ID
	 * @return string Column content
	 */
	public function admin_user_column_content( $value, $column_name, $user_id ) {
		if ( 'user_id' === $column_name ) {
			return $user_id;
		}

		if ( 'user_badge' === $column_name ) {
			$user = new WP_User( $user_id );
			if ( ! $user || empty( $user->roles ) ) {
				return $value;
			}

			$badges = kanews_get_option( 'user-badge' );
			if ( empty( $badges ) || ! is_array( $badges ) ) {
				return $value;
			}

			$user_role = $user->roles[0] ?? '';
			$output = '';

			foreach ( $badges as $badge ) {
				if ( empty( $badge['title'] ) || empty( $badge['role'] ) || $badge['role'] !== $user_role ) {
					continue;
				}

				$color = esc_attr( $badge['color'] ?? '#000' );
				$title = esc_html( $badge['title'] );
				$output .= sprintf(
					'<button class="button" style="margin: 0 2px;border-color:%s;background-color: %s;color:#fff">%s</button>',
					$color,
					$color,
					$title
				);
			}

			return $output ?: $value;
		}

		return $value;
	}
	
	/**
	 * My Feed - Subscribe/Unsubscribe category or author
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public function kanews_ajax_subscribe_category() {
		// Security
		$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( $_POST['nonce'] ) : '';
		if ( ! wp_verify_nonce( $nonce, 'kanews-ajax-nonce' ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'İzin verilmedi!', 'kanews' ) ] );
			return;
		}

		$uid = get_current_user_id();
		if ( ! is_user_logged_in() || ! $uid ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Giriş yapmalısınız!', 'kanews' ) ] );
			return;
		}

		$cats = get_user_option( 'kanews_subscribe_category', $uid );
		$authors = get_user_option( 'kanews_subscribe_authors', $uid );
		$cats = is_array( $cats ) ? $cats : [];
		$authors = is_array( $authors ) ? $authors : [];

		$new_cat = isset( $_POST['cat_id'] ) ? absint( $_POST['cat_id'] ) : 0;
		$new_author = isset( $_POST['uid'] ) ? absint( $_POST['uid'] ) : 0;

		if ( $new_cat > 0 ) {
			$key = array_search( $new_cat, $cats, true );
			if ( $key !== false ) {
				unset( $cats[ $key ] );
				$cats = array_values( $cats ); // Re-index array
			} else {
				$cats[] = $new_cat;
			}
			update_user_option( $uid, 'kanews_subscribe_category', $cats );
			wp_send_json_success();
			return;
		}

		if ( $new_author > 0 ) {
			if ( $uid === $new_author ) {
				wp_send_json_error( [ 'message' => esc_html__( 'İzin verilmedi!', 'kanews' ) ] );
				return;
			}

			$key = array_search( $new_author, $authors, true );
			if ( $key !== false ) {
				unset( $authors[ $key ] );
				$authors = array_values( $authors ); // Re-index array
			} else {
				$authors[] = $new_author;
			}
			update_user_option( $uid, 'kanews_subscribe_authors', $authors );
			wp_send_json_success();
			return;
		}

		wp_send_json_error( [ 'message' => esc_html__( 'Geçersiz istek!', 'kanews' ) ] );
	}

	/**
	 * İlanı Yukarı Taşı (Move listing to top)
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public function kanews_ilan_ilan_update() {
		// Security
		$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( $_POST['nonce'] ) : '';
		$post_user_id = isset( $_POST['puid'] ) ? absint( $_POST['puid'] ) : 0;
		$post_id = isset( $_POST['pid'] ) ? absint( $_POST['pid'] ) : 0;

		if ( ! wp_verify_nonce( $nonce, 'kanews-ajax-nonce' ) 
			|| ! $post_user_id 
			|| ! $post_id 
			|| ! is_user_logged_in() 
		) {
			wp_send_json_error( [ 'message' => esc_html__( 'Yukarı taşınamadı, tekrar deneyin.', 'kanews' ) ] );
			return;
		}

		$user_id = get_current_user_id();
		if ( $user_id !== $post_user_id ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Yukarı taşınamadı, tekrar deneyin.', 'kanews' ) ] );
			return;
		}

		// Check if ilan system is enabled
		if ( ! class_exists( 'Simple_Review' ) 
			|| ! kanews_get_option( 'ilan-sistemi' ) 
			|| ! kanews_get_option( 'ilan-update' ) 
		) {
			wp_send_json_error( [ 'message' => esc_html__( 'Yukarı taşınamadı, tekrar deneyin.', 'kanews' ) ] );
			return;
		}

		$insights = self::DEFAULT_INSIGHTS_HOURS * HOUR_IN_SECONDS;
		$subscribed = true;

		if ( class_exists( 'WooCommerce' ) && kanews_get_option( 'ilan-insights' ) ) {
			$user_insights = get_user_meta( $user_id, 'kanews_insights_ilan_update_loop', true );
			$insights = $user_insights ? absint( $user_insights ) : $insights;
			$subscribed = kanews_insights_control( $user_id );
		}

		if ( ! $subscribed ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Yukarı taşınamadı, tekrar deneyin.', 'kanews' ) ] );
			return;
		}

		$last_update_date = get_user_option( 'ilan-last-update-date', $user_id );
		$time_diff = time() - absint( $last_update_date );

		if ( $time_diff <= $insights ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Yukarı taşınamadı, tekrar deneyin.', 'kanews' ) ] );
			return;
		}

		// Update post menu_order to 0
		wp_update_post( [
			'ID' => $post_id,
			'menu_order' => 0
		] );

		// Reorder all ilan posts
		$this->reorder_ilan_posts();

		update_user_option( $user_id, 'ilan-last-update-date', time() );
		wp_send_json_success( [ 'message' => esc_html__( 'İlan Yukarıya Taşındı', 'kanews' ) ] );
	}

	/**
	 * Reorder ilan posts by menu_order
	 * 
	 * @return void
	 */
	private function reorder_ilan_posts() {
		global $wpdb;

		$post_statuses = [ 'publish', 'pending', 'draft', 'private', 'future' ];
		$placeholders = implode( ',', array_fill( 0, count( $post_statuses ), '%s' ) );

		// Reset row number variable
		$wpdb->query( 'SET @row_number = 0' );

		// Update menu_order using ranking
		$wpdb->query( $wpdb->prepare(
			"UPDATE {$wpdb->posts} as pt 
			JOIN (
				SELECT ID, (@row_number:=@row_number + 1) AS `rank`
				FROM {$wpdb->posts}
				WHERE post_type = 'ilan' 
				AND post_status IN ($placeholders)
				ORDER BY menu_order ASC
			) as pt2 ON pt.id = pt2.id
			SET pt.menu_order = pt2.`rank`",
			$post_statuses
		) );
	}
	

	/**
	 * Ajax Register
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public function kanews_ajax_register() {
		check_ajax_referer( 'register_action', 'register_field' );

		$captcha_check = $this->validate_captcha();
		if ( is_wp_error( $captcha_check ) ) {
			wp_send_json_error( [ 'message' => $captcha_check->get_error_message() ] );
			return;
		}

		$username = isset( $_POST['username'] ) ? trim( sanitize_user( $_POST['username'] ) ) : '';
		$email = isset( $_POST['email'] ) ? trim( sanitize_email( $_POST['email'] ) ) : '';
		$password = isset( $_POST['password'] ) ? $_POST['password'] : '';
		$password2 = isset( $_POST['password2'] ) ? $_POST['password2'] : '';

		if ( empty( $username ) || empty( $email ) || empty( $password ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Lütfen tüm alanları doldurun!', 'kanews' ) ] );
			return;
		}

		if ( ! is_email( $email ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Lütfen doğru bir e-posta adresi girin!', 'kanews' ) ] );
			return;
		}

		if ( $password !== $password2 ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Girdiğiniz şifreler eşleşmiyor!', 'kanews' ) ] );
			return;
		}

		$password_check = $this->validate_password_strength( $password );
		if ( is_wp_error( $password_check ) ) {
			wp_send_json_error( [ 'message' => $password_check->get_error_message() ] );
			return;
		}

		$register_fields = [
			'user_login' => $username,
			'user_email' => $email,
			'user_pass' => $password,
			'show_admin_bar_front' => false,
			'role' => get_option( 'default_role', 'subscriber' )
		];

		$user_id = wp_insert_user( $register_fields );

		if ( is_wp_error( $user_id ) ) {
			wp_send_json_error( [ 'message' => $user_id->get_error_message() ] );
			return;
		}

		$user = get_user_by( 'ID', $user_id );
		if ( ! $user ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Kullanıcı oluşturulamadı!', 'kanews' ) ] );
			return;
		}

		wp_set_auth_cookie( $user->ID );
		wp_set_current_user( $user->ID );
		do_action( 'wp_login', $user->user_login, $user );

		wp_send_json_success( [ 'message' => esc_html__( 'Kaydınız tamamlanmıştır, yönlendiriliyorsunuz..', 'kanews' ) ] );
	}

	/**
	 * Ajax contact form
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public function kanews_ajax_contact() {
		check_ajax_referer( 'contact_action', 'contact_field' );

		$captcha_check = $this->validate_captcha();
		if ( is_wp_error( $captcha_check ) ) {
			wp_send_json_error( [ 'message' => $captcha_check->get_error_message() ] );
			return;
		}

		$pid = isset( $_POST['pid'] ) ? absint( $_POST['pid'] ) : 0;
		$to = isset( $_POST['to'] ) ? sanitize_email( $_POST['to'] ) : '';
		$name = isset( $_POST['name'] ) ? trim( sanitize_text_field( $_POST['name'] ) ) : '';
		$surname = isset( $_POST['surname'] ) ? trim( sanitize_text_field( $_POST['surname'] ) ) : '';
		$phone = isset( $_POST['phone'] ) ? trim( sanitize_text_field( $_POST['phone'] ) ) : '';
		$subject = isset( $_POST['subject'] ) ? trim( sanitize_text_field( $_POST['subject'] ) ) : '';
		$email = isset( $_POST['email'] ) ? trim( sanitize_email( $_POST['email'] ) ) : '';
		$comment = isset( $_POST['comment'] ) ? trim( sanitize_textarea_field( $_POST['comment'] ) ) : '';

		if ( empty( $name ) || empty( $email ) || empty( $subject ) || empty( $comment ) || empty( $to ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Lütfen tüm gerekli alanları doldurun!', 'kanews' ) ] );
			return;
		}

		if ( ! is_email( $email ) || ! is_email( $to ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Lütfen geçerli e-posta adresleri girin!', 'kanews' ) ] );
			return;
		}

		// Validate security question
		$answer = isset( $_POST['qua'] ) ? sanitize_text_field( $_POST['qua'] ) : '';
		$question_index = isset( $_POST['qua1'] ) ? sanitize_text_field( $_POST['qua1'] ) : '';

		if ( ! $this->validate_security_question( $answer, $question_index ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Lütfen güvenlik sorusunu doğru yanıtlayın!', 'kanews' ) ] );
			return;
		}

		$permalink = $pid > 0 ? get_the_permalink( $pid ) : home_url();
		$site_name = get_bloginfo( 'name' );

		$body = sprintf(
			'Kimden: %s %s <a href="mailto:%s">%s</a><br>Konu: %s<br>Telefon: %s<br><br>İleti gövdesi:<br>%s<br><br>Bu e-posta, %s (<a rel="noreferrer" target="_blank" href="%s">%s</a>) adresindeki iletişim formundan gönderildi.<br><br>',
			esc_html( $name ),
			esc_html( $surname ),
			esc_attr( $email ),
			esc_html( $email ),
			esc_html( $subject ),
			esc_html( $phone ),
			nl2br( esc_html( $comment ) ),
			esc_html( $site_name ),
			esc_url( $permalink ),
			esc_url( $permalink )
		);

		$headers = [
			'Content-Type: text/html; charset=UTF-8',
			'Reply-To: ' . $name . ' ' . $surname . ' <' . $email . '>'
		];

		$mail = wp_mail( $to, $subject, $body, $headers );

		if ( is_wp_error( $mail ) ) {
			wp_send_json_error( [ 'message' => $mail->get_error_message() ] );
			return;
		}

		wp_send_json_success( [ 'message' => esc_html__( 'Mesajınız iletilmiştir, yönlendiriliyorsunuz..', 'kanews' ) ] );
	}

	/**
	 * Ajax profile update
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public function kanews_ajax_profile() {
		check_ajax_referer( 'profile_action', 'profile_field' );

		$captcha_check = $this->validate_captcha();
		if ( is_wp_error( $captcha_check ) ) {
			wp_send_json_error( [ 'message' => $captcha_check->get_error_message() ] );
			return;
		}

		$user_id = get_current_user_id();
		if ( ! $user_id ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Giriş yapmalısınız!', 'kanews' ) ] );
			return;
		}

		if ( ! kanews_user_status( $user_id ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Değişiklikler kaydedilmemiştir lütfen e-posta adresinizi doğrulayın!', 'kanews' ) ] );
			return;
		}

		// Update email if provided and changed
		if ( ! empty( $_POST['email'] ) ) {
			$new_email = trim( sanitize_email( $_POST['email'] ) );
			
			if ( ! is_email( $new_email ) ) {
				wp_send_json_error( [ 'message' => esc_html__( 'Lütfen doğru bir e-posta adresi girin!', 'kanews' ) ] );
				return;
			}

			$existing_user_id = email_exists( $new_email );
			if ( $existing_user_id && $existing_user_id !== $user_id ) {
				wp_send_json_error( [ 'message' => esc_html__( 'Bu e-posta başka bir kullanıcı tarafından kullanılıyor. farklı bir e-posta adresi deneyin.', 'kanews' ) ] );
				return;
			}

			$user_data = get_userdata( $user_id );
			if ( $user_data && $new_email !== $user_data->user_email ) {
				wp_update_user( [ 'ID' => $user_id, 'user_email' => $new_email ] );
				delete_user_meta( $user_id, '_kanews_user_activation' );
				
				if ( ! kanews_user_status( $user_id ) ) {
					kanews_send_user_activation_mail( $user_id );
				}
			}
		}

		// Update password if provided
		if ( ! empty( $_POST['pass1'] ) && ! empty( $_POST['pass2'] ) ) {
			$pass1 = $_POST['pass1'];
			$pass2 = $_POST['pass2'];

			if ( $pass1 !== $pass2 ) {
				wp_send_json_error( [ 'message' => esc_html__( 'Girdiğiniz şifreler eşleşmiyor!', 'kanews' ) ] );
				return;
			}

			$password_check = $this->validate_password_strength( $pass1 );
			if ( is_wp_error( $password_check ) ) {
				wp_send_json_error( [ 'message' => $password_check->get_error_message() ] );
				return;
			}

			wp_update_user( [ 'ID' => $user_id, 'user_pass' => $pass1 ] );
		}

		// Update user fields
		$user_fields = [
			'ID' => $user_id,
			'nickname' => isset( $_POST['nickname'] ) ? trim( sanitize_text_field( $_POST['nickname'] ) ) : '',
			'first_name' => isset( $_POST['first-name'] ) ? trim( sanitize_text_field( $_POST['first-name'] ) ) : '',
			'last_name' => isset( $_POST['last-name'] ) ? trim( sanitize_text_field( $_POST['last-name'] ) ) : '',
			'display_name' => isset( $_POST['display_name'] ) ? trim( sanitize_text_field( $_POST['display_name'] ) ) : '',
		];

		$user_result = wp_update_user( $user_fields );
		if ( is_wp_error( $user_result ) ) {
			wp_send_json_error( [ 'message' => $user_result->get_error_message() ] );
			return;
		}

		// Update social profiles
		$profiles = [
			'my_city' => isset( $_POST['my_city'] ) ? $_POST['my_city'] : '',
			'facebook_profile' => isset( $_POST['facebook_profile'] ) ? $_POST['facebook_profile'] : '',
			'twitter_profile' => isset( $_POST['twitter_profile'] ) ? $_POST['twitter_profile'] : '',
			'instagram_profile' => isset( $_POST['instagram_profile'] ) ? $_POST['instagram_profile'] : '',
			'linkedin_profile' => isset( $_POST['linkedin_profile'] ) ? $_POST['linkedin_profile'] : '',
			'youtube_profile' => isset( $_POST['youtube_profile'] ) ? $_POST['youtube_profile'] : '',
			'telegram_profile' => isset( $_POST['telegram_profile'] ) ? $_POST['telegram_profile'] : '',
			'description' => isset( $_POST['description'] ) ? $_POST['description'] : '',
		];

		$this->update_user_social_profiles( $user_id, $profiles );
		$this->award_social_score( $user_id, $profiles );

		wp_send_json_success( [ 'message' => esc_html__( 'Profiliniz güncellenmiştir!', 'kanews' ) ] );
	}

	/**
	 * Ajax Login
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public function kanews_ajax_login() {
		$captcha_check = $this->validate_captcha();
		if ( is_wp_error( $captcha_check ) ) {
			wp_send_json_error( [ 'message' => $captcha_check->get_error_message() ] );
			return;
		}

		if ( ! check_ajax_referer( 'login_action', 'login_field', false ) ) {
			wp_send_json_error( [ 
				'message' => esc_html__( 'Ön bellek sebebiyle doğrulama gerçekleştirilemedi, site yöneticisine başvurarak bu sayfanın ön bellekleğinin temizlenmesini veya ön belleklemeden muaf hale getirilmesini isteyiniz.', 'kanews' ) 
			] );
			return;
		}

		$username = isset( $_POST['username'] ) ? trim( sanitize_user( $_POST['username'] ) ) : '';
		$password = isset( $_POST['password'] ) ? $_POST['password'] : '';
		$remember = isset( $_POST['rememberme'] ) && $_POST['rememberme'] === '1';

		if ( empty( $username ) || empty( $password ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Kullanıcı adı ve şifre gereklidir!', 'kanews' ) ] );
			return;
		}

		$login_fields = [
			'user_login' => $username,
			'user_password' => $password,
			'remember' => $remember
		];

		$login_status = wp_signon( $login_fields, is_ssl() );

		if ( is_wp_error( $login_status ) ) {
			wp_send_json_error( [ 'message' => $login_status->get_error_message() ] );
			return;
		}

		wp_send_json_success( [ 'message' => esc_html__( 'Giriş başarılı, yönlendiriliyorsunuz..', 'kanews' ) ] );
	}

	/**
	 * Disable subscriber author archives
	 *
	 * @since 1.0.1
	 * @return void
	 */
	public function disable_author_page() {
		if ( ! is_author() ) {
			return;
		}

		global $wp_query;
		$author_id = isset( $wp_query->query_vars['author'] ) ? absint( $wp_query->query_vars['author'] ) : 0;
		
		if ( ! $author_id ) {
			return;
		}

		$user_info = get_userdata( $author_id );
		if ( ! $user_info || empty( $user_info->roles ) ) {
			return;
		}

		if ( in_array( 'subscriber', $user_info->roles, true ) ) {
			wp_redirect( home_url(), 301 );
			exit;
		}
	}

	/**
	 * Possibly redirect wp-login.php to custom account page
	 * 
	 * @return void
	 */
	public function possibly_redirect() {
		if ( ! kanews_get_option( 'wp-admin-redirect' ) ) {
			return;
		}

		$page = kanews_get_option( 'account-page' );
		if ( ! $page || ! kanews__get__status() ) {
			return;
		}

		global $pagenow;
		if ( 'wp-login.php' !== $pagenow ) {
			return;
		}

		// Allow specific actions
		$allowed_actions = [
			isset( $_POST['wp-submit'] ),
			( isset( $_GET['action'] ) && $_GET['action'] === 'logout' ),
			( isset( $_GET['checkemail'] ) && $_GET['checkemail'] === 'confirm' ),
			( isset( $_GET['checkemail'] ) && $_GET['checkemail'] === 'registered' ),
			( isset( $_GET['action'] ) && $_GET['action'] === 'rp' ),
			( isset( $_GET['action'] ) && $_GET['action'] === 'lostpassword' ),
			isset( $_GET['loginSocial'] ),
		];

		if ( in_array( true, $allowed_actions, true ) ) {
			return;
		}

		wp_redirect( get_page_link( $page ) );
		exit;
	}

	/**
	 * Save user profile fields from admin
	 * 
	 * @param int $user_id User ID
	 * @return void
	 */
	public function save_user_profile_fields( $user_id ) {
		if ( ! current_user_can( 'edit_user', $user_id ) ) {
			return;
		}

		$social_fields = [
			'facebook_profile',
			'twitter_profile',
			'instagram_profile',
			'linkedin_profile',
			'youtube_profile',
			'telegram_profile',
		];

		foreach ( $social_fields as $field ) {
			if ( isset( $_POST[ $field ] ) ) {
				update_user_meta( $user_id, $field, sanitize_text_field( $_POST[ $field ] ) );
			}
		}
	}

	/**
	 * Add user profile fields to admin
	 * 
	 * @param \WP_User $user User object
	 * @return void
	 */
	public function add_user_profile_fields( $user ) {
		if ( ! is_admin() ) {
			return;
		}
		?>
		<table class="form-table">
			<tr>
				<th><label for="facebook_profile"><?php printf( esc_html__( '%s Kullanıcı Adınız', 'kanews' ), 'Facebook' ); ?></label></th>
				<td>
					<input type="text" name="facebook_profile" value="<?php echo esc_attr( get_the_author_meta( 'facebook_profile', $user->ID ) ); ?>" class="regular-text" />
				</td>
			</tr>
			<tr>
				<th><label for="twitter_profile"><?php printf( esc_html__( '%s Kullanıcı Adınız', 'kanews' ), 'Twitter' ); ?></label></th>
				<td>
					<input type="text" name="twitter_profile" value="<?php echo esc_attr( get_the_author_meta( 'twitter_profile', $user->ID ) ); ?>" class="regular-text" />
				</td>
			</tr>
			<tr>
				<th><label for="instagram_profile"><?php printf( esc_html__( '%s Kullanıcı Adınız', 'kanews' ), 'Instagram' ); ?></label></th>
				<td>
					<input type="text" name="instagram_profile" value="<?php echo esc_attr( get_the_author_meta( 'instagram_profile', $user->ID ) ); ?>" class="regular-text" />
				</td>
			</tr>
			<tr>
				<th><label for="linkedin_profile"><?php printf( esc_html__( '%s Kullanıcı Adınız', 'kanews' ), 'Linkedin' ); ?></label></th>
				<td>
					<input type="text" name="linkedin_profile" value="<?php echo esc_attr( get_the_author_meta( 'linkedin_profile', $user->ID ) ); ?>" class="regular-text" />
				</td>
			</tr>
			<tr>
				<th><label for="youtube_profile"><?php printf( esc_html__( '%s Kanal idsi', 'kanews' ), 'Youtube' ); ?></label></th>
				<td>
					<input type="text" name="youtube_profile" value="<?php echo esc_attr( get_the_author_meta( 'youtube_profile', $user->ID ) ); ?>" class="regular-text" />
				</td>
			</tr>
			<tr>
				<th><label for="telegram_profile"><?php printf( esc_html__( '%s Kullanıcı Adınız', 'kanews' ), 'Telegram' ); ?></label></th>
				<td>
					<input type="text" name="telegram_profile" value="<?php echo esc_attr( get_the_author_meta( 'telegram_profile', $user->ID ) ); ?>" class="regular-text" />
				</td>
			</tr>
		</table>
		<?php
	}

}
