<?php

 /**
 * =============================================================================
 * @package         Blue Raven (Free Version)
 * @Plugin URI      https://enterrahost.com/plugins/blue-raven
 * 
 * @Author          EnterraHost
 * @Author URI      https://enterrahost.com
 * @License         GPL-2.0-or-later
 *  
 * @Copyright       (c) 2025 EnterraHost
 * @Contents        Plugin Tools > Alt text
 *
 * =============================================================================
 * 
 * || INDEX:
 * ||   - BLUE RAVEN ADMIN TOOL ALT
 * || 
 * =============================================================================
 */

if ( ! defined( 'ABSPATH' ) ) exit; 

/*
============================================================
    BLUE RAVEN ADMIN TOOL ALT
============================================================
*/

class Blue_Raven_Admin_Tools_Alt {

    /**
     * Render the Alt Image tools page
     */
    public function render() {
        self::load_tools_alt_template(); 
    }
    
    /**
     * Load the Alt Image template and display data
     * 
     * @private
     */
    private static function load_tools_alt_template() {
    
    ## =========== Get Images =========== ##
     
        $images = self::get_images_with_empty_alt();
    
    ## =========== HTML =========== ##
        
        ?>
        <div class='flex-sb'>
            <h3><?php esc_html_e('Alt Image Tags', 'blue-raven'); ?></h3>
            <h4>
                <?php esc_html_e('Need Help', 'blue-raven'); ?>
                <a href="<?php echo esc_url('https://portal.enterrahost.com/knowledgebase/10/'); ?>" target="_blank" rel="noopener noreferrer" style="margin-left: 8px;" title="<?php esc_attr_e('Learn more', 'blue-raven'); ?>">
                    <i class="fas fa-question-circle"></i>
                </a>
            </h4>
        </div>
        <p class='enterra-highlight indent-one'>
            <?php esc_html_e('Alt image tags are short text descriptions that improve accessibility and help search engines understand your images. They make your site more inclusive and boost SEO by making your content easier to find. Blue Raven makes it simple to add and manage alt tags without touching code. Just enter your alt text, save, and improve your site\'s accessibility and search visibility instantly.', 'blue-raven'); ?>
        </p>            
        <div style="margin: 20px 0;">
            <section class="spacing-bottom-large" style='margin-top: 4rem;'>
                <?php
                if (empty($images)) {
                    ?>
                        <div class="br-badge success"><p><?php esc_html_e('No images found with empty alt text. Good job!', 'blue-raven'); ?></p></div>
                        </section>
                    <?php
                    return;
                }

                foreach ($images as $image) {
                    $thumbnail = wp_get_attachment_image_src($image->ID, array(400, 400));
                    $thumbnail_url = $thumbnail ? $thumbnail[0] : '';
                    $edit_url = admin_url("post.php?post={$image->ID}&action=edit");
                    ?>
                    <div class="image-alt-container">
                        <div class="image-alt-item border-bottom-white" style='margin-top:1.5rem;' data-image-id="<?php echo esc_attr($image->ID); ?>">
                            <div class="flex-left spacing-bottom">
                                <div style="flex: 0 0 150px;">
                                    <?php
                                        echo $thumbnail_url ? '<img src="' . esc_url($thumbnail_url) . '" alt="" style="max-width: 100%; height: auto;"/>' : '<div class="no-thumbnail">' . esc_html__('Thumbnail not available', 'blue-raven') . '</div>';
                                    ?>
                                </div>
                                <div style='margin-left: 2rem;'>
                                    <p><strong><?php esc_html_e('ID:', 'blue-raven'); ?> </strong><?php echo esc_html($image->ID); ?></p>
                                    <p><strong><?php esc_html_e('Title:', 'blue-raven'); ?> </strong><?php echo esc_html($image->post_title); ?></p>
                                    <p><a href="<?php echo esc_url($edit_url); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e('Edit Media', 'blue-raven'); ?></a></p>
                                </div>
                            </div>
                            <div class="flex-right" style="spacing-bottom">
                                <label class='text-center'><h4 class='no-margin-padding spacing-right-small text-center' style='width: 70px;'><?php esc_html_e('Alt Text', 'blue-raven'); ?></h4></label>
                                <input type='text' name='alt-text' placeholder='<?php esc_attr_e('Enter alternative text', 'blue-raven'); ?>' class='br-input' style='width: 85%'>
                                <button class="enterra-button save-alt-text-tools" style='margin-left: 1rem;'><?php esc_html_e('Save', 'blue-raven'); ?></button>
                            </div>
                            <div class="saving-status" style="text-align: right;"></div>
                        </div>
                    </div>
                <?php } ?>
            </section>
        </div>
        <?php
    }
    
    ## ===========  Get all images with empty alt text =========== ##
    
    private static function get_images_with_empty_alt() {
		global $wpdb;

		$posts_table    = $wpdb->posts;
		$postmeta_table = $wpdb->postmeta;
		
		$query = $wpdb->prepare(
			"SELECT p.ID, p.post_title
			FROM {$posts_table} p
			WHERE p.post_type = 'attachment'
			AND p.post_mime_type LIKE %s
			AND NOT EXISTS (
				SELECT 1 FROM {$postmeta_table} pm
				WHERE pm.post_id = p.ID
				AND pm.meta_key = '_wp_attachment_image_alt'
				AND pm.meta_value != ''
			)
			ORDER BY p.post_date DESC",
			'image/%'
		);
		
		// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Table name is safely constructed, query uses prepare()
		return $wpdb->get_results($query);
	}
}
