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

function create_shortocde_account() {
    ?>
        <div class="container">
            <div class="row">
                <div class="col-xl-3 col-lg-3 col-12">
                    <?php get_template_part( 'template-parts/content/account/naviagation' ); ?>
                </div>
                <div class="col-xl-9 col-lg-9 col-12">
                    <?php get_template_part( 'template-parts/content/account/content' ); ?>
                </div>
            </div>
        </div>
     <?php

}

if(function_exists('insert_shortcode')) {
    insert_shortcode('dealer_my_account','create_shortocde_account');
}

if ( !function_exists( 'jws_get_author_link' ) ) {
    function jws_get_author_link( $id = 'register' )
    {

        if ( $id == 'register' ) {
            //$login_page = get_theme_mod( 'login_page', 1718 );

            //$login_page = jws_motors_wpml_is_page( $login_page );

            //$link = get_permalink( $login_page );
        } else {
            if ( empty( $id ) or $id == 'myself-view' ) {
                $user = wp_get_current_user();
                if ( !is_wp_error( $user ) ) {
                    $link = get_author_posts_url( $user->data->ID );
                    if ( $id == 'myself-view' ) {
                        $link = add_query_arg( array( 'view-myself' => 1 ), $link );
                    }
                } else {
                    $link = '';
                }
            } else {
                $link = get_author_posts_url( $id );
            }

        }

        return $link;
    }
}

