<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if(!function_exists('jws_submit_field_display')) {
  function jws_submit_field_display() {
        $field = array();
        global $jws_option;    
        if(isset($jws_option['car_submit_field'])) {
           $field = $jws_option['car_submit_field']['enabled'];
        }
        
        return $field;  
  }  
}


/*
 * Display add cars form 
 */

if ( !function_exists('create_field_attr') ) { 
    
    function create_field_attr() {
        $field_option = jws_submit_field_display();

        $field = array(
            array(
                'name' => 'condition',
                'label' => esc_html__('Condition','idealauto'),
                'icon' => ''
            ),
            array(
                'name' => 'make',
                'label' => esc_html__('Make','idealauto'),
                'icon' => ''
            ),
            array(
                'name' => 'model',
                'label' => esc_html__('Model','idealauto'),
                'icon' => ''
            ),
            array(
                'name' => 'year',
                'label' => esc_html__('Year','idealauto'),
                'icon' => ''
            ),
        );

        foreach($field_option as $key => $value) {
          if($key == 'placebo') continue;
          

          if($key == 'trim') {
            $icon = 'jws-icon-002-engine';
          }elseif($key == 'seat_number') {
            $icon = 'jws-icon-seat';
          }elseif($key == 'door_number') {
            $icon = 'jws-icon-car-door';
          }elseif($key == 'stock_number') {
            $icon = 'jws-icon-box';
          }elseif($key == 'vin_number') {
            $icon = 'jws-icon-clipboard';
          }elseif($key == 'registered') {
            $icon = 'jws-icon-key';
          }elseif($key == 'exterior_color') {
            $icon = 'jws-icon-coloring-tool';
          }elseif($key == 'interior_color') {
            $icon = 'jws-icon-coloring-tool';
          }elseif($key == 'msrp_price') {
            $icon = 'jws-icon-dollar';
          }elseif($key == 'fuel_economy') {
            $icon = 'jws-icon-oil';
          }elseif($key == 'drive_train') {
            $icon = 'jws-icon-drive-train';
          }elseif($key == 'transmission') {
            $icon = 'jws-icon-transmission2';
          }elseif($key == 'engine') {
            $icon = 'jws-icon-002-engine';
          }elseif($key == 'fuel_type') {
            $icon = 'jws-icon-007-fuel';
          }elseif($key == 'mileage') {
            $icon = 'jws-icon-001-road-perspective';
          }elseif($key == 'body_style') {
            $icon = 'jws-icon-car2';
          }else{
            $icon = '';
          }                       

          $field[] = array(
                        'name' => $key,
                        'label' => $value,
                        'icon' => $icon
                    );
        }

        return $field;
  
    }
    
}
 
 
 
