<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit( 'Direct script access denied.' );
}
/**
 * jws car form handler.
 *
 * @author  PotenzaGlobalSolutions
 * @package jws
 * @version 1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Handle frontend forms.
 *
 * @author PotenzaGlobalSolutions
 */
class JWS_Cars_Form_Handler {

	/**
	 * Hook in methods.
	 */
	public static function init() {
		// add_action( 'wp_loaded', array( __CLASS__, 'process_car_save' ), 20 );.
	}

	/**
	 * Get logged in user id.
	 */
	public static function get_user_id() {
		if ( is_user_logged_in() ) {
			return get_current_user_id();
		}
		return false;
	}

	/**
	 * Save car save [ insert / update ]
	 */
	public static function process_car_save() {
		global $jws_option;
		if ( empty( $_POST['action'] ) || 'jws_save_car' !== $_POST['action'] ) {
			return array( 'status' => 2 );
		}

		$user = self::get_user_id();
		
		if ( isset( $_POST['jws-car-form-nonce-field'] ) ) {
			if ( empty( $_POST['jws-car-form-nonce-field'] ) || ! wp_verify_nonce( $_POST['jws-car-form-nonce-field'], 'jws-car-form' ) ) {
				return array( 'status' => 2 );
			}
		}

		nocache_headers();
		$car_data = array();
		$errors   = new WP_Error();

		$car_data = $_POST['car_data'];
         // car insert limit exceeded.
		$validateinsert = self::validate_car_insert();
		if ( 2 == $validateinsert['status'] ) {
			return array(
				'status' => 5,
				'limit'  => $validateinsert['limit'],
			); // car insert limit exceeded.
		} elseif ( 3 == $validateinsert['status'] ) {
			return array(
				'status' => 6,
				'limit'  => $validateinsert['limit'],
			); // car img upload limit exceeded.
		}
	
		/**
		 * Filters the array of vehicle required fields.
		 *
		 * @since 1.0
		 * @param array      $required_fields   Array of fields to put in required fields in add car form(server side validation).
		 * @visible           true
		 */
		$required_fields = apply_filters(
			'jws_car_required_fields',
			array(
				'year'          => esc_html__( 'Year', 'idealauto' ),
				'make'          => esc_html__( 'Make', 'idealauto' ),
				'model'         => esc_html__( 'Model', 'idealauto' ),
				'regular_price' => esc_html__( 'Regular Price', 'idealauto' ),
                'condition' => esc_html__( 'Condition', 'idealauto' ),
                'regular_price' => esc_html__( 'Regular Price', 'idealauto' ),
                'title'=> esc_html__( 'Listing Title', 'idealauto' ),
			)
		);

		// check required fields.
		$val_err_fields = array();
		foreach ( $required_fields as $field_key => $field_name ) {
			if ( empty( $car_data[ $field_key ] ) ) {
				$val_err_fields[] = ucfirst( str_replace( '_', ' ', $field_key ) );
			}
		}
		if ( ! empty( $val_err_fields ) ) {
			return array(
				'status'     => 4,
				'err_fields' => $val_err_fields,
			);
		}
        if ( ! $user ) { // return if not logged in.
			return array( 'status' => 7 );
		}
		// Attributes.
		if ( ! empty( $car_data ) ) {

			$post_status = 'pending';
			if ( isset( $jws_option['jws_auto_publish'] ) && $jws_option['jws_auto_publish'] ) {
				$post_status = 'publish';
			}

			$car_title  = jws_clean( $car_data['title'] ); // car title.
			$taxonomies = jws_get_cars_taxonomy();

			if ( isset( $_POST['jws_action_car_id'] ) && ! empty( $_POST['jws_action_car_id'] ) ) { // Update car.
				$car_id = jws_clean( $_POST['jws_action_car_id'] );
				$car_id = wp_update_post(
					array(
						'ID'         => $car_id,
						'post_title' => $car_title,
					)
				);
			} else { // Insert car.
				$car_id = wp_insert_post(
					array(
						'post_status' => $post_status,
						'post_type'   => 'cars',
						'post_title'  => $car_title,
					)
				);
			}

			// checkbox fields i.e. array('taxonomy'=> 'fieldname').
			$checkbox_fields = apply_filters(
				'jws_checkbox_fields',
				array(
					'car_features_options'      => 'car_features_options',
					'car_vehicle_review_stamps' => 'vehicle_review_stamps',
				)
			);
			$editor_fields   = apply_filters( 'jws_editor_fields', array( 'vehicle_overview', 'technical_specifications', 'general_information' ) );

			if ( ! is_wp_error( $car_id ) ) {

				// Add user name for this car post_content.
				update_post_meta( $car_id, 'jws_car_user', $user );
                update_post_meta( $car_id, 'car_status', '' );

				// enter empty data for check box fields if check box fields are not set.
				foreach ( $checkbox_fields as $tax => $c_field ) {
					if ( ! in_array( $c_field, $car_data ) ) {
						wp_set_object_terms( $car_id, array(), $tax, false );
                        update_post_meta( $car_id, $tax, '' );
					}
				}

				/**
				 * Filters vehicle post data submitted from front submission form.
				 *
				 * @since 1.0
				 * @param array       $car_data Array of vehicle data.
				 * @param int         $car_id   Vehicle ID.
				 * @visible           true
				 */
				$car_data = apply_filters( 'jws_custom_car_data', $car_data, $car_id );
				foreach ( $car_data as $field => $value ) {

					$field_taxonomy = 'car_' . $field;
					if ( in_array( $field_taxonomy, $taxonomies ) && ! in_array( $field, $checkbox_fields ) ) { // check for taxonomy fields.
						wp_set_object_terms( $car_id, jws_clean( $value ), $field_taxonomy, false );
					} elseif ( in_array( $field, $checkbox_fields ) ) { // checkbox fields.
						// Checkbox options input.
						$car_options = jws_clean( $value );
						if ( 'car_features_options' === $field ) {
							$field_taxonomy = 'car_features_options';

							// Code to add other options for features_and_options.
							if ( isset( $car_data['jws-other'] ) && ! empty( $car_data['jws-other'] ) && ! empty( $car_data['jws-other-opt'] ) ) {
								$fno_opts = explode( ',', jws_clean( $car_data['jws-other-opt'] ) );
								if ( ! empty( $fno_opts ) ) {
									foreach ( $fno_opts as $fno_opt ) {
										$car_options[] = trim( jws_clean( $fno_opt ) );
									}
								}
							}
                            $value = implode(',',$value);
							update_post_meta( $car_id, $field,$value );
                   
						}
                        
                       
                        
						wp_set_object_terms( $car_id, $car_options, $field_taxonomy, false );
					} elseif ( 'vehicle_location' === $field ) { // Variable car_location.
						if ( ! empty( $_POST['jws_lat'] ) && ! empty( $_POST['jws_lng'] ) ) {
							$location = array(
								'address' => jws_clean( $value ),
								'lng'     => jws_clean( $_POST['jws_lng'] ),
								'lat'     => jws_clean( $_POST['jws_lat'] ),
								'zoom'    => '17',
							);
							update_post_meta( $car_id, $field, $location );
						}
					}elseif ( 'video_link' === $field ) { // Variable car_location.
				            $value = array_filter($value);
							$value = implode(',',$value);
							update_post_meta( $car_id, $field, jws_clean( $value ) );
					
					}else {
						if ( in_array( $field, $editor_fields ) ) { // Do not sanitize text editor fields.
							update_post_meta( $car_id, $field, $value ); // echo '<pre>'; print_r($value);die();.
						} else {
							update_post_meta( $car_id, $field, jws_clean( $value ) );
						}
					}
				}
                
                                                

				// car excerpt save.
				if ( isset( $_POST['car_excerpt'] ) ) {
					$post_car_excerpt = array(
						'ID'           => $car_id,
						'post_excerpt' => $_POST['car_excerpt'],
					);
					wp_update_post( $post_car_excerpt );
				}

				// Send notification mail to admin about new car add.
				if ( isset( $_POST['jws_action_cadr_id'] ) ) { // if new car added [ donot send notification on update car ].
					// get site details.
					$site_title  = get_bloginfo( 'name' );
					$site_email  = get_bloginfo( 'admin_email' );
					$admin       = get_user_by( 'email', $site_email );
					$dealer_data = get_user_by( 'id', $user );

					// Send email notification.
					$subject  = esc_html__( 'New Vehicle Added!', 'idealauto' );
					$headers  = 'MIME-Version: 1.0' . "\r\n";
					$headers .= 'Content-type:text/html;charset=UTF-8' . "\r\n";
					$headers .= 'From: ' . $site_title . ' <' . $site_email . '>' . "\r\n";

					$car_data = array(
						'admin_name'   => $admin->user_login,
						'dealer_name'  => $dealer_data->user_login,
						'dealer_email' => $dealer_data->user_email,
						'mail_html'    => jws_get_html_mail_body( $car_id ),
					);
					// Mail to admin.
					ob_start();
				
					$admin_message = ob_get_contents();
					ob_end_clean();

					// send mail.
					try {
						jws_sv_ct3( $site_email, $subject, $admin_message, $headers );
					} catch ( Exception $e ) {
						jws_add_notice( $e->getMessage(), 'error' );
						return array( 'status' => 2 );
					}
				}

				return array(
                    'check' => $_FILES,
					'status'  => 1,
					'post_id' => $car_id,
				);
			} else {
				// There was an error in the car insertion.
				return array( 'status' => 2 );
			}
		} else {
			return array( 'status' => 2 );
		}
	}

