<?php
defined( 'ABSPATH' ) || exit;

class Jalpi_Post_Support {

    private static $instance = null;

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

    private function __construct() {
        add_action( 'add_meta_boxes', [ $this, 'add_meta_box' ] );
        add_filter( 'page_row_actions',  [ $this, 'add_row_action' ], 10, 2 );
        add_filter( 'post_row_actions',  [ $this, 'add_row_action' ], 10, 2 );
        add_action( 'admin_bar_menu',    [ $this, 'admin_bar_link' ], 100 );
    }

    public function add_meta_box() {
        $types = get_option( 'jalpi_enabled_post_types', [ 'page', 'post' ] );
        foreach ( $types as $type ) {
            add_meta_box(
                'jalpi_edit_link',
                __( 'Jalpi Page Builder', 'jalpi-page-builder' ),
                [ $this, 'render_meta_box' ],
                $type,
                'side',
                'high'
            );
        }
    }

    public function render_meta_box( $post ) {
        $url = $this->editor_url( $post->ID );
        echo '<a href="' . esc_url( $url ) . '" class="button button-primary button-hero" style="width:100%;text-align:center;">';
        esc_html_e( 'Edit with Jalpi Page Builder', 'jalpi-page-builder' );
        echo '</a>';
    }

    public function add_row_action( $actions, $post ) {
        $types = get_option( 'jalpi_enabled_post_types', [ 'page', 'post' ] );
        if ( in_array( $post->post_type, $types, true ) ) {
            $actions['jalpi_edit'] = '<a href="' . esc_url( $this->editor_url( $post->ID ) ) . '">'
                . esc_html__( 'Jalpi Edit', 'jalpi-page-builder' ) . '</a>';
        }
        return $actions;
    }

    public function admin_bar_link( $wp_admin_bar ) {
        if ( ! is_singular() && ! is_admin() ) {
            return;
        }

        $post_id = get_the_ID();
        if ( ! $post_id ) {
            return;
        }

        $types = get_option( 'jalpi_enabled_post_types', [ 'page', 'post' ] );
        if ( ! in_array( get_post_type( $post_id ), $types, true ) ) {
            return;
        }

        $wp_admin_bar->add_node( [
            'id'    => 'jalpi_edit',
            'title' => __( 'Jalpi Edit', 'jalpi-page-builder' ),
            'href'  => $this->editor_url( $post_id ),
        ] );
    }

    private function editor_url( $post_id ) {
        return admin_url( 'admin.php?page=jalpi-page-builder-editor&post_id=' . intval( $post_id ) );
    }
}
