<?php
namespace Bookaro\Utils;

defined( 'ABSPATH' ) || exit;

/**
 * Shared payload helpers for lane summary admin banners.
 */
class AdminLaneSummary
{
    public static function create_payload( string $lane_label = '' ): array
    {
        return [
            'title' => __( 'Lane summary', 'mybookaro' ),
            'summary' => __( 'Shared lane snapshot with the highest-priority blocker and next action.', 'mybookaro' ),
            'lane_label' => trim( $lane_label ),
            'state' => 'info',
            'state_label' => __( 'Info', 'mybookaro' ),
            'model_label' => __( 'Current lane profile', 'mybookaro' ),
            'model_summary' => '',
            'model_items' => [],
            'top_blocker' => '',
            'next_action' => [
                'label' => '',
                'url' => '',
                'detail' => '',
            ],
        ];
    }

    public static function resolve_lane_label( string $lane_id = '', string $resolved_mode = '', string $site_type = '' ): string
    {
        $lane_id = sanitize_key( $lane_id );
        $resolved_mode = sanitize_key( $resolved_mode );
        $site_type = sanitize_key( $site_type );

        if ( 'single_business' === $site_type || 'single_business' === $lane_id ) {
            return __( 'Single Business', 'mybookaro' );
        }

        if ( 'mylisting_directory' === $lane_id || 'mylisting' === $resolved_mode ) {
            return __( 'MyListing Directory', 'mybookaro' );
        }

        return __( 'Generic Directory', 'mybookaro' );
    }

    public static function find_first_incomplete( array $items, string $completion_key = 'passed' ): ?array
    {
        foreach ( $items as $item ) {
            if ( ! is_array( $item ) ) {
                continue;
            }

            if ( ! empty( $item[ $completion_key ] ) ) {
                continue;
            }

            return $item;
        }

        return null;
    }

    public static function resolve_blocker_summary( array $blocker ): string
    {
        foreach ( [ 'summary', 'next_step', 'fix', 'detail', 'label' ] as $key ) {
            $value = trim( (string) ( $blocker[ $key ] ?? '' ) );
            if ( '' !== $value ) {
                return $value;
            }
        }

        return '';
    }