if ( !function_exists('jws_get_car_form_fields') ) {
	function jws_get_car_form_fields() {
		// assign fieldgroup key
	
			$fields = create_field_attr();
	
		
		$form_fields = array();
		$taxonomies = jws_get_cars_taxonomy();
		/**
		 * Filters the array of fields to put in required fields for add vehicle form in front submission.
		 *
		 * @since 1.0
		 * @param array     	$required_fields	Array of fields to put in required fields in add car form(front side validation).
		 * @visible			  	true
		 */
    
		$required_fields = apply_filters( 'jws_form_required_fields', array( 'year', 'make', 'model', 'condition' ) );
		foreach( $fields as $field ){
	           
		

			$fieldname = $field['name'];
			$require_class = ( in_array( $fieldname, $required_fields ) )? 'jws_validate' : '';
			$extra_classes = apply_filters('jws_additional_classes', array( $require_class ) );
			$extra_classes = ' '.implode(' ', $extra_classes);
            
            

                	switch( $fieldname ){
        				case 'mileage':
        				case 'regular_price':	
                        case 'msrp_price':
        				// number fields
        					$form_fields[] = array(
        						'type' 			=> 'number',
        						'name' 			=> $fieldname,
        						'class' 		=> $extra_classes,
        						'placeholder'	=> $field['label'],
                            'icon'	=> $field['icon']
        					);
        				break;
                        
                        case 'fuel_economy':
                        
                        $form_fields[] = array(
        						'type' 			=> 'text',
        						'name' 			=> $fieldname,
        						'class' 		=> $extra_classes,
        						'placeholder'	=> esc_html__('City/Highway','idealauto'),
                            'icon'	=> $field['icon']
        					);
                        
                        break;
        			

                        case 'vehicle_review_stamps':
                        case 'car_status':
                        case 'transmission':
                        
                        case 'engine';
                        case 'drivetrain';
                        case 'fuel_type';
                        case 'exterior_color';
                        case 'interior_color';
                        case 'drive_train';
                        case 'door_number';
                        case 'seat_number';
                        case 'condition':
                        case 'make':
                        case 'model':
                        case 'year':
                        case 'body_style':
        				// radio button
        				$options = array();
                        
                        
                        if( $fieldname == 'condition' ){
    						// Get all conditions from database
    						$conditions = get_terms( array(
    							'taxonomy' => 'car_condition',
    							'hide_empty' => false,
    						) );
    						$options = array();
    						
    						foreach( $conditions as $condition ){
    							$options[$condition->slug] = $condition->name;
    						}
    						
    					} 
                        if( $fieldname == 'make' ){
    						// Get all conditions from database
    						$makes = get_terms( array(
    							'taxonomy' => 'car_make',
    							'hide_empty' => false,
    						) );
    						$options = array();
    						
    						foreach( $makes as $make ){
    							$options[$make->slug] = $make->name;
    						}
    						
    					}
                        if( $fieldname == 'model' ){
    						// Get all conditions from database
    						$models = get_terms( array(
    							'taxonomy' => 'car_model',
    							'hide_empty' => false,
    						) );
    						$options = array();
    						
    						foreach( $models as $model ){
    							$options[$model->slug] = $model->name;
    						}
    						
    					} 
                        if( $fieldname == 'year' ){
    						// Get all conditions from database
    						$years = get_terms( array(
    							'taxonomy' => 'car_year',
    							'hide_empty' => false,
    						) );
    						$options = array();
    						
    						foreach( $years as $year ){
    							$options[$year->slug] = $year->name;
    						}
    						
    					}  
                        
                        if( $fieldname == 'body_style' ){
    						// Get all conditions from database
    						$body_styles = get_terms( array(
    							'taxonomy' => 'car_body_style',
    							'hide_empty' => false,
    						) );
    						$options = array();
    						
    						foreach( $body_styles as $body_style ){
    							$options[$body_style->slug] = $body_style->name;
    						}
    						
    					}  
                        
                        
                        
    					if( $fieldname == 'vehicle_review_stamps' ){
    						// Get all vehicle_review_stamps from database
    						$vehicle_review_stamps = get_terms( array(
    							'taxonomy' => 'car_vehicle_review_stamps',
    							'hide_empty' => false,
    						) );

    						foreach( $vehicle_review_stamps as $vehicle_review_stamp ){
    							$options[$vehicle_review_stamp->slug] = $vehicle_review_stamp->name;
    						}
    						
    					}
    					if( $fieldname == 'car_status' ){ 
    					  $options = array(
    							'unsold'	=> esc_html__('Unsold', 'idealauto'),
    							'sold'		=> esc_html__('Sold', 'idealauto'),
    					   );    
    					}
                        
                        if( $fieldname == 'transmission' ){
    						// Get all vehicle_review_stamps from database
    						$transmissions = get_terms( array(
    							'taxonomy' => 'car_transmission',
    							'hide_empty' => false,
    						) );

    						foreach( $transmissions as $transmission ){
    							$options[$transmission->slug] = $transmission->name;
    						}
    						
    					}
                        
                        if( $fieldname == 'trim' ){
    						// Get all vehicle_review_stamps from database
    						$trims = get_terms( array(
    							'taxonomy' => 'car_trim',
    							'hide_empty' => false,
    						) );

    						foreach( $trims as $trim ){
    							$options[$trim->slug] = $trim->name;
    						}
    						
    					}
                        
                        if( $fieldname == 'engine' ){
    						// Get all vehicle_review_stamps from database
    						$engines = get_terms( array(
    							'taxonomy' => 'car_engine',
    							'hide_empty' => false,
    						) );

    						foreach( $engines as $engine ){
    							$options[$engine->slug] = $engine->name;
    						}
    						
    					}
                        
                        if( $fieldname == 'drivetrain' ){
    						// Get all vehicle_review_stamps from database
    						$drivetrains = get_terms( array(
    							'taxonomy' => 'car_drivetrain',
    							'hide_empty' => false,
    						) );

    						foreach( $drivetrains as $drivetrain ){
    							$options[$drivetrain->slug] = $drivetrain->name;
    						}
    						
    					}
                        
                        if( $fieldname == 'fuel_type' ){
    						// Get all vehicle_review_stamps from database
    						$fuel_types = get_terms( array(
    							'taxonomy' => 'car_fuel_type',
    							'hide_empty' => false,
    						) );

    						foreach( $fuel_types as $fuel_type ){
    							$options[$fuel_type->slug] = $fuel_type->name;
    						}
    						
    					}
                        
                        if( $fieldname == 'exterior_color' ){
    						// Get all vehicle_review_stamps from database
    						$exterior_colors = get_terms( array(
    							'taxonomy' => 'car_exterior_color',
    							'hide_empty' => false,
    						) );

    						foreach( $exterior_colors as $exterior_color ){
    							$options[$exterior_color->slug] = $exterior_color->name;
    						}
    						
    					}
                        
                        if( $fieldname == 'interior_color' ){
    						// Get all vehicle_review_stamps from database
    						$interior_colors = get_terms( array(
    							'taxonomy' => 'car_interior_color',
    							'hide_empty' => false,
    						) );

    						foreach( $interior_colors as $interior_color ){
    							$options[$interior_color->slug] = $interior_color->name;
    						}
    						
    					}
                        
                        if( $fieldname == 'drive_train' ){
    						// Get all vehicle_review_stamps from database
                           
    						$drive_trains = get_terms( array(
    							'taxonomy' => 'car_drive_train',
    							'hide_empty' => false,
    						) );

    						foreach( $drive_trains as $drive_train ){
    							$options[$drive_train->slug] = $drive_train->name;
    						}
    						
    					}
                        
                        if( $fieldname == 'door_number' ){
    						// Get all vehicle_review_stamps from database
                           
    						$door_numbers = get_terms( array(
    							'taxonomy' => 'car_door_number',
    							'hide_empty' => false,
    						) );

    						foreach( $door_numbers as $door_number ){
    							$options[$door_number->slug] = $door_number->name;
    						}
    						
    					}
                        
                        if( $fieldname == 'seat_number' ){
    						// Get all vehicle_review_stamps from database
                           
    						$seat_numbers = get_terms( array(
    							'taxonomy' => 'car_seat_number',
    							'hide_empty' => false,
    						) );

    						foreach( $seat_numbers as $seat_number ){
    							$options[$seat_number->slug] = $seat_number->name;
    						}
    						
    					}
                        	
        			
                        
    					$form_fields[] = array(
    						'type' 			=> 'select',
    						'name' 			=> $fieldname,
    						'class' 		=> 'radio' . $extra_classes,
    						'placeholder'	=> $field['label'],
    						'options'		=> $options,
                            'icon'	=> $field['icon']
    					);
        					
        				break;
                        
                        
        				case 'features_and_options':
        				// checkbox fields
        				$form_fields[] = array(
        					'type' 			=> 'checkbox',
        					'name' 			=> $fieldname,
        					'class' 		=> 'jws-checkbox' . $extra_classes,
        					'placeholder'	=> $field['label']
        				);
        				break;
        				case 'vehicle_overview':
        				case 'technical_specifications':
        				case 'general_information':
        				// All Editor fields
        					$form_fields[] = array(
        						'type' 			=> 'editor',
        						'name' 			=> $fieldname,
        						'class' 		=> 'jws-editor' . $extra_classes,
        						'placeholder'	=> $field['label']
        					);
        				break;
        				case 'pdf_file':
        				break;
        				case 'car_images':
                        case 'car_images_transparent':
                        case 'make':
                        case 'model':
                        case 'condition':
                        case 'year':
                        case 'regular_price':
                        case 'sale_price':
                        case 'msrp_price':
                        case 'body_style':
        				break;
        				default:
        				// All text fields
        				$class = '';
        				if( in_array( 'car_'.$fieldname, $taxonomies ) && $fieldname != 'vin_number' ){ // add autofill only for taxonomy fields
        					$class = 'jws-autofill';
        				}
        				$form_fields[] = array(
        					'type' 			=> 'text',
        					'name' 			=> $fieldname,
        					'class' 		=> $class . $extra_classes,
        					'placeholder'	=> $field['label'],
                            'icon'	=> $field['icon']
        				);
        			}
        
            
            
		
		}
		/**
		 * Filters the vehicle form fields for add new vehicle page in front submission.
		 *
		 * @since 1.0
		 * @param array			$form_fields	An array of vehicle fields to be displayed on add vehicle page.
		 * @visible			   	true
		 */
		return apply_filters( 'jws_car_form_fields_items', $form_fields );
	}
}



