<?php

/**
 * Shortcode registration and rendering for the [mediat_gallery] gallery.
 *
 * @package MediaTasker
 */
// Prevent direct file access.
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
/**
 * Class Mediat_Shortcode
 *
 * Registers the [mediat_gallery] shortcode and renders
 * the responsive task gallery with filter controls.
 */
class Mediat_Shortcode {
    /**
     * Hook into WordPress.
     *
     * @return void
     */
    public static function init() {
        add_shortcode( 'mediat_gallery', array(__CLASS__, 'render_shortcode') );
    }

    /**
     * Render the [mediat_gallery] shortcode output.
     *
     * @param array  $atts    Shortcode attributes (unused for now).
     * @param string $content Shortcode inner content (unused).
     * @return string HTML output for the gallery.
     */
    public static function render_shortcode( $atts = array(), $content = '' ) {
        if ( !is_user_logged_in() ) {
            return self::render_login_prompt();
        }
        ob_start();
        $options = get_option( 'mediat_options', Mediat_Settings::get_default_options() );
        $allowed = ( isset( $options['allowed_file_types'] ) ? $options['allowed_file_types'] : 'jpg,jpeg,png,gif,pdf' );
        $max_size_mb = ( isset( $options['max_file_size'] ) ? absint( $options['max_file_size'] ) : 5 );
        ?>
		<section class="mediat_workspace view-original" id="media-viewport">

			<?php 
        if ( is_user_logged_in() && current_user_can( 'upload_files' ) ) {
            ?>
				<div class="mediat_upload-zones">
					<!-- Primary Upload Area -->
					<div class="mediat_upload-panel mediat_upload-primary">
						<header class="mediat_panel-heading">
							<span
								class="mediat_badge mediat_badge-primary"><?php 
            esc_html_e( 'Upload Original Images', 'mediatasker' );
            ?></span>
						</header>
						<div class="mediat_drop-area" id="dropzone-primary" data-allowed="<?php 
            echo esc_attr( $allowed );
            ?>"
							data-max-size="<?php 
            echo esc_attr( $max_size_mb );
            ?>">
							<div class="mediat_drop-content">
								<p class="mediat_drop-instruction"><?php 
            esc_html_e( 'Drop original images here', 'mediatasker' );
            ?>
								</p>
								<div class="mediat_drop-actions">
									<span><?php 
            esc_html_e( 'or', 'mediatasker' );
            ?></span>
									<input type="file" id="mediat_file-primary" class="mediat_hidden-input" multiple
										accept="<?php 
            echo esc_attr( '.' . implode( ',.', array_map( 'trim', explode( ',', $allowed ) ) ) );
            ?>" />
									<label for="mediat_file-primary"
										class="mediat_btn mediat_btn-primary"><?php 
            esc_html_e( 'Select Files', 'mediatasker' );
            ?></label>
								</div>
							</div>
						</div>
						<div id="mediat_preview-primary" class="mediat_preview-grid"></div>
						<div id="mediat_progress-primary" class="mediat_progress-container" style="display: none;">
							<div class="mediat_progress-track">
								<div class="mediat_progress-fill"></div>
							</div>
							<div class="mediat_progress-label">0%</div>
						</div>
					</div>

					<!-- Secondary Upload Area -->
					<div class="mediat_upload-panel mediat_upload-secondary" style="display: none;">
						<header class="mediat_panel-heading">
							<span
								class="mediat_badge mediat_badge-secondary"><?php 
            esc_html_e( 'Upload Edited Images', 'mediatasker' );
            ?></span>
						</header>
						<div class="mediat_drop-area" id="dropzone-secondary" data-allowed="<?php 
            echo esc_attr( $allowed );
            ?>"
							data-max-size="<?php 
            echo esc_attr( $max_size_mb );
            ?>">
							<div class="mediat_drop-content">
								<p class="mediat_drop-instruction"><?php 
            esc_html_e( 'Drop edited images here', 'mediatasker' );
            ?>
								</p>
								<div class="mediat_drop-actions">
									<span><?php 
            esc_html_e( 'or', 'mediatasker' );
            ?></span>
									<input type="file" id="mediat_file-secondary" class="mediat_hidden-input" multiple
										accept="<?php 
            echo esc_attr( '.' . implode( ',.', array_map( 'trim', explode( ',', $allowed ) ) ) );
            ?>" />
									<label for="mediat_file-secondary"
										class="mediat_btn mediat_btn-secondary"><?php 
            esc_html_e( 'Select Files', 'mediatasker' );
            ?></label>
								</div>
							</div>
						</div>
						<div id="mediat_preview-secondary" class="mediat_preview-grid"></div>
						<div id="mediat_progress-secondary" class="mediat_progress-container" style="display: none;">
							<div class="mediat_progress-track">
								<div class="mediat_progress-fill"></div>
							</div>
							<div class="mediat_progress-label">0%</div>
						</div>
					</div>
				</div>
			<?php 
        }
        ?>

			<!-- View Toggles & Summary Data -->
			<nav class="mediat_view-switcher">
				<button type="button" class="mediat_switch-btn is-active" data-view="original">
					<?php 
        esc_html_e( 'Original', 'mediatasker' );
        ?> <span class="mediat_counter">0</span>
				</button>
				<button type="button" class="mediat_switch-btn" data-view="edited">
					<?php 
        esc_html_e( 'Edited', 'mediatasker' );
        ?> <span class="mediat_counter">0</span>
				</button>
			</nav>

			<aside class="mediat_summary-metrics">
				<div class="mediat_metric-group mediat_group-original is-active" id="mediat_summary-original">
					<div class="mediat_metric-total">
						<span class="mediat_metric-label"><?php 
        esc_html_e( 'Total Original Images:', 'mediatasker' );
        ?></span>
						<strong class="mediat_metric-value">0</strong>
					</div>
					<div class="mediat_status-breakdown">
						<div class="mediat_status-block status-pending" role="button" tabindex="0" data-status="pending"
							title="<?php 
        esc_attr_e( 'Click to select all pending items', 'mediatasker' );
        ?>">
							<span class="mediat_block-label"><?php 
        esc_html_e( 'Pending:', 'mediatasker' );
        ?></span>
							<strong class="mediat_block-value">0</strong>
						</div>
						<div class="mediat_status-block status-in-progress" role="button" tabindex="0" data-status="in-progress"
							title="<?php 
        esc_attr_e( 'Click to select all in-progress items', 'mediatasker' );
        ?>">
							<span class="mediat_block-label"><?php 
        esc_html_e( 'In Progress:', 'mediatasker' );
        ?></span>
							<strong class="mediat_block-value">0</strong>
						</div>
						<div class="mediat_status-block status-completed" role="button" tabindex="0" data-status="completed"
							title="<?php 
        esc_attr_e( 'Click to select all completed items', 'mediatasker' );
        ?>">
							<span class="mediat_block-label"><?php 
        esc_html_e( 'Completed:', 'mediatasker' );
        ?></span>
							<strong class="mediat_block-value">0</strong>
						</div>
						<?php 
        ?>
						<p class="mediat_status-hint">
							<?php 
        esc_html_e( 'Click any status box to show all items with that status. Click again to deselect.', 'mediatasker' );
        ?>
						</p>
					</div>
				</div>
				<div class="mediat_metric-group mediat_group-edited" style="display: none;" id="mediat_summary-edited">
					<div class="mediat_metric-total">
						<span class="mediat_metric-label"><?php 
        esc_html_e( 'Total Edited Images:', 'mediatasker' );
        ?></span>
						<strong class="mediat_metric-value">0</strong>
					</div>
					<div class="mediat_status-breakdown">
						<div class="mediat_status-block status-downloaded" data-status="downloaded">
							<span class="mediat_block-label"><?php 
        esc_html_e( 'Downloaded:', 'mediatasker' );
        ?></span>
							<strong class="mediat_block-value">0</strong>
						</div>
						<div class="mediat_status-block status-not-dl" data-status="not-dl">
							<span class="mediat_block-label"><?php 
        esc_html_e( 'Not Downloaded:', 'mediatasker' );
        ?></span>
							<strong class="mediat_block-value">0</strong>
						</div>
					</div>
				</div>
			</aside>

			<!-- Global Actions -->
			<div class="mediat_global-actions">
				<div class="mediat_action-toolbar" id="mediat_actions-original">
					<button type="button" class="mediat_action-btn btn-select-all">
						<span class="dashicons dashicons-yes-alt"></span>
						<?php 
        esc_html_e( 'Select All', 'mediatasker' );
        ?>
					</button>
					<button type="button" class="mediat_action-btn btn-download-all">
						<span class="dashicons dashicons-download"></span>
						<?php 
        esc_html_e( 'Download All', 'mediatasker' );
        ?> <span class="mediat_btn-counter">0</span>
					</button>
					<button type="button" class="mediat_action-btn btn-download-pending">
						<span class="dashicons dashicons-download"></span>
						<?php 
        esc_html_e( 'Download All Pending', 'mediatasker' );
        ?> <span class="mediat_btn-counter">0</span>
					</button>
				</div>
				<div class="mediat_action-toolbar" id="mediat_actions-edited" style="display: none;">
					<button type="button" class="mediat_action-btn btn-select-all">
						<span class="dashicons dashicons-yes-alt"></span>
						<?php 
        esc_html_e( 'Select All', 'mediatasker' );
        ?>
					</button>
					<button type="button" class="mediat_action-btn btn-download-all">
						<span class="dashicons dashicons-download"></span>
						<?php 
        esc_html_e( 'Download All', 'mediatasker' );
        ?> <span class="mediat_btn-counter">0</span>
					</button>
					<button type="button" class="mediat_action-btn btn-download-unread">
						<span class="dashicons dashicons-download"></span>
						<?php 
        esc_html_e( 'Download Not Downloaded', 'mediatasker' );
        ?> <span class="mediat_btn-counter">0</span>
					</button>
				</div>
			</div>

			<!-- Main Content Area -->
			<main class="mediat_asset-boards">
				<div class="mediat_board mediat_board-original is-active" id="mediat_grid-original">
					<?php 
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        echo self::get_gallery_html( '', 0, 'original' );
        ?>
				</div>
				<div class="mediat_board mediat_board-edited" style="display: none;" id="mediat_grid-edited">
					<?php 
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        echo self::get_gallery_html( '', 0, 'edited' );
        ?>
				</div>
			</main>

			<!-- Floating Control Bar -->
			<aside class="mediat_floating-controls">
				<div class="mediat_selection-count" title="<?php 
        esc_attr_e( 'Number of selected items', 'mediatasker' );
        ?>">0
				</div>

				<button type="button" class="mediat_float-btn action-deselect"
					title="<?php 
        esc_attr_e( 'Deselect All', 'mediatasker' );
        ?>">
					<span class="dashicons dashicons-no-alt"></span>
					<span><?php 
        esc_html_e( 'Deselect', 'mediatasker' );
        ?></span>
				</button>

				<div class="mediat_float-sep"></div>

				<div class="mediat_state-toggles">
					<button type="button" class="mediat_state-btn" data-state="pending"
						title="<?php 
        esc_attr_e( 'Set to Pending', 'mediatasker' );
        ?>">
						<span class="dashicons dashicons-clock"></span>
					</button>
					<button type="button" class="mediat_state-btn" data-state="in-progress"
						title="<?php 
        esc_attr_e( 'Set to In Progress', 'mediatasker' );
        ?>">
						<span class="dashicons dashicons-update"></span>
					</button>
					<button type="button" class="mediat_state-btn" data-state="completed"
						title="<?php 
        esc_attr_e( 'Set to Completed', 'mediatasker' );
        ?>">
						<span class="dashicons dashicons-yes-alt"></span>
					</button>
				</div>

				<div class="mediat_float-sep"></div>

				<?php 
        ?>

				<button type="button" class="mediat_float-btn action-download"
					title="<?php 
        esc_attr_e( 'Download Selected', 'mediatasker' );
        ?>">
					<span class="dashicons dashicons-download"></span>
					<span><?php 
        esc_html_e( 'Download', 'mediatasker' );
        ?></span>
				</button>

				<button type="button" class="mediat_float-btn action-delete"
					title="<?php 
        esc_attr_e( 'Delete Selected', 'mediatasker' );
        ?>">
					<span class="dashicons dashicons-trash"></span>
					<span><?php 
        esc_html_e( 'Delete', 'mediatasker' );
        ?></span>
				</button>
			</aside>

			<!-- Modals Overlay -->
			<div class="mediat_overlay-backdrop"></div>

			<!-- Bulk Comment Modal -->
			<?php 
        ?>

			<!-- Unified Media Viewer Modal -->
			<dialog class="mediat_viewer-modal">
				<div class="mediat_viewer-layout">
					<section class="mediat_viewer-main">
						<header class="mediat_viewer-header">
							<button type="button" class="mediat_viewer-close"
								title="<?php 
        esc_attr_e( 'Close', 'mediatasker' );
        ?>">
								<span class="dashicons dashicons-no-alt"></span>
							</button>
						</header>

						<div class="mediat_viewer-stage">
							<button type="button" class="mediat_nav-btn nav-prev"
								title="<?php 
        esc_attr_e( 'Previous Image', 'mediatasker' );
        ?>">
								<span class="dashicons dashicons-arrow-left-alt2"></span>
							</button>

							<div class="mediat_asset-container">
								<img src="" alt="" class="mediat_asset-preview" />
							</div>

							<button type="button" class="mediat_nav-btn nav-next"
								title="<?php 
        esc_attr_e( 'Next Image', 'mediatasker' );
        ?>">
								<span class="dashicons dashicons-arrow-right-alt2"></span>
							</button>
						</div>

						<footer class="mediat_viewer-footer">
							<div class="mediat_footer-toolbar">
								<div class="mediat_modal-status-controls">
									<div class="mediat_modal-status-buttons">
										<button type="button" class="mediat_modal-status-btn pending" data-status="pending"
											title="<?php 
        esc_attr_e( 'Pending', 'mediatasker' );
        ?>">
											<span class="dashicons dashicons-clock"></span>
										</button>
										<button type="button" class="mediat_modal-status-btn in-progress"
											data-status="in-progress"
											title="<?php 
        esc_attr_e( 'In Progress', 'mediatasker' );
        ?>">
											<span class="dashicons dashicons-update"></span>
										</button>
										<button type="button" class="mediat_modal-status-btn completed" data-status="completed"
											title="<?php 
        esc_attr_e( 'Completed', 'mediatasker' );
        ?>">
											<span class="dashicons dashicons-yes-alt"></span>
										</button>
									</div>
									<span
										class="mediat_modal-current-status"><?php 
        esc_html_e( 'Pending', 'mediatasker' );
        ?></span>
								</div>

								<?php 
        ?>

								<div class="mediat_entity-actions">

									<button type="button" class="tool-btn action-dl"
										title="<?php 
        esc_attr_e( 'Download Image', 'mediatasker' );
        ?>">
										<span class="dashicons dashicons-download"></span>
									</button>
									<button type="button" class="tool-btn action-rm"
										title="<?php 
        esc_attr_e( 'Delete Image', 'mediatasker' );
        ?>">
										<span class="dashicons dashicons-trash"></span>
									</button>
								</div>


							</div>
						</footer>
					</section>

					<aside class="mediat_viewer-sidebar">
						<header class="mediat_sidebar-header">
							<h3 class="mediat_asset-title"></h3>

						</header>

						<div class="mediat_sidebar-body">
							<?php 
        ?>

							<div class="mediat_discussion-section">
								<h4 class="mediat_section-title">
									<span class="dashicons dashicons-admin-comments"></span>
									<?php 
        esc_html_e( 'Discussion', 'mediatasker' );
        ?>
								</h4>
								<div class="mediat_thread-list"></div>
								<form class="mediat_thread-form">
									<textarea class="mediat_thread-input"
										placeholder="<?php 
        esc_attr_e( 'Add a comment...', 'mediatasker' );
        ?>"
										required></textarea>
									<button type="submit" class="mediat_thread-submit">
										<?php 
        esc_html_e( 'Send', 'mediatasker' );
        ?>
									</button>
								</form>
							</div>
						</div>
					</aside>
				</div>
			</dialog>

			<!-- Custom Generic Dialog (Alert/Confirm Replacements) -->
			<dialog class="mediat_dialog mediat_custom-dialog">
				<h3 class="mediat_dialog-title mediat_custom-dialog-title"></h3>
				<div class="mediat_custom-dialog-message"></div>
				<footer class="mediat_dialog-actions mediat_custom-dialog-actions">
					<button type="button" class="mediat_btn-neutral mediat_custom-dialog-cancel" style="display:none;"></button>
					<button type="button" class="mediat_btn-primary mediat_custom-dialog-confirm"></button>
				</footer>
			</dialog>

		</section>
		<?php 
        $output = ob_get_clean();
        return preg_replace( '/\\s+/', ' ', str_replace( array("\r", "\n", "\t"), ' ', (string) $output ) );
    }