function jws_listings_ajax_save_user_data()
{

    $response = array();
    $got_error_validation = false;


		if ( empty( $_POST['action'] ) || 'update_account_details' !== $_POST['action'] || empty( $_POST['_wpnonce'] ) || ! wp_verify_nonce( $_POST['_wpnonce'], 'update_account_details' ) ) {
			return;
		}

		nocache_headers();

		$errors = new WP_Error();
		$user   = new stdClass();

		$user->ID     = (int) get_current_user_id();
		$current_user = get_user_by( 'id', $user->ID );
  
		if ( $user->ID <= 0 ) {
			return;
		}

		// Personal Details.
		$account_first_name = ! empty( $_POST['account_first_name'] ) ? jws_clean( $_POST['account_first_name'] ) : '';
		$account_last_name  = ! empty( $_POST['account_last_name'] ) ? jws_clean( $_POST['account_last_name'] ) : '';
		$account_email      = ! empty( $_POST['account_email'] ) ? jws_clean( $_POST['account_email'] ) : '';
        $account_phone      = ! empty( $_POST['account_phone'] ) ? jws_clean( $_POST['account_phone'] ) : '';
        $account_name_publicly      = ! empty( $_POST['account_name_publicly'] ) ? jws_clean( $_POST['account_name_publicly'] ) : '';
        $account_roles      = ! empty( $_POST['user_type'] ) ? jws_clean( $_POST['user_type'] ) : $current_user->roles[0];

		// Social Profiles.
		$user_facebook  = ! empty( $_POST['user_facebook'] ) ? jws_clean( $_POST['user_facebook'] ) : '';
		$user_twitter   = ! empty( $_POST['user_twitter'] ) ? jws_clean( $_POST['user_twitter'] ) : '';
		$user_whatsapp = ! empty( $_POST['user_whatsapp'] ) ? jws_clean( $_POST['user_whatsapp'] ) : '';
		$user_instagram = ! empty( $_POST['user_instagram'] ) ? jws_clean( $_POST['user_instagram'] ) : '';
        
        // Map Profiles.
		$address  = ! empty( $_POST['vehicle_location'] ) ? jws_clean( $_POST['vehicle_location'] ) : '';
		$location_lon  = ! empty( $_POST['jws_lng'] ) ? jws_clean( $_POST['jws_lng'] ) : '';
		$location_lat = ! empty( $_POST['jws_lat'] ) ? jws_clean( $_POST['jws_lat'] ) : '';


		// Login Details.
		$pass_cur  = ! empty( $_POST['password_current'] ) ? $_POST['password_current'] : '';
		$pass1     = ! empty( $_POST['password_1'] ) ? $_POST['password_1'] : '';
		$pass2     = ! empty( $_POST['password_2'] ) ? $_POST['password_2'] : '';
		$save_pass = true;

		$user->first_name = $account_first_name;
		$user->last_name  = $account_last_name;

		// Prevent emails being displayed, or leave alone.
		$user->display_name = is_email( $current_user->display_name ) ? $user->first_name : $current_user->display_name;

		// Handle required fields.
		$required_fields = apply_filters(
			'jws_update_account_details_required_fields',
			array(
				'account_first_name' => esc_html__( 'First name', 'idealauto' ),
				'account_last_name'  => esc_html__( 'Last name', 'idealauto' ),
				'account_email'      => esc_html__( 'Email address', 'idealauto' ),
                'account_name_publicly' => esc_html__( 'Account name publicly', 'idealauto' ),
			)
		);

		foreach ( $required_fields as $field_key => $field_name ) {
			if ( empty( $_POST[ $field_key ] ) ) {
				/* translators: %s: field name */
                $error_msg =  sprintf( __( '%s is a required field.', 'idealauto' ), '<strong>' . esc_html( $field_name ) . '</strong>' );
                $got_error_validation = true;
			}
		}

		if ( $account_email ) {
			$account_email = sanitize_email( $account_email );
			if ( ! is_email( $account_email ) ) {
                $error_msg = esc_html__('Please provide a valid email address.', 'idealauto');
                $got_error_validation = true;
			} elseif ( email_exists( $account_email ) && $account_email !== $current_user->user_email ) {
                $error_msg = esc_html__('This email address is already registered', 'idealauto');
                $got_error_validation = true;
			}
			$user->user_email = $account_email;
		}
        
        

        
        
        
  

		if ( ! empty( $pass_cur ) && empty( $pass1 ) && empty( $pass2 ) ) {
            $error_msg = esc_html__('Please fill out all password fields.', 'idealauto');
            $got_error_validation = true;
			$save_pass = false;
		} elseif ( ! empty( $pass1 ) && empty( $pass_cur ) ) {
            $error_msg = esc_html__('Please enter your current password.', 'idealauto');
            $got_error_validation = true;
			$save_pass = false;
		} elseif ( ! empty( $pass1 ) && empty( $pass2 ) ) {
		    $error_msg = esc_html__('Please re-enter your password.', 'idealauto');
            $got_error_validation = true;
			$save_pass = false;
		} elseif ( ( ! empty( $pass1 ) || ! empty( $pass2 ) ) && $pass1 !== $pass2 ) {
            $error_msg = esc_html__('New passwords do not match.', 'idealauto');
            $got_error_validation = true;
			$save_pass = false;
		} elseif ( ! empty( $pass1 ) && ! wp_check_password( $pass_cur, $current_user->user_pass, $current_user->ID ) ) {
            $error_msg = esc_html__('Your current password is incorrect.', 'idealauto');
            $got_error_validation = true;
			$save_pass = false;
		}elseif( empty( $location_lon ) && empty( $location_lat ) ) {
		    $error_msg = esc_html__('Please add address of you.', 'idealauto');
            $got_error_validation = true;
			$save_pass = false; 
		}

		if ( $pass1 && $save_pass ) {
			$user->user_pass = $pass1;
		}

		if ( $errors->get_error_messages() ) {
			foreach ( $errors->get_error_messages() as $error ) {
                $error_msg = $error;
                $got_error_validation = true;
			}
		}
            
		/*Profile img*/
		$allowed = array( 'jpg', 'jpeg', 'png', 'gif', 'JPG', 'JPEG', 'PNG', 'GIF' );
		if ( ! empty( $_FILES['profile_img'] ) ) {
			$file = $_FILES['profile_img'];
			if ( is_array( $file ) && ! empty( $file['name'] ) ) {
				$ext = pathinfo( $file['name'] );
				$ext = $ext['extension'];
				if ( in_array( $ext, $allowed ) ) {
					$upload_dir  = wp_upload_dir();
					$upload_url  = $upload_dir['baseurl'].'/client';
					$upload_path = $upload_dir['basedir'].'/client';
                    if (!file_exists($upload_dir)) { 
                           add_filter( 'upload_dir', 'wpse_141088_upload_dir' ); 
                        }

					/*Upload full image*/
					if ( ! function_exists( 'wp_handle_upload' ) ) {
						require_once ABSPATH . 'wp-admin/includes/file.php';
					}
                    
                    $jws_user_avatar = get_user_meta( $user->ID, 'dealer-avatar', true );
                    if(!empty($jws_user_avatar)) {
                       wp_delete_attachment( $jws_user_avatar); 
                    }
	               $attachment_id = media_handle_upload( 'profile_img', 0 ); 
				} else {
                     $error_msg = esc_html__('Please load image with right extension (jpg, jpeg, png and gif)', 'idealauto');
                     $got_error_validation = true;
				}
               
			}
		}elseif ( isset( $_POST['file_attachments_avatar'])) {// if no files uploaded then perform only img sorting update.
            if(empty($_POST['file_attachments_avatar'])) {
                $jws_user_avatar = get_user_meta( $user->ID, 'dealer-avatar', true );
                if(!empty($jws_user_avatar)) {
                   wp_delete_attachment( $jws_user_avatar); 
                }
            }
			update_user_meta( $user->ID, 'dealer-avatar', $_POST['file_attachments_avatar'] );
           
		}
        
        if( ! empty( $_FILES['profile_banner'] ) ) {
			$file = $_FILES['profile_banner'];
			if ( is_array( $file ) && ! empty( $file['name'] ) ) {
				$ext = pathinfo( $file['name'] );
				$ext = $ext['extension'];
				if ( in_array( $ext, $allowed ) ) {
					$upload_dir  = wp_upload_dir();
					$upload_url  = $upload_dir['baseurl'].'/client';
					$upload_path = $upload_dir['basedir'].'/client';
                    if (!file_exists($upload_dir)) { 
                           add_filter( 'upload_dir', 'wpse_141088_upload_dir' ); 
                        }

					/*Upload full image*/
					if ( ! function_exists( 'wp_handle_upload' ) ) {
						require_once ABSPATH . 'wp-admin/includes/file.php';
					}
                    
                    $jws_user_banner = get_user_meta( $user->ID, 'banner', true );
                    if(!empty($jws_user_banner)) {
                       wp_delete_attachment( $jws_user_banner); 
                    }
	               $attachment_banner_id = media_handle_upload( 'profile_banner', 0 ); 
				} else {
                     $error_msg = esc_html__('Please load image with right extension (jpg, jpeg, png and gif)', 'idealauto');
                     $got_error_validation = true;
				}
               
			}
		}elseif ( isset( $_POST['file_attachments_banner'])) {// if no files uploaded then perform only img sorting update.
            if(empty($_POST['file_attachments_banner'])) {
                $jws_user_avatar = get_user_meta( $user->ID, 'banner', true );
                if(!empty($jws_user_avatar)) {
                   wp_delete_attachment( $jws_user_avatar); 
                }
            }
          
			update_user_meta( $user->ID, 'banner', $_POST['file_attachments_banner'] );
            
		}
        
        
        
        
        
        /*Profile gallery*/
        $current_attachments = get_user_meta( $user->ID, 'dealer_images', true );
        $sorted_img_list = explode( ',', $_POST['file_attachments'] ); // img order.
 
        $delete_attachments = array_diff($current_attachments, $sorted_img_list);
        foreach ($delete_attachments as $delete_attachment) {
            jws_delete_media(intval($delete_attachment));
        } 
        process_image_upload($user->ID);
		if ( !$got_error_validation ) {
    
			wp_update_user( $user );
            
            /*Update user roles*/
            $current_user->remove_role( $current_user->roles[0] );
            $current_user->add_role( $account_roles );
            
			/*Update user meta path and url image*/
			if ( !empty($attachment_id ) ) {
				update_user_meta( $user->ID, 'dealer-avatar', $attachment_id );
             
			}
            if ( !empty($attachment_banner_id ) ) {
				update_user_meta( $user->ID, 'banner', $attachment_banner_id );
             
			}
            
            $opentime = array(
                'monday','tuesday','wednesday','thursday','friday','saturday','sunday'
            );
            
            foreach($opentime as $value) { 
                update_user_meta( $user->ID, $value , $_POST[$value] );
            }

            if ( ! empty( $location_lon ) && ! empty( $location_lat ) ) {
				$location = array(
					'address' => $address,
					'lng'     => $location_lon,
					'lat'     => $location_lat,
					'zoom'    => '17',
				);
				update_user_meta( $user->ID, 'dealer_location', $location );
			}

           
            wp_update_user( array ('ID' => $user->ID, 'display_name' =>  $_POST['account_name_publicly']));
            wp_update_user( array ('ID' => $user->ID, 'nickname' =>  $_POST['account_name_publicly']));
            update_user_meta( $user->ID, 'dealer_phone', $account_phone );
			// Save social profiles.
			update_user_meta( $user->ID, 'dealer_facebook', $user_facebook );
			update_user_meta( $user->ID, 'dealer_twitter', $user_twitter );
			update_user_meta( $user->ID, 'dealer_whatsapp', $user_whatsapp );
			update_user_meta( $user->ID, 'dealer_instagram', $user_instagram );
            $error_msg = esc_html__('Settings Saved.', 'idealauto');
		}

    $response['error_msg'] = $error_msg;
    $response['status'] = $got_error_validation;
    $response['redirect'] = get_author_posts_url($user->ID).'edit-profile';
    
    
    wp_send_json($response);
}