	/**
	 * Function to upload car images and pdf
	 * return: attachment id if success and false if error
	 */
	public static function process_image_upload() {
		$sorted_img_list    = explode( ',', $_POST['file_attachments'] ); // img order.
		$car_id             = jws_clean( $_POST['car_id'] );
		$max_file_size      = apply_filters( 'jws_max_media_upload_size', 1048576 * 4 ); /* 4mb is highest media upload here */
		$imgs_size_error    = '';
		$files_not_uploaded = '';
        $loc = array();
		if ( isset( $_FILES ) && ! empty( $_FILES ) ) {
			$files_uploaded = false;
			foreach ( $_FILES as $field => $images ) {
	
				$car_attachments    = array();
				$files_not_uploaded = array();
				$imgs_size_error    = array();
                $gallery = array();
				// Allowed file types.
				switch ( $field ) {
					case 'window_sticker_file':
						$allowed_types = array( 'pdf' );
						break;
					default:
						$allowed_types = array( 'jpg', 'jpeg', 'png', 'gif' );
				}
                
				if ( is_array( $images['name'] ) ) {
				   
					foreach ( $images['name'] as $key => $value ) {

						// do not upload if size exceeds.
						if ( $images['size'][ $key ] > $max_file_size ) {
							$imgs_size_error[] = $images['name'][ $key ];

							// also remove image from sorted array.
							$ordered_arr_key = array_search( $value, $sorted_img_list );
							if ( $ordered_arr_key ) {
								unset( $sorted_img_list[ $ordered_arr_key ] );
							}
							continue;
						}
						$file_array    = array(
							'name'     => $images['name'][ $key ],
							'type'     => $images['type'][ $key ],
							'tmp_name' => $images['tmp_name'][ $key ],
							'error'    => $images['error'][ $key ],
							'size'     => $images['size'][ $key ],
						);
						$_FILES        = array( $field => $file_array );
                    
						$attachment_id = jws_handle_attachment( $field, $car_id, $allowed_types );
						if ( $attachment_id ) {
							$car_attachments[ $attachment_id ] = $images['name'][ $key ]; // map attachment_id with image.                         
						} else {
							$files_not_uploaded[] = $images['name'][ $key ];
						}
					}

					// Assign attachment_ids to post.
					if ( ! empty( $car_attachments ) ) {
						$files_to_upload = array();
						foreach ( $sorted_img_list as $s_key => $sorted_img ) {
							$img_idx = array_search( $sorted_img, $car_attachments );
							if ( $img_idx ) {
								$files_to_upload[] = $img_idx;
								unset( $car_attachments[ $img_idx ] );
							} else {
								$files_to_upload[] = $sorted_img;
							}
						}

						$files_uploaded = true;
				
                       update_post_meta( $car_id, 'car_images',array_filter($files_to_upload) );
                  
					}
				} else { // single file.
                  
					if ( isset( $images ) && ! empty( $images ) ) {
			     
						$_FILES = array( $field => $images );
						foreach ( $_FILES as $field_name => $array ) {
						 
							$attachment_id = jws_handle_attachment( $field_name, $car_id, $allowed_types );
                            $loc[] = $car_id.','.$field.','.$attachment_id;

							if ( $attachment_id ) {
							 
                             
                             
                                    
                            $current_attachments = get_posts(array(
                                'fields' => 'ids',
                                'post_type' => 'attachment',
                                'posts_per_page' => -1,
                                'post_parent' => $car_id,
                                'post_mime_type' => 'application/pdf'
                            ));
                            
                            $sorted_img_list_pdf = array($attachment_id);
                            
                            $delete_attachments = array_diff($current_attachments, $sorted_img_list_pdf);
                            foreach ($delete_attachments as $delete_attachment) {
                               jws_delete_media(intval($delete_attachment));
                            }   
                            
                                    

								$files_uploaded = true;
                  
                                update_post_meta( $car_id, $field,$attachment_id );
                               
                               
                                $loc[] = '4';
							} else {
								$files_not_uploaded[] = $images['name'];
							}
						}
					}
				}
			}
		} elseif ( ! empty( $sorted_img_list ) ) {// if no files uploaded then perform only img sorting update.

            update_post_meta( $car_id, 'car_images',array_filter($sorted_img_list) );
            $loc[] = '5';
			$files_uploaded = true;
        
		}
		if ( true == $files_uploaded ) {
		  
  
            // End Remove Media //

			return array(
				'status'             => $files_uploaded,
				'file_size_error'    => $imgs_size_error,
				'files_not_uploaded' => $files_not_uploaded,
				'file_size_limit'    => ( $max_file_size / 1048576 ),
                'check2' =>  $upload_dir,
             
			);
		} else {
			return array( 'status' => false );
		}
	}

