<?php
/**
 * Public read-only management overview (chef) — slug, PIN, and request helpers.
 *
 * @package Maca_MenuList
 */

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

/**
 * Whether the public management overview feature is available.
 *
 * @return bool
 */
function maca_menulist_management_overview_enabled() {
    return function_exists('maca_menulist_pro_has_feature')
        && maca_menulist_pro_has_feature('public_overview');
}

/**
 * URL slug for the public management overview page.
 *
 * @return string
 */
function maca_menulist_get_management_overview_slug() {
    $slug = get_option('maca_menulist_management_overview_slug', 'chef-oversikt');
    $slug = sanitize_title($slug);

    if ($slug === '') {
        $slug = 'chef-oversikt';
    }

    return $slug;
}

/**
 * Full URL for the public management overview page.
 *
 * @return string
 */
function maca_menulist_get_management_overview_url() {
    return home_url('/' . maca_menulist_get_management_overview_slug() . '/');
}

/**
 * Stored management overview PIN (hashed or legacy plain).
 *
 * @return string
 */
function maca_menulist_get_management_overview_pin() {
    $pin = get_option('maca_menulist_management_overview_pin', '');

    return is_string($pin) ? $pin : '';
}

/**
 * Hash a management overview PIN for storage.
 *
 * @param string $pin Plain text PIN.
 * @return string
 */
function maca_menulist_hash_management_overview_pin($pin) {
    $pin = (string) $pin;
    if ($pin === '') {
        return '';
    }

    return wp_hash_password($pin);
}

/**
 * Lockout transient key for management overview PIN attempts.
 *
 * @return string
 */
function maca_menulist_management_pin_lock_key() {
    $ip = isset($_SERVER['REMOTE_ADDR']) ? sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR'])) : 'unknown';
    $ua = isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : 'unknown';
    $fingerprint = strtolower(trim($ip . '|' . $ua));

    return 'maca_mgmt_pin_lock_' . md5($fingerprint);
}

/**
 * Failed-attempt state for management overview PIN lockout.
 *
 * @return array{count:int,locked_until:int}
 */
function maca_menulist_get_management_pin_lock_state() {
    $state = get_transient(maca_menulist_management_pin_lock_key());
    if (!is_array($state)) {
        return array('count' => 0, 'locked_until' => 0);
    }

    return array(
        'count' => isset($state['count']) ? (int) $state['count'] : 0,
        'locked_until' => isset($state['locked_until']) ? (int) $state['locked_until'] : 0,
    );
}

/**
 * Register a failed management overview PIN attempt.
 *
 * @return void
 */
function maca_menulist_register_management_pin_failed_attempt() {
    $state = maca_menulist_get_management_pin_lock_state();
    $count = (int) $state['count'] + 1;
    $lock_after = 10;
    $lock_seconds = 10 * MINUTE_IN_SECONDS;
    $locked_until = 0;

    if ($count >= $lock_after) {
        $locked_until = time() + $lock_seconds;
    }

    set_transient(
        maca_menulist_management_pin_lock_key(),
        array(
            'count' => $count,
            'locked_until' => $locked_until,
        ),
        $lock_seconds
    );
}

/**
 * PIN-attempt feedback for the public management overview page.
 *
 * @return array{is_locked:bool,attempts_used:int,attempts_left:int,max_attempts:int,locked_seconds_remaining:int}
 */
function maca_menulist_get_management_pin_attempt_feedback() {
    $state = maca_menulist_get_management_pin_lock_state();
    $max_attempts = 10;
    $attempts_used = max(0, (int) $state['count']);
    $attempts_left = max(0, $max_attempts - $attempts_used);
    $locked_seconds_remaining = max(0, (int) $state['locked_until'] - time());

    return array(
        'is_locked' => $locked_seconds_remaining > 0,
        'attempts_used' => $attempts_used,
        'attempts_left' => $attempts_left,
        'max_attempts' => $max_attempts,
        'locked_seconds_remaining' => $locked_seconds_remaining,
    );
}

