<?php
/**
 * Main plugin class for GistMag Alt Text Generator
 *
 * @package GistMag_ATG
 */

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

class GistMag_ATG {
    private $api;
    private $admin;

    public function __construct() {
        $this->api = new GistMag_ATG_API();
        $this->admin = new GistMag_ATG_Admin();
    }

    public function run() {
        // Enqueue scripts and styles - use priority to ensure it loads
        add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'), 999);
        
        // Hook into media upload
        add_action('add_attachment', array($this, 'auto_generate_alt_text'), 10, 1);
        
        // Add AJAX handlers
        add_action('wp_ajax_gistmag_atg_generate', array($this, 'ajax_generate_alt_text'));
        add_action('wp_ajax_gistmag_atg_bulk_generate', array($this, 'ajax_bulk_generate'));
        add_action('wp_ajax_gistmag_atg_verify_key', array($this, 'ajax_verify_key'));
        
        // Add admin notices for bulk actions
        add_action('admin_notices', array($this, 'bulk_action_admin_notices'));
        
        // Add media library column
        add_filter('manage_media_columns', array($this, 'add_alt_text_column'));
        add_action('manage_media_custom_column', array($this, 'render_alt_text_column'), 10, 2);
        
        // Add button to attachment edit form (via JavaScript)
        add_action('add_meta_boxes', array($this, 'add_alt_text_meta_box'));
        
        // Add bulk action for media library
        add_filter('bulk_actions-upload', array($this, 'add_bulk_action'));
        add_filter('handle_bulk_actions-upload', array($this, 'handle_bulk_action'), 10, 3);
        
        // Also add to media grid view
        add_filter('bulk_actions', array($this, 'add_bulk_action_grid'), 10, 1);
    }

    public function enqueue_scripts($hook) {
        // Load on all admin pages to ensure media modal works everywhere
        if (!is_admin()) {
            return;
        }

        $script_url = GISTMAG_ATG_PLUGIN_URL . 'assets/js/admin.js';
        $style_url = GISTMAG_ATG_PLUGIN_URL . 'assets/css/admin.css';
        
        // Always enqueue - don't check for specific hooks
        wp_enqueue_script(
            'gistmag-atg-admin',
            $script_url,
            array('jquery', 'media-views', 'media-models'),
            GISTMAG_ATG_VERSION . '-' . time(), // Add timestamp to force reload
            true
        );

        wp_enqueue_style(
            'gistmag-atg-admin',
            $style_url,
            array(),
            GISTMAG_ATG_VERSION . '-' . time()
        );

        wp_localize_script('gistmag-atg-admin', 'gistmag_atg', array(
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('gistmag_atg_nonce'),
            'apiBaseUrl' => GISTMAG_ATG_API_BASE_URL,
            'debug' => defined('WP_DEBUG') && WP_DEBUG,
            'pluginUrl' => GISTMAG_ATG_PLUGIN_URL,
            'scriptUrl' => $script_url,
        ));
        
    }

    public function enqueue_media_scripts() {
        wp_enqueue_script('gistmag-atg-admin');
        wp_enqueue_style('gistmag-atg-admin');
    }


    public function auto_generate_alt_text($attachment_id) {
        if (!get_option('gistmag_atg_auto_generate', true)) {
            return;
        }

        $api_key = get_option('gistmag_atg_api_key');
        if (empty($api_key)) {
            return;
        }

        $image_url = wp_get_attachment_image_url($attachment_id, 'full');
        if (!$image_url) {
            return;
        }

        // Skip if alt text already exists
        $existing_alt = get_post_meta($attachment_id, '_wp_attachment_image_alt', true);
        if (!empty($existing_alt)) {
            return;
        }

        $mode = get_option('gistmag_atg_default_mode', 'short');
        $alt_text = $this->api->generate_alt_text($image_url, $mode, $api_key);

        if ($alt_text) {
            update_post_meta($attachment_id, '_wp_attachment_image_alt', $alt_text);
        }
    }