    public static function resolve_single_business_focus( array $context = [] ): array
    {
        $provider_ready = ! empty( $context['provider_ready'] );
        $pages_ready = ! empty( $context['pages_ready'] );
        $services_ready = ! empty( $context['services_ready'] );
        $missing_page_keys_raw = is_array( $context['missing_page_keys'] ?? null ) ? $context['missing_page_keys'] : [];
        $missing_page_keys = [];
        foreach ( $missing_page_keys_raw as $missing_page_key ) {
            $missing_page_key = sanitize_key( (string) $missing_page_key );
            if ( '' === $missing_page_key ) {
                continue;
            }
            $missing_page_keys[] = $missing_page_key;
        }
        $missing_page_keys = array_values( array_unique( $missing_page_keys ) );
        $missing_booking_page = in_array( 'booking', $missing_page_keys, true );
        $missing_dashboard_pages = in_array( 'provider_dashboard', $missing_page_keys, true ) || in_array( 'customer_dashboard', $missing_page_keys, true );

        $default_provider_url = trim( (string) ( $context['default_provider_url'] ?? '' ) );
        $pages_url = trim( (string) ( $context['pages_url'] ?? '' ) );
        $create_service_url = trim( (string) ( $context['create_service_url'] ?? '' ) );
        $ready_url = trim( (string) ( $context['ready_url'] ?? '' ) );

        if ( '' === $create_service_url ) {
            $create_service_url = admin_url(
                'post-new.php?post_type=' . ( defined( 'BOOKARO_SERVICE_POST_TYPE' ) ? BOOKARO_SERVICE_POST_TYPE : 'bookaro_service' )
            );
        }

        $provider_detail = trim( (string) ( $context['provider_detail'] ?? __( 'Set Default Provider first, then continue with pages and validation.', 'mybookaro' ) ) );
        $pages_detail = trim( (string) ( $context['pages_detail'] ?? __( 'Assign booking/services/dashboard pages in Setup Wizard > Pages.', 'mybookaro' ) ) );
        $services_detail = trim( (string) ( $context['services_detail'] ?? __( 'Create at least one provider service, then run one end-to-end booking flow test.', 'mybookaro' ) ) );
        $ready_label = trim( (string) ( $context['ready_label'] ?? __( 'Open booking/services preview', 'mybookaro' ) ) );
        $ready_detail = trim( (string) ( $context['ready_detail'] ?? __( 'Run one end-to-end booking from your booking/services page to verify launch readiness.', 'mybookaro' ) ) );

        if ( ! $provider_ready ) {
            return [
                'state' => 'error',
                'state_label' => __( 'Blocked', 'mybookaro' ),
                'top_blocker' => __( 'Default Provider is missing, so Single Business launch checks cannot complete.', 'mybookaro' ),
                'next_action' => [
                    'label' => __( 'Review Default Provider', 'mybookaro' ),
                    'url' => $default_provider_url,
                    'detail' => $provider_detail,
                ],
            ];
        }

        if ( ! $pages_ready ) {
            $pages_action_label = trim( (string) ( $context['pages_action_label'] ?? '' ) );
            if ( '' === $pages_action_label ) {
                if ( $missing_booking_page && $missing_dashboard_pages ) {
                    $pages_action_label = __( 'Assign booking + dashboard pages', 'mybookaro' );
                } elseif ( $missing_booking_page ) {
                    $pages_action_label = __( 'Assign Booking page', 'mybookaro' );
                } elseif ( $missing_dashboard_pages ) {
                    $pages_action_label = __( 'Assign dashboard pages', 'mybookaro' );
                } else {
                    $pages_action_label = __( 'Assign pages', 'mybookaro' );
                }
            }
            $pages_top_blocker = __( 'Booking/services pages are missing for Single Business launch flow.', 'mybookaro' );
            if ( $missing_booking_page && $missing_dashboard_pages ) {
                $pages_top_blocker = __( 'Booking page and dashboard pages are missing for Single Business launch flow.', 'mybookaro' );
            } elseif ( $missing_booking_page ) {
                $pages_top_blocker = __( 'Booking page is missing for Single Business launch flow.', 'mybookaro' );
            } elseif ( $missing_dashboard_pages ) {
                $pages_top_blocker = __( 'Provider/Customer dashboard pages are missing for Shortcodes mode.', 'mybookaro' );
            }

            return [
                'state' => 'warn',
                'state_label' => __( 'Needs attention', 'mybookaro' ),
                'top_blocker' => $pages_top_blocker,
                'next_action' => [
                    'label' => $pages_action_label,
                    'url' => $pages_url,
                    'detail' => $pages_detail,
                ],
            ];
        }

        if ( ! $services_ready ) {
            return [
                'state' => 'warn',
                'state_label' => __( 'Needs attention', 'mybookaro' ),
                'top_blocker' => __( 'No services are available for the Default Provider yet.', 'mybookaro' ),
                'next_action' => [
                    'label' => __( 'Create first service', 'mybookaro' ),
                    'url' => $create_service_url,
                    'detail' => $services_detail,
                ],
            ];
        }

        return [
            'state' => 'ok',
            'state_label' => __( 'Ready', 'mybookaro' ),
            'top_blocker' => __( 'No blockers detected for the current Single Business setup.', 'mybookaro' ),
            'next_action' => [
                'label' => $ready_label,
                'url' => $ready_url,
                'detail' => $ready_detail,
            ],
        ];
    }

