<?php
/**
 * Settings page for BW Admin Note
 */

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

class BW_Admin_Note_Settings {

    private static $instance = null;

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

    private function __construct() {
        add_action( 'admin_menu', array( $this, 'add_settings_page' ) );
        add_action( 'admin_init', array( $this, 'register_settings' ) );
        add_filter( 'plugin_action_links_' . BW_ADMIN_NOTE_PLUGIN_BASENAME, array( $this, 'add_settings_link' ) );
    }

    /**
     * Add settings page to admin menu
     */
    public function add_settings_page() {
        add_options_page(
            __( 'BW Admin Notes Config', 'bw-admin-note' ),
            __( 'BW Admin Notes Config', 'bw-admin-note' ),
            'manage_options',
            'bw-admin-note',
            array( $this, 'render_settings_page' )
        );
    }

    /**
     * Add settings link to plugins page
     */
    public function add_settings_link( $links ) {
        $settings_link = sprintf(
            '<a href="%s">%s</a>',
            admin_url( 'options-general.php?page=bw-admin-note' ),
            __( 'Settings', 'bw-admin-note' )
        );
        array_unshift( $links, $settings_link );
        return $links;
    }

    /**
     * Register settings
     */
    public function register_settings() {
        register_setting(
            'bw_admin_note_settings_group',
            'bw_admin_note_settings',
            array( $this, 'sanitize_settings' )
        );

        // Post types section
        add_settings_section(
            'bw_admin_note_post_types_section',
            __( 'Enabled Post Types', 'bw-admin-note' ),
            array( $this, 'render_post_types_section' ),
            'bw-admin-note'
        );

        add_settings_field(
            'bw_admin_note_post_types',
            __( 'Post Types', 'bw-admin-note' ),
            array( $this, 'render_post_types_field' ),
            'bw-admin-note',
            'bw_admin_note_post_types_section'
        );
    }

    /**
     * Sanitize settings before save
     */
    public function sanitize_settings( $input ) {
        $sanitized = array();

        // Post types
        $sanitized['post_types'] = isset( $input['post_types'] ) && is_array( $input['post_types'] )
            ? array_map( 'sanitize_key', $input['post_types'] )
            : array( 'page' );

        return $sanitized;
    }

    /**
     * Render settings page
     */
    public function render_settings_page() {
        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }

        // Show save message
        if ( isset( $_GET['settings-updated'] ) ) {
            add_settings_error(
                'bw_admin_note_messages',
                'bw_admin_note_message',
                __( 'Settings saved.', 'bw-admin-note' ),
                'updated'
            );
        }

        settings_errors( 'bw_admin_note_messages' );
        ?>
        <div class="wrap">
            <h1><?php echo esc_html( get_admin_page_title() ); ?></h1>

            <div class="bw-admin-note-settings-wrap">
                <form action="options.php" method="post">
                    <?php
                    settings_fields( 'bw_admin_note_settings_group' );
                    do_settings_sections( 'bw-admin-note' );
                    submit_button( __( 'Save Settings', 'bw-admin-note' ) );
                    ?>
                </form>
            </div>

            <div class="bw-admin-note-info-box" style="background: #fff; padding: 15px 20px; margin-top: 20px; border: 1px solid #c3c4c7; border-left: 4px solid #2271b1;">
                <h3 style="margin-top: 0;"><?php esc_html_e( 'How It Works', 'bw-admin-note' ); ?></h3>
                <p><?php esc_html_e( 'Admin Notes allows you to add internal notes to posts and pages that are only visible to logged-in users in the WordPress editor.', 'bw-admin-note' ); ?></p>
                <p><?php esc_html_e( 'This is useful for:', 'bw-admin-note' ); ?></p>
                <ul style="list-style: disc; margin-left: 20px;">
                    <li><?php esc_html_e( 'Providing instructions to content editors', 'bw-admin-note' ); ?></li>
                    <li><?php esc_html_e( 'Documenting how a page works', 'bw-admin-note' ); ?></li>
                    <li><?php esc_html_e( 'Warning about important considerations', 'bw-admin-note' ); ?></li>
                    <li><?php esc_html_e( 'Leaving notes for future reference', 'bw-admin-note' ); ?></li>
                </ul>
                <p><strong><?php esc_html_e( 'Notes are never shown on the frontend - only in the editor.', 'bw-admin-note' ); ?></strong></p>
            </div>

