<?php
if ( ! function_exists( 'wpj_get_attachment_image_url' ) ) {
	function wpj_get_attachment_image_url( $attachment_id, $size = 'thumbnail', $icon = false ) {
		$image = wp_get_attachment_image_src( $attachment_id, $size, $icon );

		return $image && is_array( $image ) ? $image[0] : '';
	}
}

if ( ! function_exists( 'wpj_get_attachment_id_from_url' ) ) {
	function wpj_get_attachment_id_from_url( $attachment_url = '' ) {
		if ( ! $attachment_url ) return false;

		$attachment_id = false;

		$upload_dir_paths = wp_upload_dir();

		if ( substr( $upload_dir_paths['baseurl'], 0, 8 ) != substr( $attachment_url, 0, 8 ) ) {
			if ( substr( $upload_dir_paths['baseurl'], 0, 8 ) === 'https://' ) {
				$attachment_url = substr_replace( $attachment_url, 'https://', 0, 7 );

			} else {
				$attachment_url = substr_replace( $attachment_url, 'http://', 0, 8 );

			}
		}

		if ( false !== strpos( $attachment_url, $upload_dir_paths['baseurl'] ) ) {
			$attachment_url = preg_replace( '/-\d+x\d+(?=\.(jpg|jpeg|png|gif)$)/i', '', $attachment_url );
			$attachment_url = str_replace( $upload_dir_paths['baseurl'] . '/', '', $attachment_url );

			$attachment_id = wpj_get_post_meta( 'p.ID', ['pm.meta_key' => '_wp_attached_file', 'pm.meta_value' => $attachment_url, 'p.post_type' => 'attachment'], 'var' );
		}

		return $attachment_id;
	}
}

if ( ! function_exists( 'wpj_post_has_attachments' ) ) {
	function wpj_post_has_attachments( $attachments_param = '' ) {
		$file_exists = false;

		if ( $attachments_param ) {
			$attachments = explode( ",", $attachments_param );

			if ( $attachments ) {
				foreach ( $attachments as $attachment ) {
					if ( get_attached_file ( $attachment ) != "" ) {
						$file_exists = true;
					}
				}
			}
		}

		if ( $file_exists ) return true;

		return false;

	}
}

if ( ! function_exists( 'wpj_save_auth_token_transient' ) ) {
	function wpj_save_auth_token_transient() {
		set_post_meta_transient( $_POST['secure_download'], 'wpj_authentication_token', $_POST['auth_token'], 600 );

		if ( wpj_is_ajax_call() ) wp_die();
	}
}

if ( ! function_exists( 'wpj_save_attachments' ) ) {
	function wpj_save_attachments( $attachments = '', $pid = '', $meta_name = '', $action = '', $meta_type = 'post' ) {
		if ( $attachments != "" ) {
			if ( $action == 'edit' ) {
				$new_attachments = explode( ",", $attachments );

				if ( $meta_type == 'user' ) $current_attachments = get_user_meta( $pid, $meta_name, true );
				elseif ( $meta_type == 'order' ) $current_attachments = get_option( $meta_name );
				else $current_attachments = get_post_meta( $pid, $meta_name, true );

				$current_attachments = explode( ",", $current_attachments );

				$attachments = array_merge( $new_attachments, $current_attachments );

				if ( $meta_type == 'user' ) update_user_meta( $pid, $meta_name, implode( ",", $attachments ) );
				if ( $meta_type == 'order' ) update_option( $meta_name, implode( ",", $attachments ) );
				else update_post_meta( $pid, $meta_name, implode( ",", $attachments ) );

			} else {
				if ( $meta_type == 'user' ) add_user_meta( $pid, $meta_name, $attachments, true );
				elseif ( $meta_type == 'order' ) update_option( $meta_name, $attachments );
				else add_post_meta( $pid, $meta_name, $attachments, true );

			}

			$attachments = is_array( $attachments ) ? $attachments : explode( ",", $attachments );

			if ( $attachments ) {
				foreach ( $attachments as $key => $attachment ) {
					if ( $meta_type == 'user' ) update_user_meta( $attachment, 'is_' . $meta_name, 1 );
					if ( $meta_type == 'order' ) update_option( $attachment, 'is_' . $meta_name, 1 );
					else update_post_meta( $attachment, 'is_' . $meta_name, 1 );
				}
			}
		}
	}
}

if ( ! function_exists( 'wpj_sort_attachments' ) ) {
	function wpj_sort_attachments() {
		if ( isset( $_POST['images_order'] ) ) {
			$images_order = $_POST['images_order'];

			if ( $images_order ) {
				$i = 1;

				foreach ( $images_order as $image ) {
					if ( ! is_demo_user() ) {
						if ( ! empty ( $_POST['pid'] ) && $i == 1 ) {
							set_post_thumbnail( $_POST['pid'], $image );
						}

						update_post_meta( $image, 'images_order', $i );
					}

					$i++;
				}
			}
		}

		if ( wpj_is_ajax_call() ) wp_die();
	}
}

