<?php

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


/**
 * Class Walker_Classified_Categories that extends WordPress class Walker_Category
 *
 * @class Walker_Classified_Categories
 * @package DateBook/Classes
 * @author Pagick Themes
 */
class Walker_Classified_Categories extends Walker_Category {
	
	var $get_term_slug;

    function __construct($get_term_slug) {

        $this->get_term_slug = $get_term_slug;
    }
	
    function start_lvl(&$output, $depth = 1, $args = array()) {  
        $output .= "\n<ul class=\"nav nav-pills mt-5 mb-1\">\n";  
    }  

    function end_lvl(&$output, $depth = 0, $args = array()) {  
        $output .= "</ul>\n";  
    }  

    function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
		
		if($this->get_term_slug == $item->slug) { $selected_term = ' active'; } else { $selected_term = ''; }

        $output .= '<li class="nav-item"><a class="nav-link' . $selected_term . '" href="' . esc_url( get_category_link( $item->term_id ) ) . '" title="' . esc_attr( $item->name ) . '">' . esc_attr( $item->name ) . ' <span class="badge badge-light shadow-none ml-1">' . esc_attr($item->count) . '</span>';
    }  

    function end_el(&$output, $item, $depth = 0, $args = array()) {  
        $output .= "</a></li>\n";  
    }  
}


/**
 * Class DateBook_Classifieds_Page
 *
 * @class DateBook_Classifieds_Page
 * @package DateBook/Classes
 * @author Pagick Themes
 */
class DateBook_Classifieds_Page {


	/**
	 * Hook actions and filters.
	 * 
	 * @since 1.0
	 * @access public
	 */
	public static function init() {

		add_action( 'datebook_show_classifieds', array( __CLASS__, 'show_classifieds_page' ) );
		add_shortcode( 'datebook_all_classifieds', array( __CLASS__, 'return_classifieds_page' ) );

		add_action( 'datebook_single_classifieds', array( __CLASS__, 'show_single_classifieds' ) );

		add_shortcode( 'datebook_classified_title', array( __CLASS__, 'return_classified_title' ) );
		add_shortcode( 'datebook_classified_meta', array( __CLASS__, 'return_classified_meta' ) );
		add_shortcode( 'datebook_classified_content', array( __CLASS__, 'return_classified_content' ) );
		add_shortcode( 'datebook_classified_profile', array( __CLASS__, 'return_classified_profile' ) );

	}
	

	/**
	 * Send message to Administrator
	 *
	 * @access private
	 * @return void
	 */
	private static function send_message_to_profile() {

		if (defined('DATEBOOK_CURRENT_USER_ID') && is_numeric(DATEBOOK_CURRENT_USER_ID)) {
			$current_user_id = DATEBOOK_CURRENT_USER_ID;
		} else {
			global $current_user;
			wp_get_current_user();
			$current_user_id = DateBook_Utilities::datebook_replace_user_by_admin($current_user->ID, 1);
		}

		$currentauth = get_userdata($current_user_id);

		// Someone sends a message to another user
		if (isset($_POST['action']) && $_POST['action'] == 'contacting') {

			if ($_POST['emails']) { $datebook_alert_error += 1; }

			if (is_user_logged_in()) {
				$contacting_name = $currentauth->display_name;
				$contacting_email = $currentauth->user_email;
			} else {
				$contacting_name = sanitize_text_field(wp_strip_all_tags($_POST['contacting_name']));
				if (!$contacting_name) {
					$datebook_alert_error += 1;
					$datebook_alert_error_text .= esc_html__( 'Your name is missing', 'datebook' );
				}

				$contacting_email = sanitize_email($_POST['contacting_email']);
				if ($contacting_email) {
					if ( !is_email($contacting_email) ) {
						$datebook_alert_error += 1;
						$datebook_alert_error_text .= esc_html__( 'Your email address seems to be wrong', 'datebook' );
					}
				} else {
					$datebook_alert_error += 1;
					$datebook_alert_error_text .= esc_html__( 'Your email is missing', 'datebook' );
				}
				
			}

			$contacting_text = wp_strip_all_tags($_POST['contacting_text']);
			if (!$contacting_text) {
				$datebook_alert_error += 1;
				$datebook_alert_error_text .= esc_html__( 'You need to write a message', 'datebook' );
			}

			if (!isset($datebook_alert_error) && $datebook_alert_error <= 0) {

				$select_email_template = 'reply_to_classifieds_to_profile';
				include DateBook_Template_Loader::locate( 'misc/email-templates' );

				$datebook_mail = DateBook_Utilities::datebook_email_send($contacting_name, $contacting_email, get_the_author_meta(user_email), esc_html__( 'Contact message from', 'datebook' ) . ' ' . of_get_option('email_sitename'), $body);

				unset($contacting_name, $contacting_email, $contacting_text, $body);

				$alert_success = 1;
				$alert_success_text = esc_html__( 'Your message has been sent', 'datebook' );

			}
		}
	}