    public function ajax_generate_alt_text() {
        check_ajax_referer('gistmag_atg_nonce', 'nonce');

        if (!current_user_can('upload_files')) {
            wp_send_json_error(array('message' => 'Insufficient permissions'));
            return;
        }

        $attachment_id = isset($_POST['attachment_id']) ? intval($_POST['attachment_id']) : 0;
        $image_url = isset($_POST['image_url']) ? esc_url_raw(wp_unslash($_POST['image_url'])) : '';
        $mode = isset($_POST['mode']) ? sanitize_text_field(wp_unslash($_POST['mode'])) : 'short';

        if (!$attachment_id && !$image_url) {
            wp_send_json_error(array('message' => 'Attachment ID or image URL required'));
            return;
        }

        if (!$image_url) {
            $image_url = wp_get_attachment_image_url($attachment_id, 'full');
        }

        $api_key = get_option('gistmag_atg_api_key');
        if (empty($api_key)) {
            wp_send_json_error(array('message' => 'API key not configured'));
            return;
        }

        $alt_text = $this->api->generate_alt_text($image_url, $mode, $api_key);

        if ($alt_text && $attachment_id) {
            update_post_meta($attachment_id, '_wp_attachment_image_alt', $alt_text);
        }

        if ($alt_text) {
            wp_send_json_success(array('alt_text' => $alt_text));
        } else {
            wp_send_json_error(array('message' => 'Failed to generate alt text'));
        }
    }

    public function ajax_verify_key() {
        check_ajax_referer('gistmag_atg_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'Insufficient permissions'));
            return;
        }

        $api_key = isset($_POST['api_key']) ? sanitize_text_field(wp_unslash($_POST['api_key'])) : '';
        
        if (empty($api_key)) {
            wp_send_json_error(array('message' => 'API key is required'));
            return;
        }

        $is_valid = $this->api->verify_api_key($api_key);

        if ($is_valid) {
            wp_send_json_success(array('message' => 'API key is valid'));
        } else {
            wp_send_json_error(array('message' => 'API key is invalid'));
        }
    }

    public function ajax_bulk_generate() {
        check_ajax_referer('gistmag_atg_nonce', 'nonce');

        if (!current_user_can('upload_files')) {
            wp_send_json_error(array('message' => 'Insufficient permissions'));
            return;
        }

        $attachment_ids = isset( $_POST['attachment_ids'] )
            ? array_map( 'absint', (array) wp_unslash( $_POST['attachment_ids'] ) ) // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
            : array();
        $mode = isset($_POST['mode']) ? sanitize_text_field(wp_unslash($_POST['mode'])) : 'short';

        if (empty($attachment_ids)) {
            wp_send_json_error(array('message' => 'No attachments selected'));
            return;
        }

        $api_key = get_option('gistmag_atg_api_key');
        if (empty($api_key)) {
            wp_send_json_error(array('message' => 'API key not configured'));
            return;
        }

        $results = array();
        foreach ($attachment_ids as $attachment_id) {
            $image_url = wp_get_attachment_image_url($attachment_id, 'full');
            if (!$image_url) {
                continue;
            }

            $existing_alt = get_post_meta($attachment_id, '_wp_attachment_image_alt', true);
            if (!empty($existing_alt)) {
                continue;
            }

            $alt_text = $this->api->generate_alt_text($image_url, $mode, $api_key);
            if ($alt_text) {
                update_post_meta($attachment_id, '_wp_attachment_image_alt', $alt_text);
                $results[] = array(
                    'id' => $attachment_id,
                    'success' => true,
                    'alt_text' => $alt_text,
                );
            } else {
                $results[] = array(
                    'id' => $attachment_id,
                    'success' => false,
                );
            }
            
            // Small delay to avoid rate limiting
            usleep(500000); // 0.5 seconds
        }

        wp_send_json_success(array('results' => $results));
    }

    public function add_alt_text_column($columns) {
        $columns['gistmag_alt_text'] = __('Alt Text', 'gistmag-alt-text-generator');
        return $columns;
    }

    public function render_alt_text_column($column_name, $post_id) {
        if ($column_name !== 'gistmag_alt_text') {
            return;
        }

        $alt_text = get_post_meta($post_id, '_wp_attachment_image_alt', true);
        if ($alt_text) {
            echo esc_html($alt_text);
        } else {
            echo '<span class="gistmag-atg-generate" data-attachment-id="' . esc_attr($post_id) . '">';
            echo '<button class="button button-small">Generate</button>';
            echo '</span>';
        }
    }

    public function add_alt_text_meta_box() {
        // Button will be added via JavaScript to handle dynamic media modal
    }

    public function add_bulk_action($actions) {
        // Add our bulk action - WordPress will show it in the dropdown
        $actions['gistmag_atg_generate_alt'] = __('Generate Alt Text (GistMag)', 'gistmag-alt-text-generator');
        return $actions;
    }