if ( ! function_exists( 'wpj_delete_attachments' ) ) {
	function wpj_delete_attachments( $attachment_id = '', $media_type = '', $pid = '' ) {
		global $current_user;

		$attachment_id = WPJ_Form::post( 'attachment_id', $attachment_id );
		$media_type    = WPJ_Form::post( 'media_type', $media_type );
		$pid           = WPJ_Form::post( 'pid', $pid );

		if ( $attachment_id && $media_type ) {
			if ( is_user_logged_in() && ! is_demo_admin() ) {
				$post = get_post( $attachment_id );

				if ( $post ) {
					if ( $post->post_author == $current_user->ID || user_can( $current_user, 'manage_options' ) ) {
						wp_delete_post( $attachment_id );

						if ( ! empty( $post->post_parent ) && $media_type == 'cover' )
							delete_post_meta( $post->post_parent, 'cover-image' );

						if ( $media_type == 'banner' ) {
							wp_delete_attachment( $attachment_id, true );
							delete_user_meta( $current_user->ID, 'banner' );
							delete_user_meta( $current_user->ID, 'banner_id' );
						}

						if ( str_contains( $media_type, 'bank_transfer_job_proof_attachments' ) ) {
							$attachments = get_option( 'bank_transfer_job_proof_attachments_' . $pid, );
							$attachment  = explode( ",", $attachments );

							$attachments_new = array_diff( $attachment, [$attachment_id] );
							$attachments_arr = ! empty( $attachments_new ) ? implode( ",", $attachments_new ) : '';

							update_option( 'bank_transfer_job_proof_attachments_' . $pid, $attachments_arr );

						} elseif ( $pid ) {
							$attachments = get_post_meta( $pid, $media_type, true );
							$attachment  = explode( ",", $attachments );

							$attachments_new = array_diff( $attachment, [$attachment_id] );
							$attachments_arr = ! empty( $attachments_new ) ? implode( ",", $attachments_new ) : '';

							update_post_meta( $pid, $media_type, $attachments_arr );

						}
					}
				}
			}
		}

		if ( wpj_is_ajax_call() ) wp_die();
	}
}

if ( ! function_exists( 'wpj_download_attachments' ) ) {
	function wpj_download_attachments() {
		if ( isset( $_GET['secure_download'] ) && is_numeric( $_GET['secure_download'] ) ) {
			global $current_user;

			$attachment_id = $_GET['secure_download'];

			$direct_download = 0;
			$allowed_users   = [];

			$pm_id      = get_post_meta( $attachment_id, 'pm_id', true );
			$message_id = get_post_meta( $attachment_id, 'message_id', true );
			$job_id     = get_post_meta( $attachment_id, 'job_id', true );

			if ( $pm_id && is_numeric( $pm_id ) ) {
				$p_message = wpj_get_pm_notify( $fields = 'initiator, user', ['id' => $pm_id], 'row' );

				$allowed_users[] = $p_message->initiator; // sender
				$allowed_users[] = $p_message->user; // receiver

			} elseif ( $message_id && is_numeric( $message_id ) ) {
				// get message
				$o_message = wpj_get_order_notification_message( $fields = 'oid', ['id' => $message_id],  'row' );

				// get order based on message id, then post based on order pid
				$order = wpj_get_job_order( 'pid, uid', ['id' => $o_message->oid], 'row' );
				$post  = get_post( $order->pid );

				$allowed_users[] = $post->post_author; // seller
				$allowed_users[] = $order->uid; // buyer

			} elseif ( $job_id && is_numeric( $job_id ) ) {
				// add job author to the array
				$post = get_post( $job_id );
				$allowed_users[] = $post->post_author; // seller

				// loop and add to the array all the buyers of this job
				$all_orders = wpj_get_job_order( 'DISTINCT *', ['pid' => $job_id], 'results' );

				foreach ( $all_orders as $order ) {
					$allowed_users[] = $order->uid; // buyer
				}

			} else {
				// no user specified for this download
				$direct_download = 1;

			}

			if ( ! is_user_logged_in() ) {
				if ( isset( $_GET['auth_token'] ) ) {
					$auth_token_transient = get_post_meta_transient( $_GET['secure_download'], 'wpj_authentication_token' );

					if ( $_GET['auth_token'] == $auth_token_transient ) {
						$direct_download = 1;
					}
				}
			}

			if ( user_can( $current_user, 'manage_options' ) || in_array( $current_user->ID, $allowed_users ) || $direct_download ) {
				$file = get_attached_file( $attachment_id );

				if ( $file ) {
					$filename = basename( $file );

					if ( strstr( $_SERVER['HTTP_USER_AGENT'], "MSIE" ) ) {
						header( 'Content-Type: application/octet-stream' );
						header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
						header( 'Expires: 0' );
						header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
						header( 'Content-Transfer-Encoding: binary' );
						header( 'Pragma: public' );
						header( 'Content-Length: ' . filesize( $file ) );
					} else {
						header( 'Content-Type: application/octet-stream' );
						header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
						header( 'Content-Transfer-Encoding: binary' );
						header( 'Expires: 0' );
						header( 'Pragma: no-cache' );
						header( 'Content-Length: ' . filesize( $file ) );
					}

					if ( function_exists( 'fopen' ) && function_exists( 'fpassthru') && function_exists( 'fclose' ) ) {
						$fp = @fopen( $file, 'rb' );

						if ( $fp ) {
							fpassthru( $fp );
							fclose( $fp );

						} else {
							exit( __( 'Error opening file!', 'wpjobster' ) );

						}

					} elseif ( ini_get( 'output_buffering' ) ) {
						ob_clean();
						flush();
						readfile( $file );

					}

					exit;
				} else {
					exit( __( 'Wrong attachment ID!', 'wpjobster' ) );
				}

			}

			exit( __( 'You are not allowed to download this!', 'wpjobster' ) );
		}
	}
}