<?php
namespace Bookaro\Controller;

defined( 'ABSPATH' ) || exit;

/**
 * Registers the Bookaro provider listing post type for generic mode.
 */
class ProviderPostTypeController
{
    public function register_hooks(): void
    {
        if ( ! $this->generic_mode_enabled() ) {
            return;
        }
        add_action( 'init', [ $this, 'register_post_type' ] );
        add_action( 'init', [ $this, 'register_meta' ] );
        add_action( 'add_meta_boxes', [ $this, 'register_meta_box' ] );
        add_action( 'save_post_' . BOOKARO_PROVIDER_POST_TYPE, [ $this, 'save_meta' ] );
    }

    public function register_post_type(): void
    {
        if ( ! $this->generic_mode_enabled() ) {
            return;
        }
        $labels = [
            'name'               => __( 'Providers', 'mybookaro' ),
            'singular_name'      => __( 'Provider', 'mybookaro' ),
            'add_new'            => __( 'Add New', 'mybookaro' ),
            'add_new_item'       => __( 'Add New Provider', 'mybookaro' ),
            'edit_item'          => __( 'Edit Provider', 'mybookaro' ),
            'new_item'           => __( 'New Provider', 'mybookaro' ),
            'view_item'          => __( 'View Provider', 'mybookaro' ),
            'search_items'       => __( 'Search Providers', 'mybookaro' ),
            'not_found'          => __( 'No providers found.', 'mybookaro' ),
            'not_found_in_trash' => __( 'No providers found in Trash.', 'mybookaro' ),
            'all_items'          => __( 'Providers', 'mybookaro' ),
            'menu_name'          => __( 'Providers', 'mybookaro' ),
        ];

        $show_ui = (bool) apply_filters( 'bookaro_show_provider_ui', true );
        $menu    = $show_ui ? 'bookaro-bookings' : false;

        register_post_type(
            BOOKARO_PROVIDER_POST_TYPE,
            [
                'labels'             => $labels,
                'public'             => true,
                'publicly_queryable' => true,
                'show_ui'            => $show_ui,
                'show_in_menu'       => $menu,
                'show_in_rest'       => true,
                'has_archive'        => true,
                'rewrite'            => [ 'slug' => 'providers' ],
                'menu_position'      => 25,
                'menu_icon'          => 'dashicons-id-alt',
                'supports'           => [ 'title', 'editor', 'thumbnail', 'author' ],
                'capability_type'    => 'post',
                'map_meta_cap'       => true,
            ]
        );
    }

    public function register_meta(): void
    {
        if ( ! $this->generic_mode_enabled() ) {
            return;
        }
        register_post_meta(
            BOOKARO_PROVIDER_POST_TYPE,
            BOOKARO_PROVIDER_EMAIL_META,
            [
                'type'              => 'string',
                'single'            => true,
                'show_in_rest'      => true,
                'sanitize_callback' => 'sanitize_email',
                'auth_callback'     => fn() => current_user_can( 'edit_posts' ),
            ]
        );

        register_post_meta(
            BOOKARO_PROVIDER_POST_TYPE,
            BOOKARO_PROVIDER_PHONE_META,
            [
                'type'              => 'string',
                'single'            => true,
                'show_in_rest'      => true,
                'sanitize_callback' => 'sanitize_text_field',
                'auth_callback'     => fn() => current_user_can( 'edit_posts' ),
            ]
        );
    }

    public function register_meta_box(): void
    {
        if ( ! $this->generic_mode_enabled() ) {
            return;
        }
        add_meta_box(
            'bookaro-provider-contact',
            __( 'Provider Contact', 'mybookaro' ),
            [ $this, 'render_meta_box' ],
            BOOKARO_PROVIDER_POST_TYPE,
            'normal',
            'default'
        );
    }

    public function render_meta_box( \WP_Post $post ): void
    {
        if ( ! $this->generic_mode_enabled() ) {
            return;
        }
        wp_nonce_field( 'bookaro_provider_contact', 'bookaro_provider_contact_nonce' );

        $email = get_post_meta( $post->ID, BOOKARO_PROVIDER_EMAIL_META, true );
        $phone = get_post_meta( $post->ID, BOOKARO_PROVIDER_PHONE_META, true );
        ?>
        <p>
            <label for="bookaro-provider-email"><?php esc_html_e( 'Contact Email', 'mybookaro' ); ?></label><br />
            <input
                type="email"
                class="regular-text"
                id="bookaro-provider-email"
                name="bookaro_provider_email"
                value="<?php echo esc_attr( $email ); ?>"
            />
        </p>
        <p>
            <label for="bookaro-provider-phone"><?php esc_html_e( 'Contact Phone', 'mybookaro' ); ?></label><br />
            <input
                type="text"
                class="regular-text"
                id="bookaro-provider-phone"
                name="bookaro_provider_phone"
                value="<?php echo esc_attr( $phone ); ?>"
            />
        </p>
        <?php
    }

    public function save_meta( int $post_id ): void
    {
        if ( ! $this->generic_mode_enabled() ) {
            return;
        }
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
            return;
        }

        if (
            empty( $_POST['bookaro_provider_contact_nonce'] )
            || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['bookaro_provider_contact_nonce'] ) ), 'bookaro_provider_contact' )
        ) {
            return;
        }

        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            return;
        }

        if ( array_key_exists( 'bookaro_provider_email', $_POST ) ) {
            $email = sanitize_email( wp_unslash( $_POST['bookaro_provider_email'] ) );
            update_post_meta( $post_id, BOOKARO_PROVIDER_EMAIL_META, $email );
        }

        if ( array_key_exists( 'bookaro_provider_phone', $_POST ) ) {
            $phone = sanitize_text_field( wp_unslash( $_POST['bookaro_provider_phone'] ) );
            update_post_meta( $post_id, BOOKARO_PROVIDER_PHONE_META, $phone );
        }
    }

    private function generic_mode_enabled(): bool
    {
        if ( defined( 'BOOKARO_ENABLE_GENERIC_MODE' ) && ! BOOKARO_ENABLE_GENERIC_MODE ) {
            return false;
        }
        return function_exists( 'bookaro_get_integration_mode' )
            && 'generic' === bookaro_get_integration_mode();
    }
}