/**
 * Clear failed management PIN attempts after success.
 *
 * @return void
 */
function maca_menulist_clear_management_pin_failed_attempts() {
    delete_transient(maca_menulist_management_pin_lock_key());
}

/**
 * Whether management PIN verification is locked.
 *
 * @return bool
 */
function maca_menulist_is_management_pin_locked() {
    $state = maca_menulist_get_management_pin_lock_state();

    return (int) $state['locked_until'] > time();
}

/**
 * Verify management overview PIN.
 *
 * @param string $pin Submitted PIN.
 * @return bool
 */
function maca_menulist_verify_management_overview_pin($pin) {
    if (maca_menulist_is_management_pin_locked()) {
        return false;
    }

    $submitted = trim((string) $pin);
    $expected = maca_menulist_get_management_overview_pin();

    if ($expected === '') {
        maca_menulist_register_management_pin_failed_attempt();
        return false;
    }

    $valid = false;
    if (maca_menulist_table_order_staff_pin_is_hashed($expected)) {
        $valid = wp_check_password($submitted, $expected);
    } else {
        $valid = hash_equals($expected, $submitted);
        if ($valid) {
            update_option('maca_menulist_management_overview_pin', maca_menulist_hash_management_overview_pin($submitted), false);
        }
    }

    if ($valid) {
        maca_menulist_clear_management_pin_failed_attempts();
        return true;
    }

    maca_menulist_register_management_pin_failed_attempt();

    return false;
}

/**
 * Whether the current request targets the public management overview page.
 *
 * @return bool
 */
function maca_menulist_is_management_overview_request() {
    maca_menulist_bootstrap_management_overview_query_var();

    // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Public routing.
    if (isset($_GET['maca_management_overview']) && sanitize_text_field(wp_unslash($_GET['maca_management_overview'])) === '1') {
        // phpcs:enable WordPress.Security.NonceVerification.Recommended
        return true;
    }
    // phpcs:enable WordPress.Security.NonceVerification.Recommended

    return (string) get_query_var('maca_management_overview') === '1';
}

/**
 * Bootstrap management overview query var from request path (stale rewrites).
 *
 * @return bool
 */
function maca_menulist_bootstrap_management_overview_query_var() {
    if ((string) get_query_var('maca_management_overview') === '1') {
        return false;
    }

    $path = maca_menulist_get_request_path();
    if ($path === '' || $path !== maca_menulist_get_management_overview_slug()) {
        return false;
    }

    set_query_var('maca_management_overview', '1');

    global $wp_query;
    if ($wp_query instanceof WP_Query) {
        $wp_query->set('maca_management_overview', '1');
        $wp_query->is_404 = false;
    }

    return true;
}

/**
 * Strip admin URLs and write affordances from dashboard payloads for public read-only use.
 *
 * @param array<string, mixed> $payload Dashboard payload.
 * @return array<string, mixed>
 */
function maca_menulist_sanitize_dashboard_payload_readonly($payload) {
    if (!is_array($payload)) {
        return array();
    }

    if (!empty($payload['metrics']['campaign']) && is_array($payload['metrics']['campaign'])) {
        unset($payload['metrics']['campaign']['url']);
    }

    if (!empty($payload['actions']) && is_array($payload['actions'])) {
        foreach ($payload['actions'] as $index => $item) {
            if (is_array($item)) {
                unset($payload['actions'][$index]['url']);
            }
        }
    }

    if (!empty($payload['history']) && is_array($payload['history'])) {
        unset($payload['history']['stats_url']);

        if (!empty($payload['history']['top_dishes']) && is_array($payload['history']['top_dishes'])) {
            foreach ($payload['history']['top_dishes'] as $index => $dish) {
                if (is_array($dish)) {
                    unset($payload['history']['top_dishes'][$index]['edit_url']);
                }
            }
        }
    }

    return $payload;
}