function process_image_upload($user) {
		$sorted_img_list    = explode( ',', $_POST['file_attachments'] ); // img order.
	
		$max_file_size      = apply_filters( 'jws_max_media_upload_size', 1048576 * 4 ); /* 4mb is highest media upload here */
		$imgs_size_error    = '';
		$files_not_uploaded = '';
        

		if ( isset( $_FILES ) && ! empty( $_FILES['dealer_images'] ) ) {
			$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 'pdf_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 );
                        $upload_dir  = wp_upload_dir();
    					$upload_url  = $upload_dir['baseurl'].'/client';
    					$upload_path = $upload_dir['basedir'].'/client';
                        if (!file_exists($upload_dir)) { 
                           add_filter( 'upload_dir', 'wpse_141088_upload_dir' ); 
                        }
                        $attachment_id = media_handle_upload($field, 0 ); 
						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_user_meta( $user, 'dealer_images', $files_to_upload );
					} else {
                        update_user_meta( $user, null, $field );
						$files_uploaded = true;
					}
				} else { // single file.
					if ( isset( $images ) && ! empty( $images ) ) {
						$_FILES = array( $field => $images );
						foreach ( $_FILES as $field_name => $array ) {
                            $attachment_id = media_handle_upload($field_name, 0 ); 
							if ( $attachment_id ) {
								$files_uploaded = true;
                                update_user_meta( $user , 'dealer_images', $attachment_id );
							} else {
								$files_not_uploaded[] = $images['name'];
							}
						}
					}
				}
               
			}
          
		} elseif ( ! empty( $sorted_img_list ) ) {// if no files uploaded then perform only img sorting update.
            update_user_meta( $user, 'dealer_images', $sorted_img_list );
			$files_uploaded = true;
		}

	}