	/**
	 * Return classified ads on classifieds page
	 *
	 * @access public
	 * @return void
	 */
	public static function return_classifieds_page() {
		
		global $datebook_field_titles;
		set_query_var( 'datebook_field_titles', $datebook_field_titles );

		// display the Edit Profile form
		return DateBook_Template_Loader::load( 'classifieds/classifieds-list' );
		
	}


	/**
	 * Show classified ads on classifieds page
	 *
	 * @access public
	 * @return void
	 */
	public static function show_classifieds_page() {

		echo DateBook_Template_Loader::load( 'classifieds/page-classifieds' );

	}


	/**
	 * Return Classified title - Shortcode
	 *
	 * @access public
	 * @return void
	 */
	public static function return_classified_title() {

		$classified = DateBook_Utilities::detect_post_slug(DATEBOOK_CLASSIFIEDS_TYPE);

		$classified_name = isset($classified->post_title) ? $classified->post_title : esc_html__( 'Classified Title', 'datebook' );

		return $classified_name;

	}


	/**
	 * Return Classified meta data (date, category) - Shortcode
	 *
	 * @access public
	 * @return void
	 */
	public static function return_classified_meta($atts = array()) {

		$classified = DateBook_Utilities::detect_post_slug(DATEBOOK_CLASSIFIEDS_TYPE);
		
		$is_shortcode = !empty($atts) && is_array($atts) ? 1 : 0;
		$shortcode_date = isset($atts['date']) ? $atts['date'] : 1; // 0, 1
		$shortcode_subject = isset($atts['subject']) ? $atts['subject'] : 1; // 0, 1
		$shortcode_order = isset($atts['metaorder']) ? $atts['metaorder'] : 0; // 0, 1
		
		$classified_date_out = $classified_category_out = '';
		if($shortcode_date == 1){
			$classified_date = isset($classified->post_date) ? $classified->post_date : date( 'Y-m-d H:i:s');
			$classified_date_out = esc_html__( 'Placed', 'datebook' ) . ': ' . DateBook_Utilities::datebook_date_i18n(2, $classified_date);
		}
		
		$classified_category = '';
		
		if($shortcode_subject == 1){

		$categories = get_the_terms( $classified->ID, DATEBOOK_CLASSIFIEDS_TAX );
		
		if(!empty($categories) && is_array($categories)){

			$i = 1;

			foreach( $categories as $category ) {
				$classified_category .= $category->name;
				$classified_category .= ($i < count($categories)) ? ', ' : '';
				// Increment counter
				$i++;
			}
		
		} else {
			
			$classified_category = esc_html__( 'undefined', 'datebook' );
			
		}
		
		$classified_category_out = esc_html__( 'Subject', 'datebook' ) . ': ' . $classified_category;
		
		}
		
		$classified_separate = ($shortcode_date == 1 && $shortcode_subject == 1) ? ' | ' : '';

		if($shortcode_order == 1){

			$classified_meta = $classified_category_out . $classified_separate . $classified_date_out;

		} else {

			$classified_meta = $classified_date_out . $classified_separate . $classified_category_out;

		}

		return $classified_meta;

	}