if ( !function_exists('jws_get_cars_taxonomy') ) {
	 // Get Taxomony of Cars Posttype
	function jws_get_cars_taxonomy() {
		$taxonomies = get_object_taxonomies('cars');
		$taxonomyArray = array();
		foreach ( $taxonomies as $taxonomy ) {		
			$tax_obj = get_taxonomy( $taxonomy );
			if($taxonomy != "car_features_options")
			$taxonomyArray[$tax_obj-> label] = $taxonomy;
		}
		return $taxonomyArray;
	}
}

add_action('wp_ajax_jws_get_autocomplete','jws_autocomplete_fields');
add_action('wp_ajax_nopriv_jws_get_autocomplete','jws_autocomplete_fields');
if ( !function_exists('jws_autocomplete_fields') ) {
	// auto complete fields in car form
	function jws_autocomplete_fields() {
		$responseArray = array();
		
		if(isset($_POST['action']) && $_POST['action'] == 'jws_get_autocomplete') { 
				$fieldName = 'car_'.jws_clean($_POST['fieldName']);
				$search_val = jws_clean($_POST['search']);
				$options = array (
						'orderby' => 'name',
						'order' => 'ASC',
						'hide_empty' => false, //can be 1, '1' too
						'name__like' => $search_val,
						'meta_query' => '',
						'meta_key' => array(),
						'meta_value'=> '',
				);
				// search value
				$fieldValue = get_terms( $fieldName, $options );
				
				if( !empty($fieldValue) ){ // If found match
				$result = array();
					foreach( $fieldValue as $key=> $value ){
						$result[] = array('label'=> $value-> name, 'value'=> $value-> name);
					}
					
					// Prepare response
					$responseArray = array( 'status'=> true, 'msg'=> esc_html__('Found Match!', 'idealauto'), 'data'=> $result );
				} else {
					$responseArray = array( 'status'=> true, 'msg'=> esc_html__('Not Found', 'idealauto'), 'data'=> array() );
				}
		} else {
			$responseArray = array( 'status'=> false );
		}
		
		// Send Result
		echo json_encode($responseArray); die;
	}
}