    /**
     * Render the login prompt for non-logged-in users.
     *
     * @return string HTML output for the login prompt.
     */
    private static function render_login_prompt() {
        ob_start();
        ?>
		<div class="mediat_workspace mediat_login-prompt-wrapper">
			<div class="mediat_login-prompt-card">
				<div class="mediat_login-prompt-icon">
					<span class="dashicons dashicons-lock"></span>
				</div>
				<h3 class="mediat_login-prompt-title"><?php 
        esc_html_e( 'Access Restricted', 'mediatasker' );
        ?></h3>
				<p class="mediat_login-prompt-text">
					<?php 
        esc_html_e( 'You need to be logged in to view this content.', 'mediatasker' );
        ?>
				</p>
				<a href="<?php 
        echo esc_url( wp_login_url( get_permalink() ) );
        ?>"
					class="mediat_btn mediat_btn-primary mediat_login-prompt-btn">
					<?php 
        esc_html_e( 'Log in', 'mediatasker' );
        ?>
				</a>
			</div>
		</div>
		<?php 
        $output = ob_get_clean();
        return preg_replace( '/\\s+/', ' ', str_replace( array("\r", "\n", "\t"), ' ', (string) $output ) );
    }

    /**
     * Build the gallery HTML for task cards.
     *
     * Accepts optional filter parameters used by both the initial render
     * and the AJAX filter endpoint.
     *
     * @param string $status Optional. Custom post status to filter by.
     * @param int    $tag_id Optional. Term ID of mediat_tag taxonomy.
     * @param string $view   Optional. 'original' or 'edited'.
     * @return string Escaped HTML fragment.
     */
    public static function get_gallery_html( $status = '', $tag_id = 0, $view = 'original' ) {
        $args = array(
            'post_type'      => 'mediat_task',
            'posts_per_page' => -1,
            'orderby'        => array(
                'date' => 'DESC',
                'ID'   => 'DESC',
            ),
        );
        // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query
        $args['tax_query'] = array(array(
            'taxonomy' => 'mediat_view_source',
            'field'    => 'slug',
            'terms'    => $view,
        ));
        // Filter by status.
        if ( !empty( $status ) ) {
            $args['post_status'] = sanitize_key( $status );
        } else {
            // Show all custom statuses.
            $args['post_status'] = array_keys( Mediat_Post_Types::get_task_statuses() );
        }
        // Filter by tag.
        $tag_id = absint( $tag_id );
        if ( $tag_id > 0 ) {
            // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query
            $args['tax_query'][] = array(
                'taxonomy' => 'mediat_tag',
                'field'    => 'term_id',
                'terms'    => $tag_id,
            );
        }
        $query = new WP_Query($args);
        if ( !$query->have_posts() ) {
            return '<p class="mediat_empty-notice">' . esc_html__( 'No tasks found.', 'mediatasker' ) . '</p>';
        }
        $html = '';
        $current_date = '';
        $first_group = true;
        while ( $query->have_posts() ) {
            $query->the_post();
            $post_id = get_the_ID();
            $title = get_the_title();
            $attachment_id = get_post_thumbnail_id( $post_id );
            $filename = get_the_title( $post_id );
            // Display the exact original filename from task title
            $post_date = get_the_time( 'F j, Y' );
            $status_key = get_post_status( $post_id );
            // Normalize generic post status if it somehow sneaks in
            if ( in_array( $status_key, array('publish', 'draft', 'pending') ) ) {
                $status_key = 'mediat_pending';
            }
            $status_class = str_replace( 'mediat_', '', $status_key );
            // Use simplified classes like 'pending' instead of 'mediat_pending'
            $status_class = str_replace( '_', '-', $status_class );
            // e.g. in_progress -> in-progress
            if ( $post_date !== $current_date ) {
                if ( !$first_group ) {
                    $html .= '	</div>';
                    // Close previous mediat_date-grouping
                    $html .= '</div>';
                    // Close previous mediat_date-section
                }
                $first_group = false;
                $current_date = $post_date;
                // Date Header Grouping
                $html .= '<div class="mediat_date-section">';
                $html .= '	<header class="mediat_date-header">';
                $html .= '		<div class="mediat_date-info">';
                $html .= '			<div class="mediat_date-label">';
                $html .= '				<span class="dashicons dashicons-calendar-alt"></span>';
                $html .= '				' . esc_html( $post_date );
                $html .= '			</div>';
                $html .= '		</div>';
                $html .= '	</header>';
                $html .= '	<div class="mediat_date-grouping">';
            }
            // Individual Asset Card
            $html .= '		<article class="mediat_asset-card status-' . esc_attr( $status_class ) . '" data-post-id="' . esc_attr( $post_id ) . '">';
            $html .= '			<div class="mediat_selector" role="checkbox" aria-checked="false" tabindex="0"></div>';
            $html .= '			<figure class="mediat_asset-visual">';
            if ( has_post_thumbnail( $post_id ) ) {
                // Use original image URL if available for full resolution
                $full_img_url = wp_get_original_image_url( $attachment_id );
                if ( !$full_img_url ) {
                    $full_img_url = get_the_post_thumbnail_url( $post_id, 'full' );
                }
                $html .= get_the_post_thumbnail( $post_id, 'medium', array(
                    'alt'           => esc_attr( $title ),
                    'class'         => 'mediat_preview-img',
                    'data-full-img' => esc_url( $full_img_url ),
                ) );
            } else {
                $html .= '				<div class="mediat_no-visual"><span class="dashicons dashicons-format-image"></span></div>';
            }
            $html .= '				<button type="button" class="mediat_info-trigger" title="' . esc_attr__( 'View Image Details', 'mediatasker' ) . '">';
            $html .= '					<span class="dashicons dashicons-info-outline"></span>';
            $html .= '				</button>';
            $html .= '			</figure>';
            $html .= '			<div class="mediat_asset-details">';
            $html .= '				<h3 class="mediat_asset-name" title="' . esc_attr( $title ) . '">' . esc_html( $filename ) . '</h3>';
            $html .= '			</div>';
            $html .= '			<div class="a-bottom"><section class="mediat_inline-discussion">';
            $html .= '				<div class="mediat_thread-list">';
            // Pre-load comments for the task
            $comments = get_comments( array(
                'post_id' => $post_id,
                'status'  => 'approve',
                'order'   => 'ASC',
            ) );
            if ( empty( $comments ) ) {
                // Do not output any "No comments" text
            } else {
                foreach ( $comments as $comment ) {
                    // Assume Mediat_Ajax is loaded and available
                    if ( class_exists( 'Mediat_Ajax' ) && is_callable( array('Mediat_Ajax', 'get_comment_html') ) ) {
                        $html .= Mediat_Ajax::get_comment_html( $comment );
                    }
                }
            }
            $html .= '				</div>';
            $html .= '				<form class="mediat_inline-thread-form" data-post-id="' . esc_attr( $post_id ) . '">';
            $html .= '					<textarea name="comment" placeholder="' . esc_attr__( 'Write a comment', 'mediatasker' ) . '" required></textarea>';
            $html .= '					<button type="submit" title="' . esc_attr__( 'Post Comment', 'mediatasker' ) . '"></button>';
            $html .= '				</form>';
            $html .= '			</section></div>';
            $html .= '		</article>';
        }
        if ( !$first_group ) {
            $html .= '	</div>';
            // Close final mediat_date-grouping
            $html .= '</div>';
            // Close final mediat_date-section
        }
        wp_reset_postdata();
        return preg_replace( '/\\s+/', ' ', str_replace( array("\r", "\n", "\t"), ' ', $html ) );
    }

}