add_action('wp_ajax_update_account_details', 'jws_listings_ajax_save_user_data');

function wpse_141088_upload_dir( $dir ) {
    return array(
        'path'   => $dir['basedir'] . '/client',
        'url'    => $dir['baseurl'] . '/client',
        'subdir' => '/client',
    ) + $dir;
}



function process_car_actions() {
if ( isset( $_GET['jws_car_action'] )) {
	if ( isset( $_GET['id'] ) && ! empty( $_GET['id'] ) ) {

		$car             = intval( $_GET['id'] );
		$author          = get_post_meta( $car, 'jws_car_user', true );
		$user            = wp_get_current_user();
		$action_msg      = '';
        $status = get_post_status( $car );
		if ( intval( $author ) == intval( $user->ID ) ) {

			switch ( $_GET['jws_car_action'] ) {
				case 'disable':
                if ( $status == 'publish' ) {
        			$disabled_car = array(
        				'ID'          => $car,
        				'post_status' => 'draft',
        			);
        			wp_update_post( $disabled_car );
                }    
				$action_msg      = esc_html__( 'Vehicle status is successfully set to draft.', 'idealauto' );
				break;

				case 'enable':
				    if ( $status == 'draft' ) { 
				        $disabled_car = array(
                            'ID' => $car,
                            'post_status' => 'publish'
                        );  
				    } 
                    wp_update_post( $disabled_car );
					$action_msg      = esc_html__( 'Vehicle is successfully enabled.', 'idealauto' );
					break;
				case 'trash':
					// get all attachments of this post.
					$attachments = get_posts(
						array(
							'post_type'      => 'attachment',
							'posts_per_page' => '-1',
							'post_parent'    => $car,
						)
					);

					if ( wp_delete_post( $car, true ) ) { // delete car post forcefully.
						if ( ! empty( $attachments ) ) {
							foreach ( $attachments as $attachment ) {
								wp_delete_attachment( $attachment->ID );
							}
						}
					}
                    
                    if ( $status == 'draft' ||  $status == 'pending' ) { 
				        $disabled_car = array(
                            'ID' => $car,
                            'post_status' => 'draft'
                        );  
				    } 
                    wp_update_post( $disabled_car );
                    
                    
					//jws_add_notice( esc_html__( 'Vehicle is successfully deleted.', 'idealauto' ), 'success' );
					//wp_safe_redirect(get_author_posts_url(get_the_author_meta($car)));
			
				break;
				default:
					///jws_add_notice( esc_html__( 'Invalid action.', 'idealauto' ), 'error' );
					//wp_safe_redirect(get_author_posts_url(get_the_author_meta($car)));
					

			}

			//jws_add_notice( $action_msg, 'success' );
			wp_safe_redirect(get_author_posts_url($user->ID));
		
		}
	}
}
}
  
add_action( 'init', 'process_car_actions' );


if( ! function_exists( 'jws_ajax_load_make_features' ) ) {
    	function jws_ajax_load_make_features($id = false) {
    		if( isset($_GET['id']) ) {
    			$id = (int) $_GET['id'];
    		}
            $features =  get_post_meta( $id , 'car_asset_type',  true );
            $value = $features == 'featured' ? '' : 'featured';
            update_post_meta( $id, 'car_asset_type', $value );
    		die();
    	}
    
        
        // Note: Keep default AJAX actions in case WooCommerce endpoint URL is unavailable
        add_action('wp_ajax_jws_ajax_load_make_features', 'jws_ajax_load_make_features');
        add_action('wp_ajax_nopriv_jws_ajax_load_make_features', 'jws_ajax_load_make_features');
    
}

function mein_stellenangebot_endpoint() {

    add_rewrite_endpoint( 'edit-profile',  EP_ALL );
    add_rewrite_endpoint( 'favorites',  EP_ALL );
    add_rewrite_endpoint( 'edit-woo-address',  EP_ALL );
}

add_action( 'init', 'mein_stellenangebot_endpoint' );