if (!function_exists('jws_clean')) {

    function jws_clean($var) {
        if (is_array($var)) {
            return array_map('jws_clean', $var);
        } else {
            return is_scalar($var) ? sanitize_text_field($var) : $var;
        }
    }

}



if ( ! function_exists( 'jws_handle_attachment' ) ) {
	/**
	 * Image upload handle.
	 *
	 * @param string $file_handler .
	 * @param string $post_id .
	 * @param string $allowed_types .
	 */
	function jws_handle_attachment( $file_handler, $post_id, $allowed_types = array( 'jpg', 'jpeg', 'png', 'gif' ) ) {
		// check to make sure its a successful upload.
		if ( ! isset( $_FILES[ $file_handler ]['error'] ) ) {
			return false;
		}
		if ( UPLOAD_ERR_OK !== $_FILES[ $file_handler ]['error'] ) {
			return false; }

		$ext = pathinfo( $_FILES[ $file_handler ]['name'] );
		$ext = $ext['extension'];
		if ( ! in_array( strtolower( $ext ), $allowed_types ) ) {
			/* translators: $s: Please upload file */
			 sprintf( esc_html__( 'Please upload file(s) with %s extension.', 'idealauto' ), implode( ', ', $allowed_types ) );
			return false;
		}

		require_once ABSPATH . 'wp-admin/includes/image.php';
		require_once ABSPATH . 'wp-admin/includes/file.php';
		require_once ABSPATH . 'wp-admin/includes/media.php';

		$attach_id = media_handle_upload( $file_handler, $post_id );
		if ( is_wp_error( $attach_id ) ) {
			return false;
		}
		return $attach_id;
	}
}



