<?php
/**
 * Add Simple Metaboxes Settings
 *
 * Author: Pojoksoft - http://www.pojoksoft.com
 *
 * @since 1.0.0
 * @package Lokerpro Core
 */

/**
 * Register a meta box using a class.
 *
 * @since 1.0.0
 */
class Lokerpro_Core_Metabox_Settings {

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_action( 'admin_footer', array( $this, 'lokerpro_core_admin_enqueue_scripts' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'lokerpro_core_admin_enqueue_style' ) );
		add_action( 'load-post.php', array( $this, 'post_metabox_setup' ) );
		add_action( 'load-post-new.php', array( $this, 'post_metabox_setup' ) );
	}

	/**
	 * Metabox setup function
	 */
	public function post_metabox_setup() {
		add_action( 'add_meta_boxes', array( $this, 'add_meta_box' ) );
		add_action( 'save_post', array( $this, 'save' ), 10, 2 );
	}

	/**
	 * Register the JavaScript.
	 */
	public function lokerpro_core_admin_enqueue_scripts() {
		global $post_type;
		if ( 'post' === $post_type ) {
			?>
			<script type="text/javascript">
				(function( $ ) {
					'use strict';

					/**
					 * From this point every thing related to metabox
					 */
					$('document').ready(function(){

						// Started Tab
						$('.group, .innergroup, .innergroup2').hide();
						// first tab
						var activetab = '';
						if (typeof(localStorage) != 'undefined' ) {
							activetab = localStorage.getItem("activetab");
						}
						if (activetab != '' && $(activetab).length ) {
							$(activetab).fadeIn();
						} else {
							$('.group:first').fadeIn();
						}
						if (activetab != '' && $(activetab + '-tab').length ) {
							$(activetab + '-tab').addClass('nav-tab-active');
						}
						else {
							$('.nav-tab-wrapper a:first').addClass('nav-tab-active');
						}
						$('.nav-tab-wrapper a').click(function(evt) {
							$('.nav-tab-wrapper a').removeClass('nav-tab-active');
							$(this).addClass('nav-tab-active').blur();
							var clicked_group = $(this).attr('href');
							if (typeof(localStorage) != 'undefined' ) {
								localStorage.setItem("activetab", $(this).attr('href'));
							}
							$('.group').hide();
							$(clicked_group).fadeIn();
							evt.preventDefault();
						});
						// First tab inner
						var activeinnertab = '';
						if (typeof(localStorage) != 'undefined' ) {
							activeinnertab = localStorage.getItem("activeinnertab");
						}
						if (activeinnertab != '' && $(activeinnertab).length ) {
							$(activeinnertab).fadeIn();
						} else {
							$('.innergroup:first').fadeIn();
						}
						if (activeinnertab != '' && $(activeinnertab + '-innertab').length ) {
							$(activeinnertab + '-innertab').addClass('current');
						}
						else {
							$('.lokerpro-meta-innertab-wrapper a:first').addClass('current');
						}
						$('.lokerpro-meta-innertab-wrapper a').click(function(evt) {
							$('.lokerpro-meta-innertab-wrapper a').removeClass('current');
							$(this).addClass('current').blur();
							var clicked_group = $(this).attr('href');
							if (typeof(localStorage) != 'undefined' ) {
								localStorage.setItem("activeinnertab", $(this).attr('href'));
							}
							$('.innergroup').hide();
							$(clicked_group).fadeIn();
							evt.preventDefault();
						});
						// Second tab inner
						var activeinnertab2 = '';
						if (typeof(localStorage) != 'undefined' ) {
							activeinnertab2 = localStorage.getItem("activeinnertab2");
						}
						if (activeinnertab2 != '' && $(activeinnertab2).length ) {
							$(activeinnertab2).fadeIn();
						} else {
							$('.innergroup2:first').fadeIn();
						}
						if (activeinnertab2 != '' && $(activeinnertab2 + '-innertab2').length ) {
							$(activeinnertab2 + '-innertab2').addClass('current');
						}
						else {
							$('.lokerpro-meta-innertab2-wrapper a:first').addClass('current');
						}
						$('.lokerpro-meta-innertab2-wrapper a').click(function(evt) {
							$('.lokerpro-meta-innertab2-wrapper a').removeClass('current');
							$(this).addClass('current').blur();
							var clicked_group = $(this).attr('href');
							if (typeof(localStorage) != 'undefined' ) {
								localStorage.setItem("activeinnertab2", $(this).attr('href'));
							}
							$('.innergroup2').hide();
							$(clicked_group).fadeIn();
							evt.preventDefault();
						});
						$('.dlbutton-add-row').on('click', function(e) {
							e.preventDefault();
							var $target = $($(this).data('target'));
							var row = $target.find('.dlbutton-empty-row').clone(true);
							var input = row.find('input');
							if (typeof input.data('name') !== 'undefined' && input.data('name')) input.prop('name', input.data('name'));
							input.filter('[name="lokerpro_dlbutton_item_url[]"]').addClass('lokerpro-url');
							row.removeClass('dlbutton-empty-row screen-reader-text');
							row.insertBefore($target.find('tbody>tr:last'));
							row.find(".lokerpro-focus-on-add").focus();
						});

						$('.dlbutton-remove-row').on('click', function(e) {
							e.preventDefault();
							$(this).closest('tr').remove();
						});
						// Start uploader
						$('.core-metaposer-browse').on('click', function (event) {
							event.preventDefault();

							var self = $(this);

							// Create the media frame.
							var file_frame = wp.media.frames.file_frame = wp.media({
								title: self.data('uploader_title'),
								button: {
									text: self.data('uploader_button_text'),
								},
								multiple: false
							});

							file_frame.on('select', function () {
								var attachment = file_frame.state().get('selection').first().toJSON();
								self.prev('.core-metaposer-url').val(attachment.url).change();
							});

							// Finally, open the modal
							file_frame.open();
						});
					});
				})( jQuery );
			</script>
			<?php
		}
	}

	/**
	 * Register the CSS.
	 */
	public function lokerpro_core_admin_enqueue_style() {
		global $post_type;
		if ( 'post' === $post_type ) {
			?>
			<style type="text/css">
			.lokerpro-pricecurrency-item th,
			.lokerpro-dlbutton-item th {text-align: left !important;}
			.core-metabox-common-fields .lokerpro-dlbutton-item,
			.core-metabox-common-fields .box-meta {margin-top: 20px;}
			.core-metabox-common-fields a.display-block,
			.core-metabox-common-fields input.display-block,
			.core-metabox-common-fields textarea.display-block{display:block;width:100%;}
			.core-metabox-common-fields input[type="button"].display-block {margin-top:10px;}
			.core-metabox-common-fields a.display-block {text-align:center;}
			.core-metabox-common-fields label {display: block;margin-bottom: 5px;}
			.core-metabox-common-fields input[disabled] {background: #ddd;}
			.core-metabox-common-fields .nav-tab-active,
			.core-metabox-common-fields .nav-tab-active:focus,
			.core-metabox-common-fields .nav-tab-active:focus:active,
			.core-metabox-common-fields .nav-tab-active:hover {
				border-bottom: 1px solid #ffffff !important;
				background: #ffffff !important;
				color: #000;
			}
			</style>
			<?php
		}
	}

	/**
	 * Adds the meta box.
	 *
	 * @param string $post_type Post type.
	 */
	public function add_meta_box( $post_type ) {
		$post_types = array( 'post' );
		if ( in_array( $post_type, $post_types, true ) ) {
			add_meta_box(
				'lokerpro_core_video_meta_metabox',
				__( 'Lokerpro Meta Post Settings', 'lokerpro' ),
				array( $this, 'metabox_callback' ),
				$post_type,
				'advanced',
				'default'
			);
		}
	}

	/**
	 * Get homepage without http/https and www
	 *
	 * @since 1.0.0
	 * @return string
	 */
	private function meta_get_home() {
		$protocols = array( 'http://', 'https://', 'http://www.', 'https://www.', 'www.' );
		return str_replace( $protocols, '', home_url() );
	}

	/**
	 * Save the meta box.
	 *
	 * @param int   $post_id Post ID.
	 * @param array $post Post.
	 * @return int $post_id
	 */
	public function save( $post_id, $post ) {
		/* Verify the nonce before proceeding. */
		if ( ! isset( $_POST['lokerpro_core_video_meta_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['lokerpro_core_video_meta_nonce'] ) ), basename( __FILE__ ) ) ) {
			return $post_id;
		}

		/* Get the post type object. */
		$post_type = get_post_type_object( $post->post_type );

		/* Check if the current user has permission to edit the post. */
		if ( ! current_user_can( $post_type->cap->edit_post, $post_id ) ) {
			return $post_id;
		}

		/* List of meta box fields (name => meta_key) */
		$fields = array(
			'core-version-value'   => 'LOKERPRO_Amount',
			'core-system-value'    => 'LOKERPRO_System',
			'core-filesize-value'  => 'LOKERPRO_Filesize',
			'core-license-value'   => 'LOKERPRO_License',
			'core-developer-value' => 'LOKERPRO_Developer',
			'core-pengalaman-value' => 'LOKERPRO_Pengalaman',
			'core-closingdate-value' => 'LOKERPRO_ClosingDate',
			'core-currency-value'  => 'LOKERPRO_Currency',
			'core-price-value'     => 'LOKERPRO_Price',
			'core-poster-value'    => 'LOKERPRO_Thumbnail',
			'core-image-gallery'   => 'LOKERPRO_Gallery',
		);

		foreach ( $fields as $name => $meta_key ) {
			/* Check if meta box fields has a proper value */
			if ( isset( $_POST[ $name ] ) && 'N/A' !== $_POST[ $name ] ) {
				/* Set thumbnail */
				if ( 'core-poster-value' === $name ) {
					global $post;
					$already_has_thumb = has_post_thumbnail( $post->ID );
					// if not set featured image, do not set post thumbnail.
					if ( ! $already_has_thumb ) {
						global $wpdb;
						$image_src     = sanitize_text_field( wp_unslash( $_POST[ $name ] ) );
						$query         = "SELECT ID FROM {$wpdb->posts} WHERE guid='$image_src'";
						$attachment_id = $wpdb->get_var( $query ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
						set_post_thumbnail( $post->ID, $attachment_id );
					}
				}
				$new_meta_value = sanitize_text_field( wp_unslash( $_POST[ $name ] ) );
			} else {
				$new_meta_value = '';
			}

			/* Get the meta value of the custom field key */
			$meta_value = get_post_meta( $post_id, $meta_key, true );

			/* If a new meta value was added and there was no previous value, add it. */
			if ( $new_meta_value && empty( $meta_value ) ) {
				add_post_meta( $post_id, $meta_key, $new_meta_value, true );
				/* If the new meta value does not match the old value, update it. */
			} elseif ( $new_meta_value && $new_meta_value !== $meta_value ) {
				update_post_meta( $post_id, $meta_key, $new_meta_value );

				/* If there is no new meta value but an old value exists, delete it. */
			} elseif ( empty( $new_meta_value ) && $meta_value ) {
				delete_post_meta( $post_id, $meta_key, $meta_value );

			}
		}

		/* Repeatable update and delete meta fields method. */
		$title = isset( $_POST['lokerpro_dlbutton_item_title'] ) ? $_POST['lokerpro_dlbutton_item_title'] : '';
		$url   = isset( $_POST['lokerpro_dlbutton_item_url'] ) ? $_POST['lokerpro_dlbutton_item_url'] : '';

		$old = get_post_meta( $post_id, 'lokerpro_dlbutton_item', true );
		$new = array();

		$count = count( $title );

		for ( $i = 0; $i < $count; $i++ ) {
			if ( ! empty( $title[ $i ] ) ) {
				$new[ $i ]['lokerpro_dlbutton_item_title'] = sanitize_text_field( wp_unslash( $title[ $i ] ) );
			}
			if ( ! empty( $url[ $i ] ) ) {
				$new[ $i ]['lokerpro_dlbutton_item_url'] = sanitize_text_field( wp_unslash( $url[ $i ] ) );
			}
		}

		if ( ! empty( $new ) && $new !== $old ) {
			update_post_meta( $post_id, 'lokerpro_dlbutton_item', $new );
		} elseif ( empty( $new ) && $old ) {
			delete_post_meta( $post_id, 'lokerpro_dlbutton_item', $old );
		}

	}

	/**
	 * Meta box html view
	 *
	 * @param array  $object Object Post Type.
	 * @param string $box returning string.
	 */
	public function metabox_callback( $object, $box ) {
		global $post;
		// Add an nonce field so we can check for it later.
		wp_nonce_field( basename( __FILE__ ), 'lokerpro_core_video_meta_nonce' );
		$items = get_post_meta( $post->ID, 'lokerpro_dlbutton_item', true );
		
		$hm         = md5( $this->meta_get_home() );
		$license    = trim( get_option( 'lokerpro_core_license_key' . $hm ) );
		$upload_dir = wp_upload_dir();

					?>
					<div id="col-container">
						<div class="metabox-holder core-metabox-common-fields">

							<h3 class="nav-tab-wrapper">
								<a class="nav-tab" id="lokerpro-meta-settings-tab" href="#lokerpro-meta-settings"><?php esc_html_e( 'Job Vacancies Settings:', 'lokerpro' ); ?></a>
								<a class="nav-tab" id="lokerpro-meta-download-tab" href="#lokerpro-meta-download"><?php esc_html_e( 'Job Vacancies Apply Link Settings:', 'lokerpro' ); ?></a>
							</h3>

							<div id="lokerpro-meta-settings" class="group" style="display: none;">
								<div id="lokerpro-version" class="box-meta">
									<label for="opsi-version"><strong><?php esc_html_e( 'Total Job Opening:', 'lokerpro' ); ?></strong></label>
									<input type="text" class="regular-text display-block" id="opsi-version" placeholder="<?php esc_html_e( 'Example: 2', 'lokerpro' ); ?>" name="core-version-value" value="<?php echo esc_attr( get_post_meta( $object->ID, 'LOKERPRO_Amount', true ) ); ?>" />
									<span class="howto"><?php esc_attr_e( 'Enter Total Job Opening at this company', 'lokerpro' ); ?></span>
								</div>
								<div id="lokerpro-system" class="box-meta">
									<label for="opsi-version"><strong><?php esc_html_e( 'Job Location:', 'lokerpro' ); ?></strong></label>
									<input type="text" class="regular-text display-block" id="opsi-system" placeholder="<?php esc_html_e( 'Example: Jakarta', 'lokerpro' ); ?>" name="core-system-value" value="<?php echo esc_attr( get_post_meta( $object->ID, 'LOKERPRO_System', true ) ); ?>" />
									<span class="howto"><?php esc_attr_e( 'Enter job location, for example: Jakarta, Bandung.', 'lokerpro' ); ?></span>
								</div>
								<div id="lokerpro-license" class="box-meta">
									<label for="opsi-license"><strong><?php esc_html_e( 'Employment Type:', 'lokerpro' ); ?></strong></label>
									<input type="text" class="regular-text display-block" id="opsi-license" placeholder="<?php esc_html_e( 'Example: Full Time', 'lokerpro' ); ?>" name="core-license-value" value="<?php echo esc_attr( get_post_meta( $object->ID, 'LOKERPRO_License', true ) ); ?>" />
									<span class="howto"><?php esc_attr_e( 'Enter Employment Type. For example: Full Time, Part Time', 'lokerpro' ); ?></span>
								</div>
								<div id="lokerpro-developer" class="box-meta">
									<label for="opsi-developer"><strong><?php esc_html_e( 'Education Requirements:', 'lokerpro' ); ?></strong></label>
									<input type="text" class="regular-text display-block" id="opsi-developer" placeholder="<?php esc_html_e( 'Example: S1', 'lokerpro' ); ?>" name="core-developer-value" value="<?php echo esc_attr( get_post_meta( $object->ID, 'LOKERPRO_Developer', true ) ); ?>" />
									<span class="howto"><?php esc_attr_e( 'Educational background needed for the position or Occupation. For example: SMA, D3, S1, S2.', 'lokerpro' ); ?></span>
								</div>
								<div id="lokerpro-pengalaman" class="box-meta">
									<label for="opsi-pengalaman"><strong><?php esc_html_e( 'Experience Requirements:', 'lokerpro' ); ?></strong></label>
									<input type="text" class="regular-text display-block" id="opsi-pengalaman" placeholder="<?php esc_html_e( 'Example: 0 - 2 Years', 'lokerpro' ); ?>" name="core-pengalaman-value" value="<?php echo esc_attr( get_post_meta( $object->ID, 'LOKERPRO_Pengalaman', true ) ); ?>" />
									<span class="howto"><?php esc_attr_e( 'Minimum Experience needed for the position or Occupation. For example: 0 - 2 Years', 'lokerpro' ); ?></span>
								</div>
								<div id="lokerpro-closingdate" class="box-meta">
									<label for="opsi-closingdate"><strong><?php esc_html_e( 'Closing Date:', 'lokerpro' ); ?></strong></label>
									<input type="date" class="regular-text display-block" id="opsi-closingdate" name="core-closingdate-value" value="<?php echo esc_attr( get_post_meta( $object->ID, 'LOKERPRO_ClosingDate', true ) ); ?>" />
									<span class="howto"><?php esc_attr_e( 'Registration Closing Date. For example: January 2, 2022.', 'lokerpro' ); ?></span>
								</div>
								<div id="lokerpro-image-gallery" class="box-meta">
									<label for="opsi-image-gallery"><strong><?php esc_html_e( 'Shortcode Gallery:', 'lokerpro' ); ?></strong></label>
									<textarea name="core-image-gallery" id="opsi-image-gallery" rows="4" cols="55" class="regular-text display-block"><?php echo esc_textarea( get_post_meta( $object->ID, 'LOKERPRO_Gallery', true ) ); ?></textarea>
									<span class="howto"><?php esc_attr_e( 'This is to put pictures related to the locker/company, format: [lokerpro-gallery image_url="URL of image 1, URL of image 2, URL of image 3"]', 'lokerpro' ); ?></span>
								</div>
							</div>

							<div id="lokerpro-meta-download" class="group" style="display: none;">
								<!-- Start repeater field -->
								<table id="lokerpro-dlbutton-item" class="lokerpro-dlbutton-item" width="100%">

									<thead>
										<tr>
											<th width="48%"><?php esc_html_e( 'Job Vacancy Link Title', 'lokerpro' ); ?></th>
											<th width="48%"><?php esc_html_e( 'Link Apply Job Vacancies', 'lokerpro' ); ?></th>
											<th width="4%"></th>
										</tr>
									</thead>

									<tbody>
										<?php if ( ! empty( $items ) ) : ?>

											<?php
											foreach ( $items as $item ) {
												if ( ! empty( $item['lokerpro_dlbutton_item_title'] ) ) {
													$title = $item['lokerpro_dlbutton_item_title'];
												} else {
													$title = '';
												}
												if ( ! empty( $item['lokerpro_dlbutton_item_url'] ) ) {
													$uri = $item['lokerpro_dlbutton_item_url'];
												} else {
													$uri = '';
												}
												?>
												<tr>
													<td>
														<input type="text" class="regular-text display-block" name="lokerpro_dlbutton_item_title[]" placeholder="<?php esc_html_e( 'Example: Website Developer', 'lokerpro' ); ?>" value="<?php echo esc_attr( $title ); ?>" />
													</td>
													<td>
														<input type="url" class="regular-text display-block" name="lokerpro_dlbutton_item_url[]" placeholder="<?php esc_html_e( 'Example: https://pojoksoft.com/', 'lokerpro' ); ?>" value="<?php echo esc_url( $uri ); ?>" />
													</td>
													<td><a class="button dlbutton-remove-row display-block" href="#"><?php esc_html_e( 'Delete', 'lokerpro' ); ?></a></td>
												</tr>

											<?php } ?>

										<?php else : ?>
											<tr>
												<td><input type="text" class="regular-text display-block" placeholder="<?php esc_html_e( 'Example: Website Developer', 'lokerpro' ); ?>" name="lokerpro_dlbutton_item_title[]" /></td>
												<td><input type="url" class="regular-text display-block" placeholder="<?php esc_html_e( 'Example: https://pojoksoft.com/', 'lokerpro' ); ?>" name="lokerpro_dlbutton_item_url[]" /></td>
												<td><a class="button dlbutton-remove-row display-block" href="#"><?php esc_html_e( 'Delete', 'lokerpro' ); ?></a></td>
											</tr>

										<?php endif; ?>

										<!-- empty hidden one for jQuery -->
										<tr class="dlbutton-empty-row screen-reader-text">
											<td><input type="text" class="regular-text display-block lokerpro-focus-on-add" placeholder="<?php esc_html_e( 'Example: Website Developer', 'lokerpro' ); ?>" name="lokerpro_dlbutton_item_title[]" /></td>
											<td><input type="url" class="regular-text display-block" placeholder="<?php esc_html_e( 'Example: https://pojoksoft.com/', 'lokerpro' ); ?>" name="lokerpro_dlbutton_item_url[]" /></td>
											<td><a class="button dlbutton-remove-row display-block" href="#"><?php esc_html_e( 'Delete', 'lokerpro' ); ?></a></td>
										</tr>

									</tbody>

								</table>
								<table width="100%">
									<tr>
										<td><a class="dlbutton-add-row button display-block" data-target="#lokerpro-dlbutton-item" href="#"><?php esc_html_e( 'Add another', 'lokerpro' ); ?></a></td>
									</tr>
								</table>
								<span class="howto"><?php esc_html_e( 'Please enter the title and URL of the job vacancy. You can click "Add Another" to add a new job vacancy position and click "Delete" to remove a job vacancy position.', 'lokerpro' ); ?></span>
							</div>
						</div>
					</div>

				<?php

	}

}

// Load only if dashboard.
if ( is_admin() ) {
	new Lokerpro_Core_Metabox_Settings();
}