<?php
/**
 * Admin column for expiry date display
 */

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

class BW_Expiry_Column {

    private static $instance = null;
    private $meta_key = '_bw_expiry_date';

    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, 'register_columns' ) );
        add_action( 'admin_head', array( $this, 'column_styles' ) );
    }

    /**
     * Register columns for enabled post types
     */
    public function register_columns() {
        $options = get_option( 'bw_expiry_settings', array() );
        $enabled_types = isset( $options['post_types'] ) ? $options['post_types'] : array( 'post' );

        foreach ( $enabled_types as $post_type ) {
            add_filter( "manage_{$post_type}_posts_columns", array( $this, 'add_column' ) );
            add_action( "manage_{$post_type}_posts_custom_column", array( $this, 'render_column' ), 10, 2 );
            add_filter( "manage_edit-{$post_type}_sortable_columns", array( $this, 'sortable_column' ) );
        }

        add_action( 'pre_get_posts', array( $this, 'sort_by_expiry' ) );
    }

    /**
     * Add expiry column to post list
     */
    public function add_column( $columns ) {
        $new_columns = array();

        foreach ( $columns as $key => $value ) {
            $new_columns[ $key ] = $value;
            // Insert after title or after date
            if ( 'title' === $key || 'date' === $key ) {
                if ( ! isset( $new_columns['bw_expiry'] ) ) {
                    $new_columns['bw_expiry'] = __( 'Expires', 'bw-expiry-post' );
                }
            }
        }

        // Fallback: add at end if not inserted
        if ( ! isset( $new_columns['bw_expiry'] ) ) {
            $new_columns['bw_expiry'] = __( 'Expires', 'bw-expiry-post' );
        }

        return $new_columns;
    }

    /**
     * Render the expiry column content
     */
    public function render_column( $column, $post_id ) {
        if ( 'bw_expiry' !== $column ) {
            return;
        }

        $expiry_date = get_post_meta( $post_id, $this->meta_key, true );
        $was_expired = get_post_meta( $post_id, '_bw_expired', true );

        // No date set
        if ( empty( $expiry_date ) ) {
            echo '<span class="bw-expiry-never" title="' . esc_attr__( 'Never expires', 'bw-expiry-post' ) . '">—</span>';
            return;
        }

        $expiry_timestamp = strtotime( $expiry_date );
        $now = current_time( 'timestamp' );

        // Check if "never" date (50+ years in future)
        $fifty_years = strtotime( '+50 years' );
        if ( $expiry_timestamp > $fifty_years ) {
            echo '<span class="bw-expiry-never" title="' . esc_attr__( 'Never expires', 'bw-expiry-post' ) . '">';
            echo '<span class="dashicons dashicons-infinity" style="color:#50a14f;"></span> ';
            echo esc_html__( 'Never', 'bw-expiry-post' );
            echo '</span>';
            return;
        }

        // Format the date
        $formatted_date = date_i18n( 'M j, Y', $expiry_timestamp );
        $formatted_time = date_i18n( 'g:i a', $expiry_timestamp );
        $full_date = date_i18n( 'F j, Y \a\t g:i a', $expiry_timestamp );

        // Determine status
        if ( $expiry_timestamp <= $now ) {
            // Expired
            $class = 'bw-expiry-expired';
            $icon = 'dashicons-warning';
            $icon_color = '#d63638';
            $label = __( 'Expired', 'bw-expiry-post' );
        } elseif ( $expiry_timestamp <= strtotime( '+7 days' ) ) {
            // Expiring soon (within 7 days)
            $class = 'bw-expiry-soon';
            $icon = 'dashicons-clock';
            $icon_color = '#dba617';
            $days_left = ceil( ( $expiry_timestamp - $now ) / DAY_IN_SECONDS );
            $label = sprintf( _n( '%d day', '%d days', $days_left, 'bw-expiry-post' ), $days_left );
        } else {
            // Future date
            $class = 'bw-expiry-future';
            $icon = 'dashicons-calendar-alt';
            $icon_color = '#50a14f';
            $label = $formatted_date;
        }

        echo '<span class="' . esc_attr( $class ) . '" title="' . esc_attr( $full_date ) . '">';
        echo '<span class="dashicons ' . esc_attr( $icon ) . '" style="color:' . esc_attr( $icon_color ) . ';font-size:16px;width:16px;height:16px;vertical-align:middle;"></span> ';
        echo '<span style="vertical-align:middle;">' . esc_html( $label ) . '</span>';
        echo '</span>';
    }

    /**
     * Make the column sortable
     */
    public function sortable_column( $columns ) {
        $columns['bw_expiry'] = 'bw_expiry';
        return $columns;
    }

    /**
     * Handle sorting by expiry date
     */
    public function sort_by_expiry( $query ) {
        if ( ! is_admin() || ! $query->is_main_query() ) {
            return;
        }

        if ( 'bw_expiry' !== $query->get( 'orderby' ) ) {
            return;
        }

        $query->set( 'meta_key', $this->meta_key );
        $query->set( 'orderby', 'meta_value' );

        // Include posts without expiry date
        $query->set( 'meta_query', array(
            'relation' => 'OR',
            array(
                'key'     => $this->meta_key,
                'compare' => 'EXISTS',
            ),
            array(
                'key'     => $this->meta_key,
                'compare' => 'NOT EXISTS',
            ),
        ) );
    }

    /**
     * Add inline styles for the column
     */
    public function column_styles() {
        $screen = get_current_screen();
        if ( ! $screen || 'edit' !== $screen->base ) {
            return;
        }

        $options = get_option( 'bw_expiry_settings', array() );
        $enabled_types = isset( $options['post_types'] ) ? $options['post_types'] : array( 'post' );

        if ( ! in_array( $screen->post_type, $enabled_types ) ) {
            return;
        }
        ?>
        <style>
            .column-bw_expiry {
                width: 120px;
            }
            .bw-expiry-expired {
                color: #d63638;
                font-weight: 500;
            }
            .bw-expiry-soon {
                color: #996800;
                font-weight: 500;
            }
            .bw-expiry-future {
                color: #2271b1;
            }
            .bw-expiry-never {
                color: #50a14f;
            }
        </style>
        <?php
    }
}