/**
* Submit Car ajax
**/

add_action( 'wp_ajax_jws_save_car', 'jws_do_save' );
add_action( 'wp_ajax_nopriv_jws_save_car', 'jws_do_save' );
if ( ! function_exists( 'jws_do_save' ) ) {
	/**
	 * Function to save car data
	 */
	function jws_do_save() {
	    global $jws_option;   
		$status = false;
		$msg    = esc_html__( 'Something went wrong!', 'idealauto' );
		$car_id = '';
		if ( isset( $_POST['action'] ) && 'jws_save_car' === $_POST['action'] ) {
			$result         = JWS_Cars_Form_Handler::process_car_save();
			$invalid_fields = array();
			if ( ! empty( $result ) ) {
				switch ( $result['status'] ) {
					case 1:
						$status = true;
						$msg    = esc_html__( 'Media uploading , upload time depends on media size.', 'idealauto' );
						$car_id = $result['post_id'];
						break;
					case 3:
						$status = false;
						$msg    = esc_html__( 'Please check captcha form.', 'idealauto' );
						break;
					case 4:
						$status = false;
						foreach ( $result['err_fields'] as $field ) {
							$invalid_fields[] = strtolower( str_replace( ' ', '_', $field ) );
						}
						$msg = sprintf(
							/* translators: %s: list of required fields */
							esc_html__( 'Please fill required fields: %s', 'idealauto' ),
							esc_html( implode( ', ', $result['err_fields'] ) )
						);
						break;
					case 5:
						$status = false;
						$msg    = sprintf(
							/* translators: %s: number of vehicles */
							esc_html__( 'Sorry! you can add at most %s vehicles.', 'idealauto' ),
							esc_html( $result['limit'] )
						);
						break;
					case 6:
						$status = false;
						$msg    = sprintf(
							/* translators: %s: number of images */
							esc_html__( 'Sorry! you can upload vehicle images at most %s.', 'idealauto' ),
							esc_html( $result['limit'] )
						);
						break;
                    case 7:
						$status = false;
                        $msg    = __( 'Sorry! Please log in to add your vehicle. <a href="javascript:void(0)">Click login or register</a>', 'idealauto' );
				
						break;    
					default:
						$status = false;
						$msg    = esc_html__( 'There is an error inserting vehicle, please try again later!', 'idealauto' );
				}
			}
		}
        
        // Remove Media //
            if(isset($_POST['file_attachments'])) {
                $sorted_img_list  = explode( ',', $_POST['file_attachments'] ); // img order.
                
                $current_attachments = get_posts(array(
                    'fields' => 'ids',
                    'post_type' => 'attachment',
                    'posts_per_page' => -1,
                    'post_parent' => $car_id,
                    'post_mime_type' => 'image'
                ));
        
                $delete_attachments = array_diff($current_attachments, $sorted_img_list);
                foreach ($delete_attachments as $delete_attachment) {
                   jws_delete_media(intval($delete_attachment));
                }  
            }
            
            
             if(isset($_POST['pdf-value'])) {
               $sorted_img_list_pdf = array($_POST['pdf-value']);
                
                $current_attachments = get_posts(array(
                    'fields' => 'ids',
                    'post_type' => 'attachment',
                    'posts_per_page' => -1,
                    'post_parent' => $car_id,
                    'post_mime_type' => 'application/pdf'
                ));
        
                $delete_attachments = array_diff($current_attachments, $sorted_img_list_pdf);
                foreach ($delete_attachments as $delete_attachment) {
                   jws_delete_media(intval($delete_attachment));
                }  
            }
            
            
		echo wp_json_encode(
			array(
                'check' => $_POST,
                'check2' => $result['check2'],
				'status'         => $status,
				'car_id'         => $car_id,
				'message'        => $msg,
				'invalid_fields' => $invalid_fields,
			)
		);
		die;
	}
}