	/**
	 * Return Classified title - Shortcode
	 *
	 * @access public
	 * @return void
	 */
	public static function return_classified_content() {

		$profile = DateBook_Utilities::detect_post_slug(DATEBOOK_CLASSIFIEDS_TYPE);
		
		$profile_id = isset($profile->ID) ? $profile->ID : 0;
		
		$layout = '';
		
		if($profile_id > 1){

			$aboutyou = isset($profile->post_content) ? nl2br($profile->post_content) : '';

			$layout .= esc_html($aboutyou);

		} else {

			$layout .= 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ultrices dui eu lectus fringilla non pellentesque magna egestas. Suspendisse potenti. Vivamus at magna libero. Donec et purus nunc, eu aliquam diam. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica.';

		}

		return $layout;

	}


	/**
	 * Return Classified Profile - Shortcode
	 *
	 * @access public
	 * @return void
	 */
	public static function return_classified_profile($atts = array()) {

		$post = DateBook_Utilities::detect_post_slug(DATEBOOK_CLASSIFIEDS_TYPE);
		
		$is_shortcode = !empty($atts) && is_array($atts) ? 1 : 0;
		$shortcode_image = isset($atts['image']) ? $atts['image'] : 1; // 0, 1
		$shortcode_age = isset($atts['age']) ? $atts['age'] : 1; // 0, 1
		$shortcode_sex = isset($atts['sex']) ? $atts['sex'] : 0; // 0, 1
		$shortcode_gender = isset($atts['gender']) ? $atts['gender'] : 0; // 0, 1
		$shortcode_location = isset($atts['location']) ? $atts['location'] : 1; // 0, 1
		$shortcode_contact_button = isset($atts['contact_button']) ? $atts['contact_button'] : 1; // 0, 1

		$post_id = isset($post->ID) ? $post->ID : 0;
		$classified_user_id = $post->post_author;

		$layout = '';
		
		// Check if Retina enabled in Theme Options
		$enable_retina_images = of_get_option('enable_retina_images') ? 1 : 0;


		if($post_id > 1){
			
			global $datebook_field_titles;
			
			set_query_var( 'datebook_field_titles', $datebook_field_titles );
	
			$datebook_field_titles = get_query_var( 'datebook_field_titles' );
			if ( is_array( $datebook_field_titles ) ) { extract($datebook_field_titles); }

			$profile_postid = get_user_meta( $classified_user_id, 'profile_postid', true );
			$profile_data = get_post($profile_postid);

			if (!empty($profile_data->ID) && $profile_data->ID > 1) {

				$profile_id = $profile_data->ID;
				$profile_title = $profile_data->post_title;
				$profile_status = $profile_data->post_status;

				$get_profile_data = get_post_meta($profile_id, 'profile_personal_data', true);
				$datebook_get_data = !empty($get_profile_data) ? $get_profile_data : array();

				$country = $region = $city = '';

				if(isset($datebook_get_data['city'])){

					$term_data = DateBook_Utilities::datebook_get_term_by( 'id', $datebook_get_data['city'] );
					$city = isset($term_data->city) ? $term_data->city : '';
					$country = isset($term_data->country) ? $term_data->country : '';

				}

				$age = isset($datebook_get_data['birthday']) && !empty($datebook_get_data['birthday']) ? floor((time() - strtotime($datebook_get_data['birthday']))/31556926) . ' ' . esc_html__( 'years old', 'datebook' ) : '';
				$gender = isset($datebook_get_data['gender']) ? $datebook_get_data['gender'] : 0;
				$sexualorientation = isset($datebook_get_data['sexualorientation']) ? $datebook_get_data['sexualorientation'] : '';

				if ($gender == 1) {

					$gender_icon = 'fa fa-venus fa-lg';

				} else if ($gender == 2) {

					$gender_icon = 'fa fa-mars fa-lg';

				} else {

					$gender_icon = 'fa fa-user fa-lg';

				}

			}

			if (!empty($profile_id) && $profile_id > 1 && $profile_status == 'publish') {

				if($shortcode_image == 1){

					$thumbnail_url = DateBook_Utilities::datebook_profile_thumbnail($profile_id, 'image_small', $gender, true, $datebook_get_data);

					$layout .= '<a class="float-left mr-3 mb-4" href="' . esc_url(get_permalink($profile_id)) . '"><img class="rounded-circle shadow" src="' . esc_url( $thumbnail_url['img_full_url'] ) . '" width="' . esc_attr( $thumbnail_url['width'] ) . '" height="' . esc_attr( $thumbnail_url['height'] ) . '" alt="' . esc_attr($profile_title) . '"';
					
					if($enable_retina_images == 1) {
						$layout .= ' data-rjs="2"';
					}
					
					$layout .= '/></a>';
				}
				$layout .= '<h5 class="mt-0 mb-2"><a href="' . esc_url(get_permalink($profile_id)) . '">' . esc_attr($profile_title) . '</a></h5>';
				$layout .= '<p>';

				if($shortcode_age == 1){
					$layout .= esc_attr($age);
				}
				
				$show_sexual_orientation = (DateBook_Utilities::datebook_show_field('sexualorientation', 1) && (of_get_option('sexual_orientation_allowed') != '' || of_get_option('sexual_orientation_allowed_other_' . DATEBOOK_WPLANG) != '')) ? 1 : 0;
				
				if ($show_sexual_orientation == 1) {
					if($shortcode_sex == 1){
						$sexualorientation = $sexualorientation == 2 && isset($gender) && $gender > 0 ? $gender.$sexualorientation . '00' : $sexualorientation;
						if(isset($datebook_sexualorientation_titles[$sexualorientation])){
							$layout .= ' <span class="badge badge-info">' . esc_html__( $datebook_sexualorientation_titles[$sexualorientation], 'datebook' ) . '</span>';
						}
					}
				}

				if($shortcode_gender == 1){
					if(isset($datebook_gender_titles[$gender])){
						$layout .= ' <span title="' . esc_html__( $datebook_gender_titles[$gender], 'datebook' ) . '"><i class="' . esc_attr($gender_icon) . '"></i></span>';
					}
				}

				$layout .= '</p>';
				
				if($shortcode_location == 1){
					$layout .= '<p>';
				
					if (isset($city)) {
						$layout .= esc_attr($city);
					}

					if (isset($city) && isset($country)) {
						$layout .= ', ';
					}

					if (isset($country)) {
						$layout .= esc_attr($country);
					}

					$layout .= '</p>';
				}
				
				if($shortcode_contact_button == 1){
					$layout .= '<div id="datebook-contactpanel">';
				
					if (of_get_option('contact_method') == '1') {
						
						$open_message_link = add_query_arg( array(
							'action' => 'read',
							'sid' => absint($classified_user_id)
						), get_permalink(of_get_option('my_messages_page')) );

						$layout .= '<a id="datebook-chatpopup" class="btn btn-primary btn-message" href="' . esc_url($open_message_link) . '" onclick="return false;"><i class="fa fa-envelope mr-2"></i> ' . esc_html__( 'Write a message', 'datebook' ) . '</a>';

					} else {

						$layout .= '<div id="datebook-emailpopup" class="btn-group">';
						$layout .= '<button data-toggle="dropdown" class="btn btn-primary btn-message" type="button"><i class="fa fa-envelope"></i> ' . esc_html__( 'Write a message', 'datebook' ) . '</button>';
						$layout .= '<button data-toggle="dropdown" class="btn btn-secondary btn-message dropdown-toggle" type="button">';

						if (isset($datebook_alert_error) && $_POST['action'] == "contacting") {
							$layout .= '<span>&#x25B2;</span>';
						} else {
							$layout .= '<span>&#x25BC;</span>';
						}

						$layout .= '</button>';

						$layout .= '</div>';

						include DateBook_Template_Loader::locate( 'profile/profile-contact-form' );

					}

					$layout .= '</div>';

				}

			}

		} else {

			$show_comma = $show_sexualorientation = $show_gender = 0;

			if($shortcode_image == 1){

				$thumbnail_url = DateBook_Utilities::datebook_profile_thumbnail($profile_id, 'image_small', $gender, true, $datebook_get_data);

				$layout .= '<img class="float-left mr-3 mb-4 rounded-circle shadow" src="' . esc_url( $thumbnail_url['img_full_url'] ) . '" width="' . esc_attr( $thumbnail_url['width'] ) . '" height="' . esc_attr( $thumbnail_url['height'] ) . '" alt="' . esc_html__( 'Profile Title', 'datebook' ) . '"';
					
				if($enable_retina_images == 1) {
					$layout .= ' data-rjs="2"';
				}

				$layout .= '/></a>';
			}
			$layout .= '<h5 class="mt-0 mb-2">' . esc_html__( 'Profile Title', 'datebook' ) . '</h5>';
			$layout .= '<p>';

			if (DateBook_Utilities::datebook_show_field('sexualorientation', 1) && (of_get_option('sexual_orientation_allowed') != '' || of_get_option('sexual_orientation_allowed_other_' . DATEBOOK_WPLANG) != '') && isset($datebook_get_data['sexualorientation'])) {

				$show_sexualorientation = 1;

			}

			if (DateBook_Utilities::datebook_show_field('gender', 1) && (of_get_option('gender_allowed') != '' || of_get_option('gender_allowed_other_' . DATEBOOK_WPLANG) != '')) {

				$show_gender = 1;

			}
			
			if (DateBook_Utilities::datebook_show_field('birthdate', 1)) {

				if($shortcode_age == 1){

					$layout .= esc_html__( 'Age', 'datebook' );

					$show_comma = 1;

				}

				if ($show_comma == 1) {
					$layout .= ', ';
				}

				$layout .= esc_html__( 'Zodiac', 'datebook' );

				$show_comma = 1;

			}

			if($shortcode_sex == 1){

				if ($show_comma == 1) {
					$layout .= ', ';
				}

				$layout .= esc_html__( 'Sex', 'datebook' );

				$show_comma = 1;

			}
			
			if($shortcode_gender == 1){
				if ($show_comma == 1) {
					$layout .= ', ';
				}

				$layout .= esc_html__( 'Gender', 'datebook' );

				$show_comma = 1;

			}

			$layout .= '</p>';

			if (DateBook_Utilities::datebook_show_field('countrycity', 1)) {
				if($shortcode_location == 1){

					$layout .= '<p class="mb-3">';
					$layout .= esc_html__( 'City', 'datebook' );
					$layout .= ', ';
					$layout .= esc_html__( 'Country', 'datebook' );
					$layout .= '</p>';

				}
			}

			if($shortcode_contact_button == 1){
				$layout .= '<div id="datebook-contactpanel">';

				$layout .= '<a id="datebook-chatpopup" class="btn btn-primary btn-message" href="" onclick="return false;"><i class="fa fa-envelope mr-2"></i> ' . esc_html__( 'Write a message', 'datebook' ) . '</a>';

				$layout .= '</div>';

			}

		}

		return $layout;

	}


	/**
	 * Return classified ads on classifieds page
	 *
	 * @access public
	 * @return void
	 */
	public static function return_single_classifieds() {
		
		if (isset($_POST['action']) && $_POST['action'] == 'contacting') {
			
			self::send_message_to_profile();
			
		}

		// display a Single Classified page
		return DateBook_Template_Loader::load( 'classifieds/single-classifieds' );
		
	}


	/**
	 * Show classified ads on classifieds page
	 *
	 * @access public
	 * @return void
	 */
	public static function show_single_classifieds() {
		
		// display the Edit Profile form
		echo self::return_single_classifieds();
		
	}
	

}

DateBook_Classifieds_Page::init();