<?php
/**
 * Visual submenu section headings in the maca Restu admin menu.
 *
 * @package Maca_Menu_List
 */

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Submenu slugs grouped under "Import & backup".
 *
 * @return array<int, string>
 */
function maca_menulist_get_import_backup_submenu_slugs() {
    $slugs = array(
        'maca-restu-backup',
    );

    if (maca_menulist_is_dishes_mode()) {
        $slugs = array_merge(
            array(
                'maca-restu-dish-csv',
                'maca-restu-import-pdf',
            ),
            $slugs
        );
    }

    /**
     * Submenu slugs shown under the Import & backup heading.
     *
     * @param array<int, string> $slugs Page slugs.
     */
    return apply_filters('maca_menulist_import_backup_submenu_slugs', $slugs);
}

/**
 * Whether the Import & backup submenu group should render expanded.
 *
 * @return bool
 */
function maca_menulist_import_group_is_open() {
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : '';

    if ($page !== '' && in_array($page, maca_menulist_get_import_backup_submenu_slugs(), true)) {
        return true;
    }

    $user_id = get_current_user_id();
    if ($user_id <= 0) {
        return false;
    }

    $stored = get_user_meta($user_id, 'maca_menulist_import_group_open', true);

    if ($stored === '1') {
        return true;
    }

    if ($stored === '0') {
        return false;
    }

    return false;
}

/**
 * Persist Import & backup submenu open/closed state for the current user.
 *
 * @param bool $is_open Whether the group is open.
 * @return void
 */
function maca_menulist_save_import_group_open_state($is_open) {
    $user_id = get_current_user_id();
    if ($user_id <= 0) {
        return;
    }

    update_user_meta($user_id, 'maca_menulist_import_group_open', $is_open ? '1' : '0');
}

/**
 * Register admin menu group hooks.
 *
 * @return void
 */
function maca_menulist_register_admin_menu_groups() {
    add_action('admin_menu', 'maca_menulist_add_import_backup_submenu_heading', 19);
    add_action('admin_init', 'maca_menulist_redirect_admin_submenu_heading_pages', 1);
    add_action('admin_enqueue_scripts', 'maca_menulist_enqueue_admin_menu_groups_assets');
    add_action('adminmenu', 'maca_menulist_bootstrap_admin_menu_groups', 20);
    add_filter('admin_body_class', 'maca_menulist_admin_menu_groups_body_class');
    add_action('wp_ajax_maca_menulist_import_group_toggle', 'maca_menulist_ajax_import_group_toggle');
}

/**
 * Body class for collapsed Import & backup group (works before JS runs).
 *
 * @param string $classes Space-separated admin body classes.
 * @return string
 */
function maca_menulist_admin_menu_groups_body_class($classes) {
    if (!is_admin() || !maca_menulist_user_can_manage_plugin()) {
        return $classes;
    }

    if (maca_menulist_import_group_is_open()) {
        return $classes . ' maca-import-group-open';
    }

    return $classes . ' maca-import-group-collapsed';
}

/**
 * Apply child markers and collapsed state as soon as the admin menu exists.
 *
 * @return void
 */
function maca_menulist_bootstrap_admin_menu_groups() {
    if (!maca_menulist_user_can_manage_plugin()) {
        return;
    }

    $config = array(
        'groupSlug'  => 'maca-restu-group-import-backup',
        'childPages' => maca_menulist_get_import_backup_submenu_slugs(),
        'isOpen'     => maca_menulist_import_group_is_open(),
    );

    echo '<script>(function(){';
    echo 'var cfg=' . wp_json_encode($config) . ';';
    echo 'var top=document.getElementById("toplevel_page_maca-restu");';
    echo 'if(!top){return;}';
    echo 'cfg.childPages.forEach(function(slug){';
    echo 'top.querySelectorAll(".wp-submenu a").forEach(function(link){';
    echo 'if((link.getAttribute("href")||"").indexOf("page="+slug)!==-1&&link.parentElement){';
    echo 'link.parentElement.classList.add("maca-menulist-import-child");';
    echo '}});});';
    echo 'var heading=null;';
    echo 'top.querySelectorAll(".wp-submenu a").forEach(function(link){';
    echo 'if((link.getAttribute("href")||"").indexOf("page="+cfg.groupSlug)!==-1){heading=link;}';
    echo 'if(link.querySelector(".maca-menulist-submenu-heading--toggle")){heading=link;}';
    echo '});';
    echo 'if(heading){';
    echo 'heading.setAttribute("role","button");';
    echo 'heading.setAttribute("href","#maca-menulist-import-backup-submenu");';
    echo 'heading.setAttribute("aria-expanded",cfg.isOpen?"true":"false");';
    echo 'heading.setAttribute("aria-controls","maca-menulist-import-backup-submenu");';
    echo '}';
    echo 'top.classList.toggle("maca-import-group-open",!!cfg.isOpen);';
    echo 'top.classList.toggle("maca-import-group-collapsed",!cfg.isOpen);';
    echo '})();</script>';
}

