<?php
namespace Bookaro\Controller\Frontend;

defined( 'ABSPATH' ) || exit;

/**
 * Registers WooCommerce account endpoints and menu items.
 */
class AccountEndpointsController
{
    public function register_hooks(): void
    {
        if ( 'woocommerce' !== bookaro_get_ui_mode() ) {
            return;
        }
        add_action( 'init', [ $this, 'add_account_endpoint' ] );
        add_filter( 'query_vars', [ $this, 'add_query_vars' ], 0 );
        add_filter( 'woocommerce_account_menu_items', [ $this, 'add_menu_item' ] );
        add_action( 'woocommerce_account_bookings-and-management_endpoint', [ $this, 'render_bookings' ] );
    }

    public function add_account_endpoint(): void
    {
        add_rewrite_endpoint( 'bookings-and-management', EP_PAGES );
    }

    public function add_query_vars( array $vars ): array
    {
        $vars[] = 'bookings-and-management';
        return $vars;
    }

    public function add_menu_item( array $items ): array
    {
        $user          = wp_get_current_user();

        $new = [];
        foreach ( $items as $key => $label ) {
            $new[ $key ] = $label;
            if ( 'dashboard' === $key ) {
                if ( bookaro_user_has_dashboard_access( $user->ID ) ) {
                    $new['bookings-and-management'] = __( 'Bookings', 'mybookaro' );
                }
            }
        }
        return $new;
    }

    public function render_bookings(): void
    {
        if ( bookaro_get_option( 'require_login', 1 ) && ! is_user_logged_in() ) {
            return;
        }

        $assets = AssetsController::instance();
        if ( $assets ) {
            $assets->ensure_frontend_assets();
        }

        $user = wp_get_current_user();
        if ( bookaro_user_has_provider_access( $user->ID ) ) {
            echo '<div id="bookaro-provider-dashboard" class="bookaro-scope bookaro-provider-dashboard"></div>';
        } elseif ( bookaro_user_has_customer_access( $user->ID ) ) {
            echo '<div id="bookaro-owner-dashboard" class="bookaro-scope bookaro-owner-dashboard"></div>';
        }
    }
}