    public function add_bulk_action_grid($actions) {
        // For grid view
        if (get_current_screen() && get_current_screen()->id === 'upload') {
            $actions['gistmag_atg_generate_alt'] = __('Generate Alt Text (GistMag)', 'gistmag-alt-text-generator');
        }
        return $actions;
    }

    public function handle_bulk_action($redirect_to, $action, $post_ids) {
        if ($action !== 'gistmag_atg_generate_alt') {
            return $redirect_to;
        }

        // Check nonce.
        $nonce_raw = isset( $_REQUEST['_wpnonce'] ) ? wp_unslash( $_REQUEST['_wpnonce'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
        $nonce     = sanitize_text_field( $nonce_raw );
        if ( ! $nonce || ! wp_verify_nonce( $nonce, 'bulk-media' ) ) {
            return $redirect_to;
        }

        $api_key = get_option('gistmag_atg_api_key');
        if (empty($api_key)) {
            $redirect_to = add_query_arg('gistmag_atg_error', 'no_api_key', $redirect_to);
            return $redirect_to;
        }

        $mode = get_option('gistmag_atg_default_mode', 'short');
        $processed = 0;
        $updated = 0;

        foreach ($post_ids as $post_id) {
            // Check if it's an image
            $post = get_post($post_id);
            if (!$post || strpos($post->post_mime_type, 'image/') !== 0) {
                continue;
            }

            // Check if alt text already exists
            $existing_alt = get_post_meta($post_id, '_wp_attachment_image_alt', true);
            if (!empty($existing_alt)) {
                continue;
            }

            $image_url = wp_get_attachment_image_url($post_id, 'full');
            if (!$image_url) {
                continue;
            }

            $alt_text = $this->api->generate_alt_text($image_url, $mode, $api_key);
            if ($alt_text) {
                update_post_meta($post_id, '_wp_attachment_image_alt', $alt_text);
                $updated++;
            }

            $processed++;
            
            // Small delay to avoid rate limiting
            usleep(500000); // 0.5 seconds
        }

        $redirect_to = remove_query_arg(
            array( 'gistmag_atg_error', 'gistmag_atg_processed', 'gistmag_atg_updated', 'gistmag_atg_nonce' ),
            $redirect_to
        );
        $redirect_to = add_query_arg(
            array(
                'gistmag_atg_processed' => $processed,
                'gistmag_atg_updated'   => $updated,
                'gistmag_atg_nonce'     => wp_create_nonce( 'gistmag_atg_bulk_notice' ),
            ),
            $redirect_to
        );

        return $redirect_to;
    }

    public function bulk_action_admin_notices() {
        // Verify notice nonce before using query parameters.
        if (
            ! isset( $_REQUEST['gistmag_atg_nonce'] )
            || ! wp_verify_nonce(
                sanitize_text_field( wp_unslash( $_REQUEST['gistmag_atg_nonce'] ) ), // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
                'gistmag_atg_bulk_notice'
            )
        ) {
            return;
        }

        if ( isset( $_REQUEST['gistmag_atg_error'] ) && 'no_api_key' === sanitize_text_field( wp_unslash( $_REQUEST['gistmag_atg_error'] ) ) ) {
            echo '<div class="notice notice-error"><p>' . esc_html( __( 'GistMag ATG: API key not configured. Please set your API key in settings.', 'gistmag-alt-text-generator' ) ) . '</p></div>';
        }

        if ( isset( $_REQUEST['gistmag_atg_processed'] ) ) {
            $processed = isset( $_REQUEST['gistmag_atg_processed'] ) ? absint( wp_unslash( $_REQUEST['gistmag_atg_processed'] ) ) : 0;
            $updated   = isset( $_REQUEST['gistmag_atg_updated'] ) ? absint( wp_unslash( $_REQUEST['gistmag_atg_updated'] ) ) : 0;
            $message   = sprintf(
                /* translators: 1: number of images processed, 2: number of images updated with alt text. */
                __( 'GistMag ATG: Processed %1$d image(s), updated %2$d with alt text.', 'gistmag-alt-text-generator' ),
                $processed,
                $updated
            );
            echo '<div class="notice notice-success is-dismissible"><p>' . esc_html( $message ) . '</p></div>';
        }
    }
}
