<?php
/**
 * DSM Attachment Fields Handler
 * 
 * Handles all gallery-related functionality for Divi Supreme Modules
 * 
 * @since 1.0.0
 * @package dsm-supreme-modules-pro-for-divi
 */

// Prevent direct access
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Initialize gallery-related hooks
 */
function dsm_init_attachment_fields() {
	// Gallery hooks
	add_filter( 'attachment_fields_to_edit', 'dsm_attachment_fields_to_edit', 10, 2 );
	add_filter( 'attachment_fields_to_save', 'dsm_attachment_fields_to_save', 10, 2 );
	add_action( 'init', 'dsm_attachment_category_fields', 1 );
	add_action( 'init', 'dsm_add_categories_to_attachments', 1 );
	add_action( 'wp_ajax_divi_supreme_get_attachments', 'dsm_divi_supreme_get_attachments' );
}

/**
 * For Divi Upload Gallery Fields To Edit
 *
 * @since 1.0.0
 * @param array $fields The existing fields
 * @param WP_Post $post The post object
 * @return array Modified fields
 */
function dsm_attachment_fields_to_edit( $fields, $post ) {
	$fields['dsm_gallery_fields_title'] = array(
		'label' => __( 'For Divi Supreme Modules only', 'dsm-supreme-modules-pro-for-divi' ),
		'input' => 'html',
		'html'  => __( ' ', 'dsm-supreme-modules-pro-for-divi' ),
	);

	$custom_link_url_value                        = get_post_meta( $post->ID, 'dsm_upload_gallery_custom_link_url', true );
	$fields['dsm_upload_gallery_custom_link_url'] = array(
		'label' => __( 'Link URL', 'dsm-supreme-modules-pro-for-divi' ),
		'input' => 'text',
		'value' => $custom_link_url_value ? $custom_link_url_value : '',
	);
	$target_value                                 = get_post_meta( $post->ID, 'dsm_upload_gallery_link_url_target', true );
	$fields['dsm_upload_gallery_link_url_target'] = array(
		'label' => __( 'Link Target', 'dsm-supreme-modules-pro-for-divi' ),
		'input' => 'html',
		'html'  => '
			<select class="widefat" name="attachments[' . $post->ID . '][dsm_upload_gallery_link_url_target]" id="attachments[' . $post->ID . '][dsm_upload_gallery_link_url_target]">
				<option value="_self"' . ( '_self' === $target_value ? ' selected="selected"' : '' ) . '>' .
					__( 'In The Same Window', 'dsm-supreme-modules-pro-for-divi' ) .
				'</option>
				<option value="_blank"' . ( '_blank' === $target_value ? ' selected="selected"' : '' ) . '>' .
					__( 'In The New Tab', 'dsm-supreme-modules-pro-for-divi' ) .
				'</option>
			</select>',
	);

	$download_as_file                                   = get_post_meta( $post->ID, 'dsm_upload_gallery_link_as_download_file', true );
	$fields['dsm_upload_gallery_link_as_download_file'] = array(
		'label' => __( ' ', 'dsm-supreme-modules-pro-for-divi' ),
		'input' => 'html',
		'html'  => '<input type="checkbox" value="1" name="attachments[' . $post->ID . '][dsm_upload_gallery_link_as_download_file]" id="attachments[' . $post->ID . '][dsm_upload_gallery_link_as_download_file]" ' . checked( 1, get_post_meta( $post->ID, 'dsm_upload_gallery_link_as_download_file', true ), false ) . '/> Download as file',
	);
	return $fields;
}

/**
 * For Divi Upload Gallery Fields To Save
 *
 * @since 1.0.0
 * @param array $post The post data
 * @param array $attachment The attachment data
 * @return array Modified post data
 */
function dsm_attachment_fields_to_save( $post, $attachment ) {
	if ( isset( $attachment['dsm_upload_gallery_custom_link_url'] ) ) {
		update_post_meta(
			$post['ID'],
			'dsm_upload_gallery_custom_link_url',
			esc_url_raw( wp_unslash( (string) $attachment['dsm_upload_gallery_custom_link_url'] ) )
		);
	}
	if ( isset( $attachment['dsm_upload_gallery_link_url_target'] ) ) {
		update_post_meta( $post['ID'], 'dsm_upload_gallery_link_url_target', $attachment['dsm_upload_gallery_link_url_target'] );
	}
	if ( isset( $attachment['dsm_upload_gallery_link_as_download_file'] ) ) {
		update_post_meta( $post['ID'], 'dsm_upload_gallery_link_as_download_file', $attachment['dsm_upload_gallery_link_as_download_file'] );
	}
	return $post;
}

/**
 * Add Custom Taxonomy Category to Media
 *
 * @since 4.8.88
 */
function dsm_add_categories_to_attachments() {
	// Currently empty function - keeping for compatibility
}

/**
 * Register attachment category fields
 *
 * @since 4.8.88
 */