    public static function build_single_business_readiness_snapshot( array $context = [] ): array
    {
        $provider_ready = ! empty( $context['provider_ready'] );
        $booking_page_ready = ! empty( $context['booking_page_ready'] );
        $services_ready = ! empty( $context['services_ready'] );
        $dashboard_mode = sanitize_key( (string) ( $context['dashboard_mode'] ?? 'shortcodes' ) );
        if ( ! in_array( $dashboard_mode, [ 'shortcodes', 'woocommerce' ], true ) ) {
            $dashboard_mode = 'shortcodes';
        }
        $dashboard_pages_ready = ! empty( $context['dashboard_pages_ready'] );
        if ( 'woocommerce' === $dashboard_mode ) {
            $dashboard_pages_ready = true;
        }
        $preview_ready = ! empty( $context['preview_ready'] );
        $fast_path_ready = ! empty( $context['fast_path_ready'] );
        $services_count = max( 0, absint( $context['services_count'] ?? 0 ) );

        $services_value = '';
        if ( ! $provider_ready ) {
            $services_value = __( 'Blocked until Default Provider is set', 'mybookaro' );
        } elseif ( $services_ready ) {
            $services_value = ( 1 === $services_count )
                ? __( '1 available service', 'mybookaro' )
                : sprintf(
                    /* translators: %d: available services count */
                    __( '%d available services', 'mybookaro' ),
                    $services_count
                );
        } else {
            $services_value = __( 'Missing for Default Provider', 'mybookaro' );
        }

        $dashboard_value = ( 'shortcodes' === $dashboard_mode )
            ? (
                $dashboard_pages_ready
                    ? __( 'Shortcodes mode (dashboard pages assigned)', 'mybookaro' )
                    : __( 'Shortcodes mode (assign dashboard pages)', 'mybookaro' )
            )
            : __( 'WooCommerce My Account mode', 'mybookaro' );

        $preview_fast_path_ready = $preview_ready && $fast_path_ready;
        if ( $preview_fast_path_ready ) {
            $preview_fast_path_value = __( 'Ready to preview booking and run fast path', 'mybookaro' );
        } elseif ( ! $provider_ready ) {
            $preview_fast_path_value = __( 'Set Default Provider first', 'mybookaro' );
        } elseif ( ! $booking_page_ready ) {
            $preview_fast_path_value = __( 'Assign Booking page first', 'mybookaro' );
        } elseif ( ! $dashboard_pages_ready ) {
            $preview_fast_path_value = __( 'Assign dashboard pages for Shortcodes mode', 'mybookaro' );
        } elseif ( ! $services_ready ) {
            $preview_fast_path_value = __( 'Create first service for Default Provider', 'mybookaro' );
        } else {
            $preview_fast_path_value = __( 'Finish preview path setup', 'mybookaro' );
        }

        $checks_ready = 0;
        $checks_ready += $provider_ready ? 1 : 0;
        $checks_ready += $booking_page_ready ? 1 : 0;
        $checks_ready += $services_ready ? 1 : 0;
        $checks_ready += $dashboard_pages_ready ? 1 : 0;
        $checks_ready += $preview_fast_path_ready ? 1 : 0;

        $summary = sprintf(
            /* translators: 1: ready checks count, 2: total checks count */
            __( 'Single Business launch assistant: %1$d of %2$d checks ready.', 'mybookaro' ),
            $checks_ready,
            5
        );

        if ( ! $provider_ready ) {
            $summary .= ' ' . __( 'Next priority: set Default Provider.', 'mybookaro' );
        } elseif ( ! $booking_page_ready ) {
            $summary .= ' ' . __( 'Next priority: assign Booking page.', 'mybookaro' );
        } elseif ( ! $dashboard_pages_ready ) {
            $summary .= ' ' . __( 'Next priority: assign dashboard pages for Shortcodes mode.', 'mybookaro' );
        } elseif ( ! $services_ready ) {
            $summary .= ' ' . __( 'Next priority: create the first service for the Default Provider.', 'mybookaro' );
        } elseif ( ! $preview_fast_path_ready ) {
            $summary .= ' ' . __( 'Next priority: run preview booking and fast path.', 'mybookaro' );
        }

        return [
            'summary' => $summary,
            'items' => [
                [
                    'label' => __( 'Default Provider', 'mybookaro' ),
                    'value' => $provider_ready ? __( 'Set', 'mybookaro' ) : __( 'Missing', 'mybookaro' ),
                ],
                [
                    'label' => __( 'Booking page', 'mybookaro' ),
                    'value' => $booking_page_ready ? __( 'Assigned', 'mybookaro' ) : __( 'Missing', 'mybookaro' ),
                ],
                [
                    'label' => __( 'Services availability', 'mybookaro' ),
                    'value' => $services_value,
                ],
                [
                    'label' => __( 'Dashboard mode', 'mybookaro' ),
                    'value' => $dashboard_value,
                ],
                [
                    'label' => __( 'Preview booking fast-path', 'mybookaro' ),
                    'value' => $preview_fast_path_value,
                ],
            ],
        ];
    }

