<?php

/**
 * My Account Editor helper functions
 *
 * @package ArraySubs\Functions
 * @since 1.9.0
 */

defined('ABSPATH') || exit;

/**
 * Get the saved My Account menu configuration.
 *
 * @return array
 */
function arraysubs_get_myaccount_menu_config(): array
{
    $config = get_option('arraysubs_myaccount_menu_config', []);

    if (!is_array($config)) {
        return [];
    }

    return $config;
}

/**
 * Save the My Account menu configuration.
 *
 * @param array $items Menu items to save.
 * @return bool
 */
function arraysubs_save_myaccount_menu_config(array $items): bool
{
    $sanitized = arraysubs_sanitize_myaccount_menu_config($items);
    return update_option('arraysubs_myaccount_menu_config', $sanitized);
}

/**
 * Sanitize the My Account menu configuration.
 *
 * @param array $items Raw menu items.
 * @return array Sanitized items.
 */
function arraysubs_sanitize_myaccount_menu_config(array $items): array
{
    $sanitized = [];

    foreach ($items as $index => $item) {
        if (!is_array($item)) {
            continue;
        }

        $type = sanitize_text_field($item['type'] ?? 'default');

        if (!in_array($type, ['default', 'custom'], true)) {
            continue;
        }

        $sanitized_item = [
            'id'       => sanitize_key($item['id'] ?? ''),
            'label'    => sanitize_text_field($item['label'] ?? ''),
            'type'     => $type,
            'enabled'  => isset($item['enabled']) ? (bool) $item['enabled'] : true,
            'position' => absint($item['position'] ?? $index),
        ];

        if ('custom' === $type) {
            $sanitized_item['content_id']            = absint($item['content_id'] ?? 0);
            $sanitized_item['content_type']          = sanitize_text_field($item['content_type'] ?? 'page');
            $sanitized_item['endpoint']              = sanitize_title($item['endpoint'] ?? '');
            $sanitized_item['prevent_direct_access'] = !empty($item['prevent_direct_access']);
        }

        if (!empty($sanitized_item['id'])) {
            $sanitized[] = $sanitized_item;
        }
    }

    return $sanitized;
}

/**
 * Get the default WooCommerce My Account menu items.
 *
 * Temporarily bypasses the MyAccountEditor reorder filter so we get the raw
 * WC defaults (plus items added by other plugins/features).
 *
 * @return array Normalized array of default menu items.
 */
function arraysubs_get_default_myaccount_menu_items(): array
{
    // Tell the Hooks service to skip its reorder logic for this call.
    \ArraySubs\Features\MyAccountEditor\Services\Hooks::$bypass_menu_filter = true;

    $wc_items = function_exists('wc_get_account_menu_items')
        ? wc_get_account_menu_items()
        : [];

    \ArraySubs\Features\MyAccountEditor\Services\Hooks::$bypass_menu_filter = false;

    $defaults = [];

    foreach ($wc_items as $endpoint => $label) {
        $defaults[] = [
            'id'      => sanitize_key($endpoint),
            'label'   => $label,
            'type'    => 'default',
            'enabled' => true,
        ];
    }

    return $defaults;
}

/**
 * Get the list of custom endpoints from saved config.
 *
 * @return array
 */
function arraysubs_get_custom_myaccount_endpoints(): array
{
    $config = arraysubs_get_myaccount_menu_config();
    $custom = [];

    foreach ($config as $item) {
        if (isset($item['type']) && 'custom' === $item['type'] && !empty($item['endpoint'])) {
            $custom[] = $item;
        }
    }

    return $custom;
}

/**
 * Schedule a rewrite rules flush for My Account editor changes.
 *
 * @return void
 */
function arraysubs_schedule_myaccount_editor_flush(): void
{
    if (!get_option('arraysubs_myaccount_editor_flush_pending')) {
        update_option('arraysubs_myaccount_editor_flush_pending', '1');
        add_action('shutdown', function () {
            flush_rewrite_rules();
            delete_option('arraysubs_myaccount_editor_flush_pending');
        });
    }
}