/**
 * AJAX: save Import & backup submenu open/closed preference.
 *
 * @return void
 */
function maca_menulist_ajax_import_group_toggle() {
    if (!maca_menulist_user_can_manage_plugin()) {
        wp_send_json_error(array('message' => 'Forbidden'), 403);
    }

    check_ajax_referer('maca_menulist_import_group_toggle', 'nonce');

    $open = isset($_POST['open']) && sanitize_text_field(wp_unslash($_POST['open'])) === '1';
    maca_menulist_save_import_group_open_state($open);

    wp_send_json_success(array('open' => $open));
}

/**
 * Script + styles for collapsible Import & backup submenu group.
 *
 * @return void
 */
function maca_menulist_enqueue_admin_menu_groups_assets() {
    if (!is_admin() || !maca_menulist_user_can_manage_plugin()) {
        return;
    }

    wp_enqueue_style(
        'maca-menulist-admin',
        MACA_MENULIST_PLUGIN_URL . 'assets/css/admin.css',
        array(),
        MACA_MENULIST_VERSION
    );

    wp_enqueue_script(
        'maca-menulist-admin-menu-groups',
        MACA_MENULIST_PLUGIN_URL . 'assets/js/admin-menu-groups.js',
        array(),
        MACA_MENULIST_VERSION,
        true
    );

    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $current_page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : '';

    wp_localize_script(
        'maca-menulist-admin-menu-groups',
        'macaMenulistAdminMenuGroups',
        array(
            'groupSlug'   => 'maca-restu-group-import-backup',
            'childPages'  => maca_menulist_get_import_backup_submenu_slugs(),
            'storageKey'  => 'maca_menulist_import_group_open',
            'isOpen'      => maca_menulist_import_group_is_open(),
            'currentPage' => $current_page,
            'ajaxUrl'     => admin_url('admin-ajax.php'),
            'nonce'       => wp_create_nonce('maca_menulist_import_group_toggle'),
        )
    );
}

/**
 * Add a collapsible submenu heading row (toggle via admin-menu-groups.js).
 *
 * @param string $parent_slug Parent menu slug.
 * @param string $heading_slug Unique submenu slug for the heading.
 * @param string $label        Visible heading text.
 * @return void
 */
function maca_menulist_add_admin_submenu_heading($parent_slug, $heading_slug, $label) {
    add_submenu_page(
        $parent_slug,
        $label,
        '<span class="maca-menulist-submenu-heading maca-menulist-submenu-heading--toggle">' . esc_html($label) . '</span>',
        maca_menulist_admin_required_cap(),
        $heading_slug,
        'maca_menulist_render_admin_submenu_heading_page'
    );
}

/**
 * Heading submenu callback (should not render; redirect handles direct hits).
 *
 * @return void
 */
function maca_menulist_render_admin_submenu_heading_page() {
    wp_safe_redirect(admin_url('admin.php?page=maca-restu-dashboard'));
    exit;
}

/**
 * Register the Import & backup submenu heading.
 *
 * @return void
 */
function maca_menulist_add_import_backup_submenu_heading() {
    maca_menulist_add_admin_submenu_heading(
        maca_menulist_admin_menu_slug(),
        'maca-restu-group-import-backup',
        __('Import & säkerhetskopiering', 'maca-restu-pro')
    );
}

/**
 * Redirect accidental visits to heading slugs to the first child page.
 *
 * @return void
 */
function maca_menulist_redirect_admin_submenu_heading_pages() {
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : '';

    if ($page !== 'maca-restu-group-import-backup') {
        return;
    }

    $children = maca_menulist_get_import_backup_submenu_slugs();

    if (!empty($children[0])) {
        wp_safe_redirect(admin_url('admin.php?page=' . rawurlencode($children[0])));
        exit;
    }

    wp_safe_redirect(admin_url('admin.php?page=maca-restu-dashboard'));
    exit;
}