    public static function resolve_mylisting_focus( array $activation_flow = [], array $fallback_next_action = [] ): array
    {
        $milestones = is_array( $activation_flow['milestones'] ?? null ) ? $activation_flow['milestones'] : [];
        $pending_milestone = self::find_first_incomplete( $milestones, 'passed' );

        $completed = absint( $activation_flow['completed'] ?? 0 );
        $total = absint( $activation_flow['total'] ?? 0 );
        if ( $total < 1 ) {
            $total = count( $milestones );
        }
        if ( $total < 1 ) {
            $total = 4;
        }

        $state = ( $completed >= $total && null === $pending_milestone ) ? 'ok' : 'warn';
        $state_label = ( 'ok' === $state ) ? __( 'Ready', 'mybookaro' ) : __( 'Needs attention', 'mybookaro' );
        $top_blocker = __( 'No blockers detected for MyListing first-booking milestones.', 'mybookaro' );
        $next_action = is_array( $fallback_next_action ) ? $fallback_next_action : [];

        if ( is_array( $pending_milestone ) ) {
            $top_blocker = trim( (string) ( $pending_milestone['detail'] ?? '' ) );
            if ( '' === $top_blocker ) {
                $top_blocker = sprintf(
                    /* translators: %s: pending milestone label */
                    __( 'Pending milestone: %s.', 'mybookaro' ),
                    (string) ( $pending_milestone['label'] ?? __( 'Setup step', 'mybookaro' ) )
                );
            }
            if ( is_array( $pending_milestone['action'] ?? null ) ) {
                $next_action = $pending_milestone['action'];
            }
            if ( '' === trim( (string) ( $next_action['detail'] ?? '' ) ) ) {
                $next_action['detail'] = sprintf(
                    /* translators: %s: pending milestone label */
                    __( 'Next step: %s', 'mybookaro' ),
                    (string) ( $pending_milestone['label'] ?? __( 'Setup step', 'mybookaro' ) )
                );
            }
        } elseif ( '' === trim( (string) ( $next_action['detail'] ?? '' ) ) ) {
            $next_action['detail'] = __( 'Run another booking request to verify notifications and availability changes.', 'mybookaro' );
        }

        return [
            'state' => $state,
            'state_label' => $state_label,
            'top_blocker' => $top_blocker,
            'next_action' => is_array( $next_action ) ? $next_action : [],
        ];
    }

    public static function build_generic_model_snapshot(
        string $pattern_label,
        string $provider_mapping_label,
        string $services_model_label,
        string $placement_label
    ): array {
        $pattern_label = trim( $pattern_label );
        if ( '' === $pattern_label ) {
            $pattern_label = __( 'Not set', 'mybookaro' );
        }
        $provider_mapping_label = trim( $provider_mapping_label );
        if ( '' === $provider_mapping_label ) {
            $provider_mapping_label = __( 'Not set', 'mybookaro' );
        }
        $services_model_label = trim( $services_model_label );
        if ( '' === $services_model_label ) {
            $services_model_label = __( 'Not set', 'mybookaro' );
        }
        $placement_label = trim( $placement_label );
        if ( '' === $placement_label ) {
            $placement_label = __( 'Not set', 'mybookaro' );
        }

        $items = [
            [
                'label' => __( 'Pattern', 'mybookaro' ),
                'value' => $pattern_label,
            ],
            [
                'label' => __( 'Provider ownership', 'mybookaro' ),
                'value' => $provider_mapping_label,
            ],
            [
                'label' => __( 'Service ownership', 'mybookaro' ),
                'value' => $services_model_label,
            ],
            [
                'label' => __( 'Placement strategy', 'mybookaro' ),
                'value' => $placement_label,
            ],
        ];

        return [
            'summary' => sprintf(
                /* translators: 1: pattern label, 2: provider ownership label, 3: service ownership label, 4: placement strategy label */
                __( 'Pattern: %1$s | Provider ownership: %2$s | Service ownership: %3$s | Placement: %4$s', 'mybookaro' ),
                $pattern_label,
                $provider_mapping_label,
                $services_model_label,
                $placement_label
            ),
            'items' => $items,
        ];
    }