	/**
	 * Validate car insert limit and image limit
	 *
	 * Return : true (if validated) / false ( if not validated )
	 */
	public static function validate_car_insert() {
		global $jws_option;

		$img_limit     = isset( $jws_option['jws_image_limit'] ) ? $jws_option['jws_image_limit'] : '10';
		$car_limit     = isset( $jws_option['jws_cars_limit'] ) ? $jws_option['jws_cars_limit'] : null;
		$uploaded_imgs = isset( $_POST['car_img_cnt'] ) ? jws_clean( $_POST['car_img_cnt'] ) : 0;

		$user = self::get_user_id();

		if ( $user ) {
			if ( class_exists( 'Subscriptio' ) || class_exists( 'RP_SUB' ) ) {
				$user_subscriptions = array();

				if ( function_exists( 'subscriptio_get_customer_subscriptions' ) ) {
					$user_subscriptions = subscriptio_get_customer_subscriptions( $user );
				}

				if( ! empty( $user_subscriptions ) ) {

					$user_subscription = reset( $user_subscriptions );

					$status = $user_subscription->get_status();

					$_product_id = '';

					if ( 'active' === $status ) {
						$car_limit = intval( get_user_meta( $user, 'jws_car_limt', true ) );
						$img_limit = intval( get_user_meta( $user, 'jws_img_limt', true ) );
					}
				}
			}
			$args = array(
				'post_type'   => 'cars',
				'post_status' => array( 'draft', 'publish', 'trash', 'pending' ),
				'meta_query'  => array(
					array(
						'key'     => 'jws_car_user',
						'value'   => $user,
						'compare' => '=',
					),
				),
			);

			$loop     = new WP_Query( $args );
			$numposts = $loop->post_count;

			if ( null != $car_limit && ( $numposts >= $car_limit ) ) {
				return array(
					'status' => 2,
					'limit'  => $car_limit,
				);
			}

			if ( $uploaded_imgs > $img_limit ) {
				return array(
					'status' => 3,
					'limit'  => $img_limit,
				);
			}
			return array( 'status' => 1 );
		}
		return array( 'status' => 0 );
	}

}

JWS_Cars_Form_Handler::init();
