<?php
/**
 * Terms of use and privacy policy acceptance for maca Restu Pro.
 *
 * @package Maca_Menu_List_Pro
 */

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

define('MACA_MENULIST_LEGAL_TERMS_VERSION', '1.7');
define('MACA_MENULIST_LEGAL_PRIVACY_VERSION', '1.6');
define('MACA_MENULIST_LEGAL_OPTION', 'maca_menulist_legal_acceptance');
define('MACA_MENULIST_LEGAL_REDIRECT_TRANSIENT', 'maca_menulist_legal_redirect');

/**
 * Run on plugin activation — prompt admin to accept legal documents.
 */
function maca_menulist_legal_on_activate() {
    set_transient(MACA_MENULIST_LEGAL_REDIRECT_TRANSIENT, '1', MINUTE_IN_SECONDS);
}

/**
 * Whether legal acceptance is required for this install.
 *
 * @return bool
 */
function maca_menulist_legal_is_required() {
    return defined('MACA_MENULIST_PRO') && MACA_MENULIST_PRO;
}

/**
 * Stored acceptance record.
 *
 * @return array<string, mixed>
 */
function maca_menulist_legal_get_acceptance() {
    $stored = get_option(MACA_MENULIST_LEGAL_OPTION, array());
    return is_array($stored) ? $stored : array();
}

/**
 * Whether current legal document versions are accepted.
 *
 * @return bool
 */
function maca_menulist_legal_is_accepted() {
    if (!maca_menulist_legal_is_required()) {
        return true;
    }

    $stored = maca_menulist_legal_get_acceptance();
    if (empty($stored['terms_version']) || empty($stored['privacy_version'])) {
        return false;
    }

    return $stored['terms_version'] === MACA_MENULIST_LEGAL_TERMS_VERSION
        && $stored['privacy_version'] === MACA_MENULIST_LEGAL_PRIVACY_VERSION;
}

/**
 * Whether the plugin frontend should stay disabled.
 *
 * @return bool
 */
function maca_menulist_legal_blocks_frontend() {
    return maca_menulist_legal_is_required() && !maca_menulist_legal_is_accepted();
}

/**
 * Locale suffix for legal documents.
 *
 * @return string
 */
function maca_menulist_legal_get_locale_suffix() {
    $locale = function_exists('get_user_locale') ? get_user_locale() : get_locale();
    $lang = substr((string) $locale, 0, 2);

    return ($lang === 'sv') ? 'sv' : 'en';
}

/**
 * Absolute path to a legal markdown document.
 *
 * @param string $type terms|privacy
 * @return string
 */
function maca_menulist_legal_get_document_path($type) {
    $type = strtolower((string) $type);
    $suffix = maca_menulist_legal_get_locale_suffix();
    $basename = ($type === 'privacy') ? 'PRIVACY' : 'TERMS';
    $path = MACA_MENULIST_PLUGIN_DIR . 'docs/legal/' . $basename . '-' . $suffix . '.md';

    if (!file_exists($path)) {
        $path = MACA_MENULIST_PLUGIN_DIR . 'docs/legal/' . $basename . '-en.md';
    }

    return $path;
}

/**
 * Save acceptance after admin confirmation.
 *
 * @param int $user_id Accepting user ID.
 * @return bool
 */
function maca_menulist_legal_save_acceptance($user_id) {
    $user_id = absint($user_id);
    if ($user_id <= 0) {
        return false;
    }

    $user = get_userdata($user_id);
    if (!$user) {
        return false;
    }

    $record = array(
        'terms_version'   => MACA_MENULIST_LEGAL_TERMS_VERSION,
        'privacy_version' => MACA_MENULIST_LEGAL_PRIVACY_VERSION,
        'accepted_at'     => maca_menulist_wp_now_mysql(),
        'accepted_at_gmt' => current_time('mysql', true),
        'user_id'         => $user_id,
        'user_login'      => $user->user_login,
        'plugin_version'  => MACA_MENULIST_VERSION,
    );

    return update_option(MACA_MENULIST_LEGAL_OPTION, $record, false);
}

/**
 * Admin URL for the legal page.
 *
 * @param string $tab Optional tab: terms|privacy
 * @return string
 */
function maca_menulist_legal_get_admin_url($tab = 'terms') {
    $tab = ($tab === 'privacy') ? 'privacy' : 'terms';

    return add_query_arg(
        array(
            'page' => 'maca-restu-legal',
            'tab'  => $tab,
        ),
        admin_url('admin.php')
    );
}

/**
 * Message shown on the frontend when legal acceptance is pending.
 *
 * @return string
 */
function maca_menulist_legal_frontend_blocked_message() {
    if (!maca_menulist_legal_blocks_frontend()) {
        return '';
    }

    if (maca_menulist_user_can_manage_plugin()) {
        $url = maca_menulist_legal_get_admin_url();

        return '<p class="maca-menulist-legal-blocked">' . sprintf(
            wp_kses(
                /* translators: %s: admin legal page URL */
                __('maca Restu Pro is paused until you accept the <a href="%s">Terms and Privacy Policy</a> in wp-admin.', 'maca-restu-pro'),
                array('a' => array('href' => true))
            ),
            esc_url($url)
        ) . '</p>';
    }

    return '<p class="maca-menulist-legal-blocked">' . esc_html__('The menu is temporarily unavailable.', 'maca-restu-pro') . '</p>';
}

/**
 * Output a minimal blocked QR page and exit.
 */
function maca_menulist_legal_render_blocked_page() {
    status_header(200);
    nocache_headers();

    $message = maca_menulist_legal_frontend_blocked_message();
    $title = esc_html__('Menu unavailable', 'maca-restu-pro');

    echo '<!DOCTYPE html><html lang="' . esc_attr(get_bloginfo('language')) . '"><head>';
    echo '<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">';
    echo '<title>' . esc_html($title) . '</title>';
    echo '<style>body{font-family:system-ui,sans-serif;margin:2rem;line-height:1.5;color:#1d2327}</style>';
    echo '</head><body>';
    echo wp_kses_post($message);
    echo '</body></html>';
    exit;
}
