<?php
/**
 * Plugin Name: BW Admin Column
 * Plugin URI: https://bowdenworks.com
 * Description: Adds Excerpt and Featured Image columns to admin post lists. Click on thumbnail to change featured image.
 * Version: 1.0.0
 * Author: BowdenWorks
 * Author URI: https://bowdenworks.com
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: bw-admin-column
 */

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

class BW_Admin_Column {

    private static $instance = null;

    /**
     * Post types to add columns to
     */
    private $post_types = array( 'post', 'page' );

    public static function get_instance() {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        add_action( 'admin_init', array( $this, 'setup_columns' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_assets' ) );
        add_action( 'wp_ajax_bw_set_featured_image', array( $this, 'ajax_set_featured_image' ) );
        add_action( 'wp_ajax_bw_remove_featured_image', array( $this, 'ajax_remove_featured_image' ) );
    }

    /**
     * Setup columns for each post type
     */
    public function setup_columns() {
        // Allow filtering of post types
        $this->post_types = apply_filters( 'bw_admin_column_post_types', $this->post_types );

        foreach ( $this->post_types as $post_type ) {
            add_filter( "manage_{$post_type}_posts_columns", array( $this, 'add_columns' ) );
            add_action( "manage_{$post_type}_posts_custom_column", array( $this, 'render_columns' ), 10, 2 );
        }
    }

    /**
     * Add custom columns
     */
    public function add_columns( $columns ) {
        $new_columns = array();

        foreach ( $columns as $key => $value ) {
            // Add Featured Image after checkbox
            if ( $key === 'cb' ) {
                $new_columns[ $key ] = $value;
                $new_columns['bw_featured_image'] = __( 'Image', 'bw-admin-column' );
                continue;
            }

            $new_columns[ $key ] = $value;

            // Add Excerpt after title
            if ( $key === 'title' ) {
                $new_columns['bw_excerpt'] = __( 'Excerpt', 'bw-admin-column' );
            }
        }

        return $new_columns;
    }

    /**
     * Render custom columns
     */
    public function render_columns( $column, $post_id ) {
        switch ( $column ) {
            case 'bw_featured_image':
                $this->render_featured_image_column( $post_id );
                break;

            case 'bw_excerpt':
                $this->render_excerpt_column( $post_id );
                break;
        }
    }

    /**
     * Render Featured Image column
     */
    private function render_featured_image_column( $post_id ) {
        $thumbnail_id = get_post_thumbnail_id( $post_id );

        echo '<div class="bw-featured-image-cell" data-post-id="' . esc_attr( $post_id ) . '">';

        if ( $thumbnail_id ) {
            $thumb_url = wp_get_attachment_image_url( $thumbnail_id, 'thumbnail' );
            echo '<div class="bw-thumb-wrapper bw-has-image">';
            echo '<img src="' . esc_url( $thumb_url ) . '" alt="" class="bw-thumb-img" />';
            echo '<span class="bw-thumb-remove" title="' . esc_attr__( 'Remove', 'bw-admin-column' ) . '">&times;</span>';
            echo '</div>';
        } else {
            echo '<div class="bw-thumb-wrapper bw-no-image">';
            echo '<span class="dashicons dashicons-format-image"></span>';
            echo '</div>';
        }

        echo '</div>';
    }

    /**
     * Render Excerpt column
     */
    private function render_excerpt_column( $post_id ) {
        $post = get_post( $post_id );
        $excerpt = $post->post_excerpt;

        if ( empty( $excerpt ) ) {
            // Generate excerpt from content if not set
            $excerpt = wp_trim_words( wp_strip_all_tags( $post->post_content ), 20, '...' );
        }

        if ( ! empty( $excerpt ) ) {
            echo '<span class="bw-excerpt-text">' . esc_html( wp_trim_words( $excerpt, 15, '...' ) ) . '</span>';
        } else {
            echo '<span class="bw-excerpt-empty">—</span>';
        }
    }

    /**
     * Enqueue admin assets
     */
    public function enqueue_admin_assets( $hook ) {
        // Only on post list pages
        if ( 'edit.php' !== $hook ) {
            return;
        }

        // Enqueue media library
        wp_enqueue_media();

        // Inline styles
        wp_add_inline_style( 'wp-admin', $this->get_admin_css() );

        // Inline script
        wp_add_inline_script( 'jquery', $this->get_admin_js() );
    }

    /**
     * Get admin CSS
     */
    private function get_admin_css() {
        return '
            .column-bw_featured_image {
                width: 60px;
            }
            .column-bw_excerpt {
                width: 200px;
            }
            .bw-featured-image-cell {
                cursor: pointer;
            }
            .bw-thumb-wrapper {
                width: 50px;
                height: 50px;
                display: flex;
                align-items: center;
                justify-content: center;
                background: #f0f0f1;
                border-radius: 4px;
                position: relative;
                transition: all 0.2s ease;
            }
            .bw-thumb-wrapper:hover {
                background: #e0e0e0;
            }
            .bw-thumb-wrapper.bw-has-image {
                background: transparent;
            }
            .bw-thumb-img {
                width: 50px;
                height: 50px;
                object-fit: cover;
                border-radius: 4px;
                display: block;
            }
            .bw-thumb-wrapper .dashicons {
                font-size: 24px;
                width: 24px;
                height: 24px;
                color: #999;
            }
            .bw-thumb-wrapper:hover .dashicons {
                color: #0073aa;
            }
            .bw-thumb-remove {
                position: absolute;
                top: -6px;
                right: -6px;
                width: 18px;
                height: 18px;
                background: #dc3232;
                color: #fff;
                border-radius: 50%;
                font-size: 14px;
                line-height: 16px;
                text-align: center;
                cursor: pointer;
                opacity: 0;
                transition: opacity 0.2s ease;
            }
            .bw-thumb-wrapper:hover .bw-thumb-remove {
                opacity: 1;
            }
            .bw-thumb-remove:hover {
                background: #a00;
            }
            .bw-excerpt-text {
                color: #666;
                font-size: 12px;
                line-height: 1.4;
                display: block;
            }
            .bw-excerpt-empty {
                color: #999;
            }
            .bw-loading .bw-thumb-wrapper {
                opacity: 0.5;
            }
        ';
    }

    /**
     * Get admin JavaScript
     */
    private function get_admin_js() {
        return "
            jQuery(document).ready(function($) {
                var bwMediaFrame;

                // Click on featured image cell to open media library
                $(document).on('click', '.bw-featured-image-cell .bw-thumb-wrapper', function(e) {
                    // Don't open if clicking remove button
                    if ($(e.target).hasClass('bw-thumb-remove')) {
                        return;
                    }

                    var cell = $(this).closest('.bw-featured-image-cell');
                    var postId = cell.data('post-id');

                    // Create media frame
                    bwMediaFrame = wp.media({
                        title: '" . esc_js( __( 'Select Featured Image', 'bw-admin-column' ) ) . "',
                        button: {
                            text: '" . esc_js( __( 'Set Featured Image', 'bw-admin-column' ) ) . "'
                        },
                        multiple: false,
                        library: {
                            type: 'image'
                        }
                    });

                    // When image selected
                    bwMediaFrame.on('select', function() {
                        var attachment = bwMediaFrame.state().get('selection').first().toJSON();
                        bwSetFeaturedImage(postId, attachment.id, cell);
                    });

                    bwMediaFrame.open();
                });

                // Click remove button
                $(document).on('click', '.bw-thumb-remove', function(e) {
                    e.preventDefault();
                    e.stopPropagation();

                    var cell = $(this).closest('.bw-featured-image-cell');
                    var postId = cell.data('post-id');

                    if (confirm('" . esc_js( __( 'Remove featured image?', 'bw-admin-column' ) ) . "')) {
                        bwRemoveFeaturedImage(postId, cell);
                    }
                });

                // Set featured image via AJAX
                function bwSetFeaturedImage(postId, attachmentId, cell) {
                    cell.addClass('bw-loading');

                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'bw_set_featured_image',
                            post_id: postId,
                            attachment_id: attachmentId,
                            nonce: '" . wp_create_nonce( 'bw_featured_image' ) . "'
                        },
                        success: function(response) {
                            if (response.success) {
                                cell.find('.bw-thumb-wrapper').remove();
                                cell.append(response.data.html);
                            } else {
                                alert(response.data.message || 'Error setting featured image');
                            }
                        },
                        error: function() {
                            alert('Error setting featured image');
                        },
                        complete: function() {
                            cell.removeClass('bw-loading');
                        }
                    });
                }

                // Remove featured image via AJAX
                function bwRemoveFeaturedImage(postId, cell) {
                    cell.addClass('bw-loading');

                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'bw_remove_featured_image',
                            post_id: postId,
                            nonce: '" . wp_create_nonce( 'bw_featured_image' ) . "'
                        },
                        success: function(response) {
                            if (response.success) {
                                cell.find('.bw-thumb-wrapper').remove();
                                cell.append(response.data.html);
                            } else {
                                alert(response.data.message || 'Error removing featured image');
                            }
                        },
                        error: function() {
                            alert('Error removing featured image');
                        },
                        complete: function() {
                            cell.removeClass('bw-loading');
                        }
                    });
                }
            });
        ";
    }

    /**
     * AJAX: Set featured image
     */
    public function ajax_set_featured_image() {
        check_ajax_referer( 'bw_featured_image', 'nonce' );

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

        if ( ! $post_id || ! $attachment_id ) {
            wp_send_json_error( array( 'message' => __( 'Invalid request', 'bw-admin-column' ) ) );
        }

        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied', 'bw-admin-column' ) ) );
        }

        $result = set_post_thumbnail( $post_id, $attachment_id );

        if ( $result ) {
            $thumb_url = wp_get_attachment_image_url( $attachment_id, 'thumbnail' );
            $html = '<div class="bw-thumb-wrapper bw-has-image">';
            $html .= '<img src="' . esc_url( $thumb_url ) . '" alt="" class="bw-thumb-img" />';
            $html .= '<span class="bw-thumb-remove" title="' . esc_attr__( 'Remove', 'bw-admin-column' ) . '">&times;</span>';
            $html .= '</div>';

            wp_send_json_success( array( 'html' => $html ) );
        } else {
            wp_send_json_error( array( 'message' => __( 'Failed to set featured image', 'bw-admin-column' ) ) );
        }
    }

    /**
     * AJAX: Remove featured image
     */
    public function ajax_remove_featured_image() {
        check_ajax_referer( 'bw_featured_image', 'nonce' );

        $post_id = isset( $_POST['post_id'] ) ? intval( $_POST['post_id'] ) : 0;

        if ( ! $post_id ) {
            wp_send_json_error( array( 'message' => __( 'Invalid request', 'bw-admin-column' ) ) );
        }

        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied', 'bw-admin-column' ) ) );
        }

        $result = delete_post_thumbnail( $post_id );

        $html = '<div class="bw-thumb-wrapper bw-no-image">';
        $html .= '<span class="dashicons dashicons-format-image"></span>';
        $html .= '</div>';

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

// Initialize plugin
BW_Admin_Column::get_instance();