            <?php $this->render_notes_index(); ?>
        </div>
        <?php
    }

    /**
     * Render index of all posts with admin notes
     */
    public function render_notes_index() {
        // Query all posts with admin notes
        $posts_with_notes = $this->get_posts_with_notes();

        ?>
        <div class="bw-admin-note-index" style="margin-top: 30px;">
            <h2><?php esc_html_e( 'Notes Index', 'bw-admin-note' ); ?></h2>
            <p class="description"><?php esc_html_e( 'All posts, pages, and custom post types that have admin notes.', 'bw-admin-note' ); ?></p>

            <?php if ( empty( $posts_with_notes ) ) : ?>
                <div style="background: #f0f0f1; padding: 20px; border-radius: 4px; margin-top: 15px;">
                    <p style="margin: 0; color: #50575e;">
                        <span class="dashicons dashicons-info" style="margin-right: 5px;"></span>
                        <?php esc_html_e( 'No posts with admin notes found.', 'bw-admin-note' ); ?>
                    </p>
                </div>
            <?php else : ?>
                <table class="wp-list-table widefat fixed striped" style="margin-top: 15px;">
                    <thead>
                        <tr>
                            <th scope="col" style="width: 22%;"><?php esc_html_e( 'Title', 'bw-admin-note' ); ?></th>
                            <th scope="col" style="width: 10%;"><?php esc_html_e( 'Type', 'bw-admin-note' ); ?></th>
                            <th scope="col" style="width: 10%;"><?php esc_html_e( 'Author', 'bw-admin-note' ); ?></th>
                            <th scope="col" style="width: 8%;"><?php esc_html_e( 'Status', 'bw-admin-note' ); ?></th>
                            <th scope="col" style="width: 50%;"><?php esc_html_e( 'Note Preview', 'bw-admin-note' ); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ( $posts_with_notes as $post_data ) : ?>
                            <tr>
                                <td>
                                    <strong>
                                        <a href="<?php echo esc_url( $post_data['edit_link'] ); ?>">
                                            <?php echo esc_html( $post_data['title'] ); ?>
                                        </a>
                                    </strong>
                                    <div class="row-actions">
                                        <span class="edit">
                                            <a href="<?php echo esc_url( $post_data['edit_link'] ); ?>"><?php esc_html_e( 'Edit', 'bw-admin-note' ); ?></a> |
                                        </span>
                                        <span class="view">
                                            <a href="<?php echo esc_url( $post_data['view_link'] ); ?>" target="_blank"><?php esc_html_e( 'View', 'bw-admin-note' ); ?></a>
                                        </span>
                                    </div>
                                </td>
                                <td>
                                    <span class="post-type-badge" style="background: #f0f0f1; padding: 3px 8px; border-radius: 3px; font-size: 12px;">
                                        <?php echo esc_html( $post_data['post_type_label'] ); ?>
                                    </span>
                                </td>
                                <td>
                                    <?php echo esc_html( $post_data['author_name'] ); ?>
                                </td>
                                <td>
                                    <?php
                                    $status_colors = array(
                                        'publish' => '#00a32a',
                                        'draft'   => '#d63638',
                                        'pending' => '#dba617',
                                        'private' => '#2271b1',
                                        'future'  => '#8c8f94',
                                    );
                                    $status_color = isset( $status_colors[ $post_data['status'] ] ) ? $status_colors[ $post_data['status'] ] : '#8c8f94';
                                    ?>
                                    <span style="color: <?php echo esc_attr( $status_color ); ?>; font-weight: 500;">
                                        <?php echo esc_html( $post_data['status_label'] ); ?>
                                    </span>
                                </td>
                                <td>
                                    <div class="note-preview" style="color: #50575e; font-size: 13px; line-height: 1.5; max-height: 60px; overflow: hidden; position: relative;">
                                        <?php echo esc_html( $post_data['note_preview'] ); ?>
                                        <?php if ( strlen( $post_data['note'] ) > 150 ) : ?>
                                            <span style="color: #2271b1;">...</span>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>

                <p style="margin-top: 15px; color: #50575e;">
                    <?php
                    printf(
                        esc_html( _n( '%d post with admin note found.', '%d posts with admin notes found.', count( $posts_with_notes ), 'bw-admin-note' ) ),
                        count( $posts_with_notes )
                    );
                    ?>
                </p>
            <?php endif; ?>
        </div>
        <?php
    }

    /**
     * Get all posts that have admin notes
     */
    private function get_posts_with_notes() {
        global $wpdb;

        // Query posts with non-empty admin notes
        $results = $wpdb->get_results(
            "SELECT p.ID, p.post_title, p.post_type, p.post_status, p.post_author, pm.meta_value as note
             FROM {$wpdb->posts} p
             INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
             WHERE pm.meta_key = '_bw_admin_note'
             AND pm.meta_value != ''
             AND p.post_status IN ('publish', 'draft', 'pending', 'private', 'future')
             ORDER BY p.post_type ASC, p.post_title ASC"
        );

        if ( empty( $results ) ) {
            return array();
        }

        $posts_with_notes = array();

        foreach ( $results as $row ) {
            // Get post type object for label
            $post_type_obj = get_post_type_object( $row->post_type );
            $post_type_label = $post_type_obj ? $post_type_obj->labels->singular_name : $row->post_type;

            // Get status label
            $status_obj = get_post_status_object( $row->post_status );
            $status_label = $status_obj ? $status_obj->label : ucfirst( $row->post_status );

            // Get author name
            $author = get_userdata( $row->post_author );
            $author_name = $author ? $author->display_name : __( 'Unknown', 'bw-admin-note' );

            // Create preview (first 150 chars)
            $note_preview = wp_strip_all_tags( $row->note );
            $note_preview = strlen( $note_preview ) > 150 ? substr( $note_preview, 0, 150 ) : $note_preview;

            $posts_with_notes[] = array(
                'id'              => $row->ID,
                'title'           => $row->post_title ? $row->post_title : __( '(no title)', 'bw-admin-note' ),
                'post_type'       => $row->post_type,
                'post_type_label' => $post_type_label,
                'author_id'       => $row->post_author,
                'author_name'     => $author_name,
                'status'          => $row->post_status,
                'status_label'    => $status_label,
                'note'            => $row->note,
                'note_preview'    => $note_preview,
                'edit_link'       => get_edit_post_link( $row->ID, 'raw' ),
                'view_link'       => get_permalink( $row->ID ),
            );
        }

        return $posts_with_notes;
    }

    /**
     * Render post types section description
     */
    public function render_post_types_section() {
        echo '<p>' . esc_html__( 'Select which post types should have the Admin Notes feature enabled.', 'bw-admin-note' ) . '</p>';
    }

    /**
     * Render post types checkboxes
     */
    public function render_post_types_field() {
        $options = get_option( 'bw_admin_note_settings', array() );
        $enabled_types = isset( $options['post_types'] ) ? $options['post_types'] : array( 'page' );

        // Get all public post types
        $post_types = get_post_types( array( 'public' => true ), 'objects' );

        // Exclude attachments
        unset( $post_types['attachment'] );

        foreach ( $post_types as $post_type ) {
            $checked = in_array( $post_type->name, $enabled_types );
            ?>
            <label class="bw-admin-note-post-type-option" style="display: block; margin-bottom: 8px;">
                <input
                    type="checkbox"
                    name="bw_admin_note_settings[post_types][]"
                    value="<?php echo esc_attr( $post_type->name ); ?>"
                    <?php checked( $checked ); ?>
                >
                <?php echo esc_html( $post_type->labels->singular_name ); ?>
                <span class="description" style="color: #666;">(<?php echo esc_html( $post_type->name ); ?>)</span>
            </label>
            <?php
        }
    }
}