function dsm_attachment_category_fields() {
	$labels = array(
		'name'              => __( 'Attachment Category - Divi Supreme', 'dsm-supreme-modules-pro-for-divi' ),
		'singular_name'     => __( 'Attachment Category - Divi Supreme', 'dsm-supreme-modules-pro-for-divi' ),
		'search_items'      => __( 'Search Categories', 'dsm-supreme-modules-pro-for-divi' ),
		'all_items'         => __( 'All Categories', 'dsm-supreme-modules-pro-for-divi' ),
		'parent_item'       => __( 'Parent Category', 'dsm-supreme-modules-pro-for-divi' ),
		'parent_item_colon' => __( 'Parent Category:', 'dsm-supreme-modules-pro-for-divi' ),
		'edit_item'         => __( 'Edit Category', 'dsm-supreme-modules-pro-for-divi' ),
		'update_item'       => __( 'Update Category', 'dsm-supreme-modules-pro-for-divi' ),
		'add_new_item'      => __( 'Add New Category', 'dsm-supreme-modules-pro-for-divi' ),
		'new_item_name'     => __( 'New Category Name', 'dsm-supreme-modules-pro-for-divi' ),
		'menu_name'         => __( 'Categories', 'dsm-supreme-modules-pro-for-divi' ),
	);

	$args = array(
		'hierarchical'      => true,
		'labels'            => $labels,
		'show_ui'           => true,
		'show_admin_column' => true,
		'query_var'         => true,
		'rewrite'           => array( 'slug' => 'dsm-attachment-category' ),
	);

	register_taxonomy( 'dsm-attachment-category', array( 'attachment' ), $args );
	global $wp_taxonomies;
	if ( ! taxonomy_exists( 'dsm-attachment-category' ) ) {
		return false;
	}

	$wp_taxonomies['dsm-attachment-category']->update_count_callback = '_update_generic_term_count';
}

/**
 * Get Attachment Categories for Filterable Gallery
 *
 * @since 4.8.88
 */
function dsm_divi_supreme_get_attachments() {
	$nonce = isset( $_REQUEST['nonce'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['nonce'] ) ) : '';

	if ( ! wp_verify_nonce( $nonce, 'dsm_filterable_gallery' ) ) {
		echo wp_json_encode( array() );
		wp_die();
	}
	
	$ids         = isset( $_REQUEST['ids'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['ids'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification
	$categories  = isset( $_REQUEST['categories'] ) ? array_map( 'sanitize_text_field', wp_unslash( $_REQUEST['categories'] ) ) : array();
	$use_dynamic = isset( $_REQUEST['dynamic'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['dynamic'] ) ) : false; // phpcs:ignore WordPress.Security.NonceVerification
	$max         = isset( $_REQUEST['max'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['max'] ) ) : -1; // phpcs:ignore WordPress.Security.NonceVerification
	$order       = isset( $_REQUEST['order'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['order'] ) ) : 'ASC'; // phpcs:ignore WordPress.Security.NonceVerification

	$attachments = array();

	$defaults = array(
		'gallery_ids'        => array_map(
			function ( $id ) {
				return (int) $id;
			},
			explode( ',', $ids )
		),
		'gallery_orderby'    => '',
		'include_categories' => '',
		'posts_per_page'     => 10,
		'order'              => 'ASC',
	);

	$args     = wp_parse_args( $args, $defaults );
	$per_page = (int) $args['posts_per_page'];

	$attachments_args = array(
		'include'        => $args['gallery_ids'],
		'post_status'    => 'inherit',
		'post_type'      => 'attachment',
		'post_mime_type' => 'image',
		'order'          => $order,
	);

	if ( 'true' !== $use_dynamic ) {
		unset( $attachments_args['order'] );
		$attachments_args['orderby'] = 'post__in';
	}

	if ( 'true' === $use_dynamic ) {
		$attachments_args['numberposts'] = $max;
	}

	if ( 'true' === $use_dynamic ) {
		// Unsetting selected images.
		unset( $attachments_args['orderby'] );
		unset( $attachments_args['include'] );

		$attachments_args['tax_query'] = array(
			array(
				'taxonomy' => 'dsm-attachment-category',
				'field'    => 'term_id',
				'terms'    => $categories,
			),
		);
	}

	$_attachments = get_posts( $attachments_args );

	foreach ( $_attachments as $key => $val ) {
		$attachments[ $key ] = $_attachments[ $key ];

		$available_sizes = get_intermediate_image_sizes();

		$sizes = array();

		foreach ( $available_sizes as $available_size ) {
			$attachment_src_data = wp_get_attachment_image_src( $val->ID, $available_size );

			if ( false !== $attachment_src_data ) {
				$sizes[ $available_size ] = $attachment_src_data[0]; // Only attaching source.
			}
		}

		$attachments[ $key ]->sizes = $sizes;

		$current_categories = get_the_terms( $val->ID, 'dsm-attachment-category' );

		$all_category         = new stdClass();
		$all_category->name   = 'all';
		$current_categories[] = $all_category;

		$attachment_categories = array();

		foreach ( $current_categories as $category ) {
			$attachment_categories[] = array(
				'name' => $category->name,
				'id'   => $category->term_id,
				'slug' => $category->slug,
			);
		}

		// Attaching categories and caption.
		$attachments[ $key ]->categories  = $attachment_categories;
		$attachments[ $key ]->caption     = wp_get_attachment_caption( $val->ID );
		$attachments[ $key ]->description = $val->post_content;
	}

	echo wp_json_encode( $_attachments );

	wp_die();
}

// Initialize the attachment fields functionality
dsm_init_attachment_fields(); 