add_action( 'wp_ajax_jws_upload_images', 'jws_do_upload_images' );
add_action( 'wp_ajax_nopriv_jws_upload_images', 'jws_do_upload_images' );
if ( ! function_exists( 'jws_do_upload_images' ) ) {
	/**
	 * Remove attachments
	 */
	function jws_do_upload_images() {
		$status     = false;
		$redirect   = '';
		$status_msg = esc_html__( 'Something went wrong!', 'idealauto' );

		if ( isset( $_POST['action'] ) && 'jws_upload_images' === $_POST['action'] ) {
			$imgupload = JWS_Cars_Form_Handler::process_image_upload();
			if ( true === (bool) $imgupload['status'] ) {
			    $user   = wp_get_current_user(); 
             
				$redirect   = get_author_posts_url($user->ID); //jws_get_page_permalink( 'myuseraccount' );
				$status_msg = esc_html__( 'Vehicle data uploaded successfully! , redirecting...', 'idealauto' );
				//jws_add_notice( esc_html__( 'Vehicle is successfully saved!', 'idealauto' ) );
				$status = true;
				if ( ! empty( $imgupload['file_size_error'] ) ) {
					/* translators: $s: Following images not uploaded due to image size exceeded than */
				//	jws_add_notice( sprintf( esc_html__( 'Following images not uploaded due to image size exceeded than %1$s MB: %2$s.', 'idealauto' ), $imgupload['file_size_limit'], implode( ',', $imgupload['file_size_error'] ) ), 'error' );
				}
			}
		}
		echo wp_json_encode(
			array(
				'status'     => $imgupload['status'],
				'redirect'   => $redirect,
				'status_msg' => $status_msg,
			)
		);
		die;
	}
}


if (!function_exists('jws_delete_media')) {
    /**
     * Delete media
     *
     * @param $media_id
     */
    function jws_delete_media($media_id)
    {
        $current_user = wp_get_current_user();
        $media_id = intval($media_id);
        if (!empty($current_user->ID)) {
            $current_user_id = $current_user->ID;

            $args = array(
                'author' => intval($current_user_id),
                'post_status' => 'any',
                'post__in' => array($media_id),
                'post_type' => 'attachment'
            );

            $query = new WP_Query($args);

            if ($query->found_posts == 1) {
                wp_delete_attachment($media_id, true);
            }
        }
    }
}

function limitTextWords($content = false, $limit = false, $stripTags = false, $ellipsis = false) 
{
    if ($content && $limit) {
        $content = ($stripTags ? strip_tags($content) : $content);
        $content = explode(' ', $content, $limit+1);   
        array_pop($content);
        if ($ellipsis) {
            array_push($content, '...');
        }
        $content = implode(' ', $content);
    }
    return $content;
}


function limitTextChars($content = false, $limit = false, $stripTags = false, $ellipsis = false) 
{
    if ($content && $limit) {
        $content  = ($stripTags ? strip_tags($content) : $content);
        $ellipsis = ($ellipsis ? "..." : $ellipsis);
        $content  = mb_strimwidth($content, 0, $limit, $ellipsis);
    }
    return $content;
}