    private static function normalize_model_items( array $items ): array
    {
        $normalized = [];
        foreach ( $items as $item ) {
            if ( ! is_array( $item ) ) {
                continue;
            }
            $label = trim( (string) ( $item['label'] ?? '' ) );
            $value = trim( (string) ( $item['value'] ?? '' ) );
            if ( '' === $label || '' === $value ) {
                continue;
            }
            $normalized[] = [
                'label' => $label,
                'value' => $value,
            ];
        }
        return $normalized;
    }

    public static function normalize( array $summary ): array
    {
        $state = sanitize_key( (string) ( $summary['state'] ?? 'info' ) );
        if ( ! in_array( $state, [ 'ok', 'warn', 'error', 'info' ], true ) ) {
            $state = 'info';
        }

        $state_labels = [
            'ok' => __( 'Ready', 'mybookaro' ),
            'warn' => __( 'Needs attention', 'mybookaro' ),
            'error' => __( 'Blocked', 'mybookaro' ),
            'info' => __( 'Info', 'mybookaro' ),
        ];

        $next_action = is_array( $summary['next_action'] ?? null ) ? $summary['next_action'] : [];
        $normalized = [
            'visible' => ! array_key_exists( 'visible', $summary ) || ! empty( $summary['visible'] ),
            'title' => trim( (string) ( $summary['title'] ?? __( 'Lane summary', 'mybookaro' ) ) ),
            'summary' => trim( (string) ( $summary['summary'] ?? '' ) ),
            'state' => $state,
            'state_label' => trim( (string) ( $summary['state_label'] ?? ( $state_labels[ $state ] ?? __( 'Info', 'mybookaro' ) ) ) ),
            'lane_label' => trim( (string) ( $summary['lane_label'] ?? '' ) ),
            'model_label' => trim( (string) ( $summary['model_label'] ?? __( 'Current lane profile', 'mybookaro' ) ) ),
            'model_summary' => trim( (string) ( $summary['model_summary'] ?? '' ) ),
            'model_items' => self::normalize_model_items( is_array( $summary['model_items'] ?? null ) ? $summary['model_items'] : [] ),
            'top_blocker_label' => trim( (string) ( $summary['top_blocker_label'] ?? __( 'Top blocker', 'mybookaro' ) ) ),
            'top_blocker' => trim( (string) ( $summary['top_blocker'] ?? '' ) ),
            'next_action_label' => trim( (string) ( $summary['next_action_label'] ?? __( 'Next action', 'mybookaro' ) ) ),
            'next_action' => [
                'label' => trim( (string) ( $next_action['label'] ?? '' ) ),
                'url' => trim( (string) ( $next_action['url'] ?? '' ) ),
                'detail' => trim( (string) ( $next_action['detail'] ?? '' ) ),
            ],
        ];

        if ( '' === $normalized['title'] ) {
            $normalized['title'] = __( 'Lane summary', 'mybookaro' );
        }
        if ( '' === $normalized['state_label'] ) {
            $normalized['state_label'] = $state_labels[ $state ] ?? __( 'Info', 'mybookaro' );
        }

        return $normalized;
    }
}
