<?php
/**
 * Deprecated Nisje functionality
 *
 * @package Nisje
 */

// Temporary Metabox fix.
add_action( 'add_meta_boxes', function() {
	add_meta_box(
		'nisje_attachments',
		esc_html__( 'Attachments', 'nisje' ),
		function( $post ) {
			wp_nonce_field( '_nisje_delete_attachment', '_nisje_attachment_nonce' );

			$attachments = nisje_get_post_attachments( $post );

			if ( ! empty( $attachments['attachments'] ) ) {
				?>
				<input type="hidden" name="has-nisje-attachments" value="1" />
				<ul class="nisje-attachments">
					<?php
					foreach ( $attachments['attachments'] as $attachment ) {
						?>
						<li class="nisje-attachment-delete-<?php echo esc_attr( $attachment['id'] ); ?>" style="border-bottom: 1px #ccc solid; padding-bottom: 20px;">
							<p><?php echo esc_html( $attachment['title'] ); ?></p>
							<button><?php esc_html_e( 'Delete attachment', 'nisje' ); ?></button>

							<input type="hidden" name="nisje-attachments[]" value="<?php echo esc_attr( $attachment['id'] ); ?>" />
						</li>
						<?php
					}
					?>
				</ul>
				<script>
				var delete_buttons = document.querySelectorAll( '.nisje-attachments button' );
				var empty = "<?php echo esc_js( esc_html__( 'There are no attachments connected to this post', 'nisje' ) ); ?>";
				for ( var i = 0; i < delete_buttons.length; i++ ) {
					delete_buttons[i].addEventListener( 'click', function( e ) {
						e.target.parentElement.remove();

						if ( 0 === document.querySelectorAll( 'ul.nisje-attachments li' ).length ) {
							var list = document.querySelector( 'ul.nisje-attachments' );
							var li = document.createElement( 'li' );
							li.appendChild( document.createTextNode( empty ) );
							list.appendChild( li );
						}
					} );
				}
				</script>
				<?php
			} else {
				?>
				<p><?php esc_html_e( 'There are no attachments connected to this post', 'nisje' ); ?></p>
				<?php
			}
		},
		[
			'dekode-wiki',
			'dekode-news',
		],
		'side'
	);
} );

// Save field.
add_action( 'save_post', function( $post_id ) {
	if ( isset( $_POST['has-nisje-attachments'], $_POST['_nisje_attachment_nonce'] ) && wp_verify_nonce( $_POST['_nisje_attachment_nonce'], '_nisje_delete_attachment' ) ) { // phpcs:ignore
		if ( isset( $_POST['nisje-attachments'] ) ) {
			update_post_meta( $post_id, 'attachments', array_map( 'absint', $_POST['nisje-attachments'] ) ); // phpcs:ignore
		} else {
			delete_post_meta( $post_id, 'attachments' );
		}
	}
} );
