<?php
/**
 * Plugin Name: A11ysaurio PDF Checker
 * Plugin URI: https://josehumanes.com/
 * Description: El primer validador automático de accesibilidad para documentos PDF (WCAG y PDF/UA) directamente integrado en tu biblioteca de medios. Analiza, detecta y revisa problemas de accesibilidad sin salir de WordPress.
 * Version: 1.0.0
 * Author: Jose Humanes
 * Text Domain: a11ysaurio-pdf-checker
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 */

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

class A11ysaurio_PDF_Checker {

    public function __construct() {
        add_action( 'admin_menu', array( $this, 'add_admin_menu' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ) );
        add_filter( 'media_row_actions', array( $this, 'add_media_row_action' ), 10, 2 );
        add_filter( 'attachment_fields_to_edit', array( $this, 'add_attachment_details_action' ), 10, 2 );
        add_action( 'attachment_submitbox_misc_actions', array( $this, 'add_submitbox_action' ) );
        add_action( 'wp_ajax_a11ysaurio_save_results', array( $this, 'ajax_save_results' ) );
        add_action( 'admin_post_a11ysaurio_delete_analysis', array( $this, 'handle_delete_analysis' ) );
        add_action( 'admin_head', array( $this, 'custom_menu_icon_style' ) );
        add_action( 'admin_post_a11ysaurio_bulk_delete_analysis', array( $this, 'handle_bulk_delete_analysis' ) );
        add_filter( 'bulk_actions-upload', array( $this, 'register_bulk_action' ) );
        add_filter( 'handle_bulk_actions-upload', array( $this, 'handle_bulk_action' ), 10, 3 );
        add_action( 'wp_dashboard_setup', array( $this, 'register_dashboard_widget' ) );
        add_filter( 'script_loader_tag', array( $this, 'add_module_to_script' ), 10, 3 );
    }

    public function add_module_to_script( $tag, $handle, $src ) {
        if ( 'a11ysaurio-admin-js' === $handle ) {
            return '<script type="module" src="' . esc_url( $src ) . '"></script>' . "\n";
        }
        return $tag;
    }

