<?php

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

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

	private static $datebook_options = null;


    public function __construct($datebook_options_array) {

		self::$datebook_options = $datebook_options_array;

		self::init();

	}


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

		add_action( 'datebook_edit_classifieds', array( __CLASS__, 'process_edit_classifieds' ) );

	}


	/**
	 * Validate all input data
	 *
	 * @access private
	 */
	private static function validate_form() {
		
		global $datebook_form_error;
	
		$update_data = array();

		// instantiate the class
		$datebook_form_error = new WP_Error;

		if (isset($_POST['subject']) && $_POST['subject'] > 0) {
			$update_data['subject'] = absint($_POST['subject']);
		} else {
			
			$args = array(
				'name'					=> 'subject',
				'hide_empty'			=> 0,
				'use_desc_for_title'	=> 0,
				'hierarchical'			=> true,
				'number'				=> NULL,
				'echo'					=> 0,
				'depth'					=> 1,
				'current_category'		=> 0,
				'hide_if_empty'			=> true,
				'pad_counts'			=> 0,
				'taxonomy'				=> DATEBOOK_CLASSIFIEDS_TAX
			);

			if(!empty(wp_dropdown_categories($args))){
				$datebook_form_error->add( 'subject', esc_html__( 'Select a subject', 'datebook' ), 'has-error' );
			} else {
				$update_data['subject'] = 0;
			}
		}

		if (isset($_POST['title']) && strlen($_POST['title']) > 10) {
			$update_data['title'] = sanitize_text_field($_POST['title']);
		} else {			
			$datebook_form_error->add( 'title', esc_html__( 'Write a title for the classified', 'datebook' ), 'has-error' );
		}

		if (!empty($_POST['description']) && strlen($_POST['description']) > 10) {
			$update_data['description'] = wp_trim_words(sanitize_text_field(wp_strip_all_tags($_POST['description'])), 1000, '');
		} else {
			$datebook_form_error->add( 'description', esc_html__( 'Write a description for the classified', 'datebook' ), 'has-error' );
		}

		return $update_data;

	}


	/**
	 * Update all data
	 *
	 * @access private
	 * @return void
	 */
	private static function update_data() {

		// Make global    
		global $datebook_form_error, $datebook_alert_error, $datebook_alert_text;

		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);
		}

		$profile_id = get_user_meta( $current_user_id, 'profile_postid', true );
		$profile_post = get_post($profile_id);
		$profile_name = $profile_post->post_title;

		// If any field is left empty, add the error message to the error object
		if ($profile_post->post_author == $current_user_id || is_super_admin()) {

			$options = array();

			// Check if profile is active otherwise do not allow to post a classified
			if ($profile_post->post_status == 'publish'){

				$get_classified_id = (isset($_POST['cid']) && $_POST['cid'] > 0) ? absint($_POST['cid']) : 0;
				$classified = get_post($get_classified_id);

				// If any field is left empty, add the error message to the error object
				if ($get_classified_id > 0 && isset($classified->post_author) && $classified->post_author != $current_user_id) {

					$options = array('status' => 'alert alert-danger', 'message' => esc_html__( 'You are not allowed to edit this classified', 'datebook' ));

					// display alert message
					echo DateBook_Template_Loader::load( 'misc/alert', $options );

				} else {

					// validate the Profile form input
					$datebook_get_data = self::validate_form();

					// Ensure WP_Error object ($datebook_form_error) contains no error
					if (count($datebook_form_error->get_error_messages()) < 1){

						$datebook_get_data['title'] = DateBook_Utilities::datebook_word_filter($datebook_get_data['title']);
						$datebook_get_data['description'] = DateBook_Utilities::datebook_word_filter($datebook_get_data['description']);

						if ($get_classified_id > 0) {

							// Approve edited classifieds automatically
							$approve_post = self::$datebook_options['approve_edited_classifieds'] ? 'publish' : 'private';

							// Create post object
							$post_classifieds = array(
								'ID' => $get_classified_id,
								'post_title' => $datebook_get_data['title'],
								'post_content' => $datebook_get_data['description'],
								'post_status' => $approve_post,
								'post_type' => DATEBOOK_CLASSIFIEDS_TYPE
							);
							wp_update_post( $post_classifieds );
							$classified_id = $get_classified_id;

						} else {

							// Approve newly submitted classifieds automatically
							$approve_post = self::$datebook_options['approve_new_classifieds'] ? 'publish' : 'private';

							$classifieds_cat_id = term_exists( 'Classifieds', 'category' );

							if (!$classifieds_cat_id) {
								$arg = array('description' => 'Classifieds');
								wp_insert_term('Classifieds', 'category', $arg);
								$classifieds_cat_id = term_exists( 'Classifieds', "category" );
							}

							$classifieds_cat_id = $classifieds_cat_id['term_id'];

							// Create post object
							$post_classifieds = array(
								'post_title' => $datebook_get_data['title'],
								'post_content' => $datebook_get_data['description'],
								'post_status' => $approve_post,
								'post_category' => array($classifieds_cat_id),
								'post_author' => $current_user_id,
								'post_parent' => $profile_id,
								'post_type' => DATEBOOK_CLASSIFIEDS_TYPE,
								'ping_status' => 'closed'
							);

							// Insert the post into the database
							$classified_id = wp_insert_post( $post_classifieds );

							update_post_meta($classified_id, 'upload_folder', time().rand(1,999));

						}

						if(isset($datebook_get_data['subject'])){
							wp_set_object_terms($classified_id, $datebook_get_data['subject'], DATEBOOK_CLASSIFIEDS_TAX);
						}

						update_post_meta($classified_id, 'profile_classifieds_id', absint($profile_id));
						
						$profile_get_permalink = get_permalink($classified_id);

						$approval = array('title' => '', 'message' => '', 'class' => 'alert alert-success');

						if($approve_post == 'private'){

							$approval = array('title' => esc_html__('Classified review pending', 'datebook' ), 'message' => esc_html__(' and is waiting for approval', 'datebook' ), 'class' => 'alert alert-warning');

						}

						if ($get_classified_id > 0) {

							$options = array('status' => $approval['class'], 'message' => esc_html__( 'Classified ad has been updated', 'datebook' ) . $approval['message'], 'title' => $approval['title']);

							// display alert message
							echo DateBook_Template_Loader::load( 'misc/alert', $options );
							
							$select_email_template = 'classified_changed_to_admin';
							$subject_in_email = esc_html__('Classified ad has been edited by', 'datebook') . ': ' . $profile_name;

						} else {

							$options = array('status' => $approval['class'], 'message' => esc_html__( 'Classified ad has been added', 'datebook' ) . $approval['message'], 'title' => $approval['title']);

							// display alert message
							echo DateBook_Template_Loader::load( 'misc/alert', $options );
							
							$select_email_template = 'classified_added_to_admin';
							$subject_in_email = esc_html__('Classified ad has been added by', 'datebook') . ': ' . $profile_name;

						}

						$_POST['action'] = '';
						
						// Let's send notification to administrator about classified update
						if(isset(self::$datebook_options['receive_email_on_classified_update']) && self::$datebook_options['receive_email_on_classified_update'] == '1'){

							$currentauth = get_userdata($current_user_id);
							$user_login = $currentauth->user_login;
							$emailaddress = $currentauth->user_email;

							include DateBook_Template_Loader::locate( 'misc/email-templates' );

							$send_to_this_email = self::$datebook_options['email_website'] ? self::$datebook_options['email_website'] : get_bloginfo('admin_email');

							$datebook_mail = DateBook_Utilities::datebook_email_send('', '', $send_to_this_email, $subject_in_email, $body);

						}

					} else {

						echo '<div class="alert alert-danger">' . esc_html__( 'Please, fill in all required fields colored red', 'datebook' ) . '</div>';

						$datebook_alert_error = array();
						$datebook_alert_text = array();

						foreach($datebook_form_error->get_error_codes() as $code){

							$datebook_alert_error[$code] = $datebook_form_error->get_error_data($code);
							$datebook_alert_text[$code] = $datebook_form_error->get_error_message($code);

						}
					}
				}

			} else {

				$options = array('status' => 'alert alert-danger', 'message' => esc_html__( 'You must first activate your profile in order to post an ad', 'datebook' ));

				// display alert message
				echo DateBook_Template_Loader::load( 'misc/alert', $options );

			}
		}
	}


	/**
	 * Delete classified ad
	 *
	 * @access private
	 * @return void
	 */
	private static function datebook_delete_classified() {

		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);
		}

		$classified_id = isset($_GET['cid']) ? absint($_GET['cid']) : 0;

		// Delete classified ad
		if (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['confirm']) && $_GET['confirm'] == 'yes' && isset($_GET['cid']) && $_GET['cid'] > 0) {
			
			$classified = get_post($classified_id);
			$classified_author = $classified->post_author;
					
			if ($classified_author == $current_user_id || is_super_admin()) {

				wp_delete_post($classified_id, true);

				echo '<div class="alert alert-success">'.esc_html__( 'Classified ad has been deleted', 'datebook' ).'</div>';

			}

		} else if (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['cid']) && $_GET['cid'] > 0) {

			$my_classifieds_link_args = get_permalink(self::$datebook_options['my_classifieds_page']);

			$my_classifieds_link = add_query_arg( array(
				'action' => 'delete',
				'confirm' => 'yes',
				'cid' => $classified_id
			), $my_classifieds_link_args );

			echo '<div class="alert alert-danger alert-dismissable">';
			echo '<h4 class="alert-heading">' . esc_html__( 'Delete the classified?', 'datebook' ) . '</h4>';
			echo '<p>' . esc_html__( 'Do you really want to delete the classified', 'datebook' ).' #' . $classified_id . '? ' . esc_html__( 'This action cannot be undone', 'datebook' ) . '.</p>';

			echo '<a href="' . esc_url($my_classifieds_link_args) . '" class="btn btn-danger">' . esc_html__( 'Yes, delete!', 'datebook' ).'</a> <a href="' . esc_url($my_classifieds_link) . '" class="btn btn-link">' . esc_html__( 'No, do not delete!', 'datebook' ) . '</a>';
			echo '</div>';

		}

	}


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

		$current_user_id = DATEBOOK_CURRENT_USER_ID;

		$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 .= "."; }
			
			if (is_user_logged_in()) {
				$from_contacting_name = $currentauth->display_name;
				$from_contacting_email = $currentauth->user_email;
			} else {
				$from_contacting_name = sanitize_text_field($_POST['contacting_name']);
				if (!$from_contacting_name) {
					$datebook_alert_error .= esc_html__( 'Your name is missing', 'datebook' )."<br />";
				}
				
				$from_contacting_email = sanitize_email($_POST['contacting_email']);
				if ($from_contacting_email) {
					if ( !is_email($from_contacting_email) ) {
						$datebook_alert_error .= esc_html__( 'Your email address seems to be wrong', 'datebook' )."<br />";
					}
				} else {
					$datebook_alert_error .= esc_html__( 'Your email is missing', 'datebook' )."<br />";
				}
			}
			
			$contacting_text = sanitize_text_field(wp_strip_all_tags($_POST['contacting_text']));
			if (!$contacting_text) {
				$datebook_alert_error .= esc_html__( 'You need to write a message', 'datebook' )."<br />";
			}
			
			if (!$datebook_alert_error) {
				
				// Put all data to an array
				$datebook_email_var = array(
					'select_email_template' => 'reply_to_classifieds_to_profile',
					'subject' => $subject_in_email,
					'profile_name' => get_the_author_meta(display_name),
					'profile_get_permalink' => get_permalink(get_the_ID())
				);

				set_query_var( 'datebook_email_var', $datebook_email_var );

				include DateBook_Template_Loader::locate( 'misc/email-templates' );


				$to_email = get_the_author_meta(user_email);
				$subject_in_email = esc_html__( 'Contact message from', 'datebook' ) . ' ' . self::$datebook_options['email_sitename'];

				$datebook_mail = DateBook_Utilities::datebook_email_send($from_contacting_name, $from_contacting_email, $to_email, $subject_in_email, $body);

				unset($from_contacting_name, $from_contacting_email, $contacting_text, $body);
				$alert_success = esc_html__( 'Your message has been sent', 'datebook' );
			}
			
		}

	}


	/**
	 * Show Classified edit form and process all data
	 *
	 * @access public
	 * @return void
	 */
	public static function process_edit_classifieds() {

		if (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['cid']) && $_GET['cid'] > 0) {
			
			// Delete profile account
			self::datebook_delete_classified();
				
		}

		// update all the input data
		if (isset($_POST['action']) && $_POST['action'] == 'addclassifieds') {
			self::update_data();
		}


		if (
		(isset($_POST['action']) && $_POST['action'] == 'addclassifieds') || 
		(isset($_GET['action']) && $_GET['action'] == 'newclassified') || 
		(isset($_GET['action']) && $_GET['action'] == 'edit' && isset($_GET['cid']) && $_GET['cid'] > 0)) {

			// display the Edit Profile form
			echo DateBook_Template_Loader::load( 'profile/profile-classifieds-form' );

		} else {

			// display the Edit Profile form
			echo DateBook_Template_Loader::load( 'profile/profile-classifieds' );

		}
		
	}



}

//DateBook_Profile_Classifieds::init();
$dateBook_profile_classifieds = new DateBook_Profile_Classifieds($datebook_options_array);