<?php
/**
 * Previous / next / close navigation on admin record edit screens.
 *
 * @package Maca_Menu_List
 */

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

/**
 * Build an admin edit URL for a record.
 *
 * @param string $page      Admin page slug.
 * @param string $id_param  Query parameter name for the record ID.
 * @param int    $record_id Record ID.
 * @return string
 */
function maca_menulist_build_admin_edit_url($page, $id_param, $record_id) {
    return admin_url(
        'admin.php?page=' . rawurlencode($page)
        . '&action=edit&'
        . rawurlencode($id_param) . '='
        . (int) $record_id
    );
}

/**
 * Find previous and next record IDs in list order.
 *
 * @param array<int, object|array<string, mixed>> $records   Records with an id field.
 * @param int                                     $current_id Current record ID.
 * @return array{prev: int|null, next: int|null, current: int, total: int}
 */
function maca_menulist_get_admin_record_neighbors($records, $current_id) {
    $ids = array();

    foreach ($records as $record) {
        $id = is_object($record) ? (int) $record->id : (int) ($record['id'] ?? 0);
        if ($id > 0) {
            $ids[] = $id;
        }
    }

    $current_id = (int) $current_id;
    $index = array_search($current_id, $ids, true);

    return array(
        'prev' => ($index !== false && $index > 0) ? $ids[$index - 1] : null,
        'next' => ($index !== false && $index < count($ids) - 1) ? $ids[$index + 1] : null,
        'current' => ($index !== false) ? $index + 1 : 0,
        'total' => count($ids),
    );
}

/**
 * Render previous, next, and close navigation for admin edit forms.
 *
 * @param array<string, mixed> $args {
 *     @type string $action      add|edit
 *     @type int    $current_id  Current record ID (edit only).
 *     @type array  $records     All records in list order.
 *     @type string $list_url    URL back to the list view.
 *     @type string $edit_page   Admin page slug for edit links.
 *     @type string $edit_id_param Query parameter for record ID.
 *     @type bool   $show_position Whether to show "2 / 8" counter.
 * }
 * @return void
 */
function maca_menulist_render_admin_record_navigation($args) {
    $args = wp_parse_args(
        is_array($args) ? $args : array(),
        array(
            'action' => 'edit',
            'current_id' => 0,
            'records' => array(),
            'list_url' => '',
            'edit_page' => '',
            'edit_id_param' => 'id',
            'show_position' => true,
        )
    );

    static $styles_printed = false;

    if (!$styles_printed) {
        $styles_printed = true;
        echo '<style>
            .maca-admin-record-nav {
                display: flex;
                flex-wrap: wrap;
                align-items: center;
                gap: 8px;
                margin: 0 0 16px;
                padding: 10px 12px;
                background: #fff;
                border: 1px solid #c3c4c7;
                border-radius: 4px;
            }
            .maca-admin-record-nav--bottom {
                margin: 16px 0 0;
            }
            .maca-admin-record-nav .maca-admin-record-nav-spacer {
                flex: 1 1 auto;
                min-width: 8px;
            }
            .maca-admin-record-nav .maca-admin-record-nav-position {
                font-size: 13px;
                color: #646970;
                white-space: nowrap;
            }
            .maca-admin-record-nav .button[disabled] {
                pointer-events: none;
                opacity: 0.55;
            }
        </style>';
    }

    $action = sanitize_key($args['action']);
    $current_id = (int) $args['current_id'];
    $list_url = esc_url($args['list_url']);
    $edit_page = sanitize_key($args['edit_page']);
    $edit_id_param = sanitize_key($args['edit_id_param']);
    $show_position = !empty($args['show_position']);
    $is_edit = ($action === 'edit' && $current_id > 0);

    $neighbors = array(
        'prev' => null,
        'next' => null,
        'current' => 0,
        'total' => 0,
    );

    if ($is_edit && !empty($args['records'])) {
        $neighbors = maca_menulist_get_admin_record_neighbors($args['records'], $current_id);
    }

    $modifier = !empty($args['modifier']) ? ' maca-admin-record-nav--' . sanitize_html_class($args['modifier']) : '';

    echo '<div class="maca-admin-record-nav' . esc_attr($modifier) . '" role="navigation" aria-label="' . esc_attr__('Record navigation', 'maca-restu-pro') . '">';

    if ($is_edit) {
        if ($neighbors['prev'] !== null && $edit_page !== '' && $edit_id_param !== '') {
            echo '<a href="' . esc_url(maca_menulist_build_admin_edit_url($edit_page, $edit_id_param, $neighbors['prev'])) . '" class="button maca-admin-record-nav-link">';
            echo esc_html__('Previous', 'maca-restu-pro');
            echo '</a>';
        } else {
            echo '<span class="button" disabled aria-hidden="true">' . esc_html__('Previous', 'maca-restu-pro') . '</span>';
        }

        if ($show_position && $neighbors['total'] > 0) {
            echo '<span class="maca-admin-record-nav-position">';
            echo esc_html(
                sprintf(
                    /* translators: 1: current item number, 2: total items */
                    __('%1$d of %2$d', 'maca-restu-pro'),
                    $neighbors['current'],
                    $neighbors['total']
                )
            );
            echo '</span>';
        }

        echo '<span class="maca-admin-record-nav-spacer" aria-hidden="true"></span>';

        if ($neighbors['next'] !== null && $edit_page !== '' && $edit_id_param !== '') {
            echo '<a href="' . esc_url(maca_menulist_build_admin_edit_url($edit_page, $edit_id_param, $neighbors['next'])) . '" class="button maca-admin-record-nav-link">';
            echo esc_html__('Next', 'maca-restu-pro');
            echo '</a>';
        } else {
            echo '<span class="button" disabled aria-hidden="true">' . esc_html__('Next', 'maca-restu-pro') . '</span>';
        }
    }

    if ($list_url !== '') {
        if (!$is_edit) {
            echo '<span class="maca-admin-record-nav-spacer" aria-hidden="true"></span>';
        }
        echo '<a href="' . esc_url($list_url) . '" class="button maca-admin-record-nav-link">' . esc_html__('Close', 'maca-restu-pro') . '</a>';
    }

    echo '</div>';
}