    public function custom_menu_icon_style() {
        echo '<style>
            /* Contenedor del icono */
            #toplevel_page_a11ysaurio-pdf-checker .wp-menu-image {
                position: relative !important;
            }
            /* Estado normal (y activo, sin cambios especiales de tamaño/posición) */
            #toplevel_page_a11ysaurio-pdf-checker .wp-menu-image img {
                width: 20px !important;
                height: 20px !important;
                max-width: none !important;
                max-height: none !important;
                padding: 0 !important;
                margin: 0 !important;
                position: absolute !important;
                top: 50% !important;
                left: 50% !important;
                transform: translate(-50%, -50%) !important;
                filter: grayscale(100%) brightness(1.3) contrast(1.2) !important;
                opacity: 0.7 !important;
                transition: opacity 0.2s ease;
            }
            #toplevel_page_a11ysaurio-pdf-checker:hover .wp-menu-image img,
            #toplevel_page_a11ysaurio-pdf-checker.current .wp-menu-image img,
            #toplevel_page_a11ysaurio-pdf-checker.wp-has-current-submenu .wp-menu-image img {
                opacity: 1 !important;
            }
        </style>';
    }

    public function add_admin_menu() {
        add_menu_page(
            'A11ysaurio PDF Checker',
            'A11ysaurio',
            'upload_files',
            'a11ysaurio-pdf-checker',
            array( $this, 'render_admin_page' ),
            plugin_dir_url( __FILE__ ) . 'assets/images/logo_saurio_V2.png',
            30
        );
    }

    public function handle_delete_analysis() {
        if ( ! isset( $_GET['attachment_id'] ) ) {
            return;
        }
        $attachment_id = intval( $_GET['attachment_id'] );
        check_admin_referer( 'a11ysaurio_delete_' . $attachment_id );

        if ( ! current_user_can( 'upload_files' ) ) {
            wp_die( 'No tienes permisos suficientes.' );
        }

        delete_post_meta( $attachment_id, '_a11ysaurio_analysis' );

        wp_safe_redirect( admin_url( 'admin.php?page=a11ysaurio-pdf-checker' ) );
        exit;
    }

    public function handle_bulk_delete_analysis() {
        if ( ! current_user_can( 'upload_files' ) ) {
            wp_die( 'Permisos insuficientes' );
        }
        check_admin_referer( 'a11ysaurio_bulk_delete_nonce' );
        
        $action = isset( $_POST['action2'] ) ? $_POST['action2'] : '';
        if ( $action === 'delete' && !empty( $_POST['post_ids'] ) && is_array( $_POST['post_ids'] ) ) {
            foreach ( $_POST['post_ids'] as $post_id ) {
                $post_id = intval( $post_id );
                if ( $post_id ) {
                    delete_post_meta( $post_id, '_a11ysaurio_analysis' );
                }
            }
        }
        wp_safe_redirect( admin_url( 'admin.php?page=a11ysaurio-pdf-checker' ) );
        exit;
    }

    public function register_bulk_action( $bulk_actions ) {
        $bulk_actions['a11ysaurio_analyze'] = __( 'Analizar con A11ysaurio', 'a11ysaurio-pdf-checker' );
        return $bulk_actions;
    }

    public function handle_bulk_action( $redirect_to, $doaction, $post_ids ) {
        if ( $doaction !== 'a11ysaurio_analyze' ) {
            return $redirect_to;
        }
        $pdf_ids = array();
        foreach ( $post_ids as $post_id ) {
            if ( get_post_mime_type( $post_id ) === 'application/pdf' ) {
                $pdf_ids[] = $post_id;
            }
        }
        if ( empty( $pdf_ids ) ) {
            return $redirect_to;
        }
        $redirect_to = admin_url( 'admin.php?page=a11ysaurio-pdf-checker&bulk_analyze=' . implode( ',', $pdf_ids ) );
        return $redirect_to;
    }

    public function register_dashboard_widget() {
        wp_add_dashboard_widget(
            'a11ysaurio_dashboard_widget',
            'Estado de Accesibilidad PDF (A11ysaurio)',
            array( $this, 'render_dashboard_widget' )
        );
    }

    public function render_dashboard_widget() {
        $args = array(
            'post_type' => 'attachment',
            'post_mime_type' => 'application/pdf',
            'post_status' => 'inherit',
            'meta_key' => '_a11ysaurio_analysis',
            'posts_per_page' => -1
        );
        $query = new WP_Query( $args );
        
        $total_pdfs = $query->found_posts;
        $total_ok = 0;
        $total_warn = 0;
        $total_err = 0;
        
        if ( $query->have_posts() ) {
            while ( $query->have_posts() ) {
                $query->the_post();
                $meta = get_post_meta( get_the_ID(), '_a11ysaurio_analysis', true );
                $data = json_decode( $meta, true );
                
                if ( isset( $data['validation_ok'] ) ) $total_ok += intval( $data['validation_ok'] );
                if ( isset( $data['validation_warn'] ) ) $total_warn += intval( $data['validation_warn'] );
                if ( isset( $data['validation_error'] ) ) $total_err += intval( $data['validation_error'] );
            }
            wp_reset_postdata();
        }
        
        echo '<div style="display: flex; gap: 15px; margin-bottom: 15px;">';
        echo '<div style="flex: 1; text-align: center; background: #f0f0f1; padding: 15px; border-radius: 4px;">';
        echo '<h4 style="margin: 0 0 5px 0;">PDFs Analizados</h4>';
        echo '<span style="font-size: 2em; font-weight: bold; color: #2271b1;">' . esc_html( $total_pdfs ) . '</span>';
        echo '</div>';
        echo '<div style="flex: 1; text-align: center; background: #f0f0f1; padding: 15px; border-radius: 4px;">';
        echo '<h4 style="margin: 0 0 5px 0;">Errores Encontrados</h4>';
        echo '<span style="font-size: 2em; font-weight: bold; color: #d63638;">' . esc_html( $total_err ) . '</span>';
        echo '</div>';
        echo '</div>';
        
        echo '<p><strong>Aprobados totales:</strong> ' . esc_html( $total_ok ) . '</p>';
        echo '<p><strong>Avisos totales:</strong> ' . esc_html( $total_warn ) . '</p>';
        
        echo '<hr style="margin: 15px 0;">';
        echo '<a href="' . esc_url( admin_url( 'admin.php?page=a11ysaurio-pdf-checker' ) ) . '" class="button button-primary">Ver Historial Completo</a>';
    }

    public function add_media_row_action( $actions, $post ) {
        if ( 'application/pdf' === $post->post_mime_type ) {
            $url = admin_url( 'admin.php?page=a11ysaurio-pdf-checker&attachment_id=' . $post->ID );
            $has_analysis = get_post_meta( $post->ID, '_a11ysaurio_analysis', true );
            $text = $has_analysis ? __( 'Ver Análisis (A11ysaurio)', 'a11ysaurio-pdf-checker' ) : __( 'Analizar PDF (A11ysaurio)', 'a11ysaurio-pdf-checker' );
            $actions['a11ysaurio_analyze'] = sprintf(
                '<a href="%s" aria-label="%s" style="color: #2271b1;">%s</a>',
                esc_url( $url ),
                esc_attr( $text ),
                esc_html( $text )
            );
        }
        return $actions;
    }

    public function add_attachment_details_action( $form_fields, $post ) {
        if ( 'application/pdf' === $post->post_mime_type ) {
            $url = admin_url( 'admin.php?page=a11ysaurio-pdf-checker&attachment_id=' . $post->ID );
            $has_analysis = get_post_meta( $post->ID, '_a11ysaurio_analysis', true );
            $text = $has_analysis ? __( 'Ver Análisis', 'a11ysaurio-pdf-checker' ) : __( 'Analizar PDF con A11ysaurio', 'a11ysaurio-pdf-checker' );
            
            $button_html = sprintf(
                '<a href="%s" class="button button-primary">%s</a>',
                esc_url( $url ),
                esc_html( $text )
            );

            $form_fields['a11ysaurio_analyze'] = array(
                'label' => 'A11ysaurio',
                'input' => 'html',
                'html'  => $button_html,
                'show_in_edit' => true,
                'show_in_modal' => true,
            );
        }
        return $form_fields;
    }

    public function add_submitbox_action() {
        global $post;
        if ( $post && 'application/pdf' === $post->post_mime_type ) {
            $url = admin_url( 'admin.php?page=a11ysaurio-pdf-checker&attachment_id=' . $post->ID );
            $has_analysis = get_post_meta( $post->ID, '_a11ysaurio_analysis', true );
            $text = $has_analysis ? __( 'Ver Análisis', 'a11ysaurio-pdf-checker' ) : __( 'Analizar con A11ysaurio', 'a11ysaurio-pdf-checker' );
            printf(
                '<div class="misc-pub-section misc-pub-a11ysaurio">
                    <a href="%s" class="button button-primary" style="width: 100%%; text-align: center;">%s</a>
                </div>',
                esc_url( $url ),
                esc_html( $text )
            );
        }
    }

    public function enqueue_admin_scripts( $hook_suffix ) {
        if ( 'toplevel_page_a11ysaurio-pdf-checker' !== $hook_suffix ) {
            return;
        }

        $attachment_url = '';
        $attachment_id = isset( $_GET['attachment_id'] ) ? intval( $_GET['attachment_id'] ) : 0;
        
        $bulk_ids = array();
        if ( isset( $_GET['bulk_analyze'] ) ) {
            $bulk_ids = array_map( 'intval', explode( ',', $_GET['bulk_analyze'] ) );
        }

        // Only enqueue the heavy JS/CSS if we are on the analysis view
        if ( ! $attachment_id && empty( $bulk_ids ) ) {
            return;
        }

        if ( $attachment_id ) {
            $attachment_url = wp_get_attachment_url( $attachment_id );
        }

        $plugin_url = plugin_dir_url( __FILE__ );

        wp_enqueue_style( 'a11ysaurio-admin-css', $plugin_url . 'assets/css/a11ysaurio-admin.css', array(), time() );
        wp_enqueue_style( 'a11ysaurio-udl-css', $plugin_url . 'assets/css/udl_styles.css', array(), time() );

        wp_enqueue_script( 'pdf-lib', $plugin_url . 'assets/vendor/pdf-lib.min.js', array(), '1.17.1', false );

        $bulk_urls = array();
        foreach ( $bulk_ids as $id ) {
            $bulk_urls[$id] = wp_get_attachment_url( $id );
        }

        wp_enqueue_script( 'a11ysaurio-admin-js', $plugin_url . 'assets/js/a11ysaurio-admin.js', array(), '1.0.0', true );
        
        wp_localize_script( 'a11ysaurio-admin-js', 'a11ysaurioData', array(
            'ajaxUrl'       => admin_url( 'admin-ajax.php' ),
            'nonce'         => wp_create_nonce( 'a11ysaurio_nonce' ),
            'attachmentId'  => $attachment_id,
            'attachmentUrl' => $attachment_url,
            'bulkIds'       => $bulk_ids,
            'bulkUrls'      => $bulk_urls,
            'pluginUrl'     => $plugin_url,
            'siteLang'      => get_locale(),
            'i18n'          => $this->get_i18n_strings()
        ) );
    }

    private function get_i18n_strings() {
        $locales_file = plugin_dir_path( __FILE__ ) . '_locales/es/messages.json';
        if ( file_exists( $locales_file ) ) {
             $json = file_get_contents( $locales_file );
             $data = json_decode( $json, true );
             $strings = array();
             if ( $data ) {
                 foreach ( $data as $key => $val ) {
                     $strings[$key] = $val['message'];
                 }
             }
             return $strings;
        }
        return array();
    }

    private function recursive_sanitize( $data ) {
        if ( is_array( $data ) ) {
            $sanitized = array();
            foreach ( $data as $key => $value ) {
                $sanitized_key = sanitize_key( $key );
                $sanitized[ $sanitized_key ] = $this->recursive_sanitize( $value );
            }
            return $sanitized;
        } elseif ( is_numeric( $data ) ) {
            return $data; // Ints/floats are safe
        } elseif ( is_bool( $data ) ) {
            return $data; // Bools are safe
        } else {
            return sanitize_text_field( $data ); // Sanitize string
        }
    }

    public function ajax_save_results() {
        check_ajax_referer( 'a11ysaurio_nonce', 'nonce' );
        if ( ! current_user_can( 'upload_files' ) ) {
            wp_send_json_error( 'Permisos insuficientes' );
        }

        $attachment_id = isset( $_POST['attachment_id'] ) ? intval( $_POST['attachment_id'] ) : 0;
        $results = isset( $_POST['results'] ) ? wp_unslash( $_POST['results'] ) : '';

        if ( $attachment_id && $results ) {
            $decoded = json_decode( $results, true );
            if ( json_last_error() === JSON_ERROR_NONE ) {
                $sanitized_decoded = $this->recursive_sanitize( $decoded );
                update_post_meta( $attachment_id, '_a11ysaurio_analysis', wp_json_encode( $sanitized_decoded ) );
                wp_send_json_success( 'Guardado correctamente' );
            } else {
                wp_send_json_error( 'JSON inválido' );
            }
        } else {
            wp_send_json_error( 'Faltan datos' );
        }
    }

    public function render_admin_page() {
        $attachment_id = isset( $_GET['attachment_id'] ) ? intval( $_GET['attachment_id'] ) : 0;
        $bulk_ids = isset( $_GET['bulk_analyze'] ) ? array_map( 'intval', explode( ',', $_GET['bulk_analyze'] ) ) : array();
        
        ?>
        <div class="wrap a11ysaurio-wrap" style="margin-top: 20px; background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
            <style>
                .a11ysaurio-wrap .wp-list-table th, 
                .a11ysaurio-wrap .wp-list-table td {
                    vertical-align: middle !important;
                    padding-top: 12px !important;
                    padding-bottom: 12px !important;
                }
                .a11ysaurio-wrap .check-column {
                    padding-top: 12px !important;
                    padding-bottom: 12px !important;
                }
                .a11ysaurio-wrap .check-column input[type="checkbox"] {
                    margin: 0 !important;
                    position: relative;
                    top: 1px;
                }
            </style>
            
            <div style="display: flex; align-items: center; margin-bottom: 20px; clear: both;">
                <img src="<?php echo esc_url( plugin_dir_url( __FILE__ ) . 'assets/images/logo_saurio_V2.png' ); ?>" alt="" style="width: 48px; height: 48px; margin-right: 15px;">
                <div>
                    <h1 style="margin: 0; padding: 0;">A11ysaurio PDF Checker</h1>
                    <p style="margin: 4px 0 0; color: #595750; font-size: 0.9375rem;">PDF Checker y Validador de Accesibilidad</p>
                </div>
            </div>
            
            <?php if ( ! $attachment_id && empty( $bulk_ids ) ) : ?>
                <div style="margin-bottom: 20px; clear: both; padding: 15px; font-size: 1.2rem; background: #e1ebfb; border-left: 4px solid #274b7a; border-radius: 4px;">
                    <p style="margin: 0; color: #252124;"><strong>Atención:</strong> Para analizar un documento nuevo, ve a la <a href="<?php echo esc_url( admin_url( 'upload.php' ) ); ?>">Biblioteca de Medios</a> y haz clic en "Analizar PDF (A11ysaurio)" debajo de un archivo PDF.</p>
                </div>

                <h2 style="font-size: 1.5em; margin-bottom: 15px; margin-top: 40px;">Histórico de Análisis</h2>
                
                <?php
                $args = array(
                    'post_type' => 'attachment',
                    'post_mime_type' => 'application/pdf',
                    'post_status' => 'inherit',
                    'meta_key' => '_a11ysaurio_analysis',
                    'posts_per_page' => -1
                );
                $query = new WP_Query( $args );
                
                if ( $query->have_posts() ) {
                    echo '<form method="post" action="' . esc_url( admin_url('admin-post.php') ) . '">';
                    echo '<input type="hidden" name="action" value="a11ysaurio_bulk_delete_analysis">';
                    wp_nonce_field( 'a11ysaurio_bulk_delete_nonce' );
                    
                    echo '<div class="tablenav top"><div class="alignleft actions bulkactions">';
                    echo '<select name="action2">';
                    echo '<option value="-1">Acciones en lote</option>';
                    echo '<option value="delete">Eliminar</option>';
                    echo '</select>';
                    echo '<input type="submit" class="button action" value="Aplicar" onclick="return confirm(\'¿Eliminar todos los análisis seleccionados?\');">';
                    echo '</div></div>';

                    echo '<table class="wp-list-table widefat fixed striped table-view-list">';
                    echo '<thead><tr><td id="cb" class="manage-column column-cb check-column"><input type="checkbox" id="cb-select-all-1" onclick="document.querySelectorAll(\'input[name=\\\'post_ids[]\\\']\').forEach(cb => cb.checked = this.checked);"></td><th>Documento</th><th>Fecha</th><th>Resultados</th><th>Acciones</th></tr></thead>';
                    echo '<tbody>';
                    while ( $query->have_posts() ) {
                        $query->the_post();
                        $post_id = get_the_ID();
                        $title = get_the_title();
                        $meta = get_post_meta( $post_id, '_a11ysaurio_analysis', true );
                        $data = json_decode( $meta, true );
                        
                        $date = isset( $data['timestamp'] ) ? wp_date( get_option('date_format') . ' ' . get_option('time_format'), intval($data['timestamp'] / 1000) ) : 'Desconocida';
                        $url = admin_url( 'admin.php?page=a11ysaurio-pdf-checker&attachment_id=' . $post_id );
                        
                        $ok = isset($data['validation_ok']) ? intval($data['validation_ok']) : 0;
                        $warn = isset($data['validation_warn']) ? intval($data['validation_warn']) : 0;
                        $err = isset($data['validation_error']) ? intval($data['validation_error']) : 0;
                        $manual = isset($data['validation_manual']) ? intval($data['validation_manual']) : 0;

                        $stats = sprintf(
                            '<span style="color: #007020; font-weight: bold;">Aprobados: %d</span><br><span style="color: #b08d00;">Avisos: %d</span><br><span style="color: #7b4c8f;">Manuales: %d</span><br><span style="color: #d63638; font-weight: bold;">Errores: %d</span>',
                            $ok, $warn, $manual, $err
                        );

                        $delete_url = wp_nonce_url( admin_url( 'admin-post.php?action=a11ysaurio_delete_analysis&attachment_id=' . $post_id ), 'a11ysaurio_delete_' . $post_id );

                        echo '<tr>';
                        echo '<th scope="row" class="check-column"><input type="checkbox" name="post_ids[]" value="' . esc_attr($post_id) . '"></th>';
                        echo '<td><strong><a href="' . esc_url($url) . '">' . esc_html($title) . '</a></strong></td>';
                        echo '<td>' . esc_html($date) . '</td>';
                        echo '<td>' . $stats . '</td>';
                        echo '<td>';
                        echo '<a href="' . esc_url($url) . '" class="button button-primary" style="margin-right:8px;">Ver Análisis</a>';
                        echo '<a href="' . esc_url($delete_url) . '" class="button" onclick="return confirm(\'¿Estás seguro de que quieres eliminar el historial de análisis de este documento?\');" style="color: #d63638; border-color: #d63638;">Eliminar</a>';
                        echo '</td>';
                        echo '</tr>';
                    }
                    echo '</tbody></table>';
                    echo '</form>';
                    wp_reset_postdata();
                } else {
                    echo '<p>No hay ningún PDF analizado en el historial.</p>';
                }
                ?>
                
            <?php else : ?>
                <?php
                // Preload URLs for bulk IDs
                $bulk_urls = array();
                foreach ( $bulk_ids as $id ) {
                    $bulk_urls[$id] = wp_get_attachment_url( $id );
                }
                
                // Data and scripts are now properly enqueued in enqueue_admin_scripts()
                ?>
                <?php include plugin_dir_path( __FILE__ ) . 'admin-template.php'; ?>
            <?php endif; ?>
        </div>
        <?php
    }
}

new A11ysaurio_PDF_Checker();



