<?php
/**
 * Public personalliggare clock-in page (/stampla/).
 *
 * @package Maca_Menu_List
 */

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

add_action('template_redirect', 'maca_menulist_handle_attendance_page', 0);
add_action('parse_request', 'maca_menulist_parse_request_attendance_route', 0);
add_filter('pre_handle_404', 'maca_menulist_prevent_attendance_route_404', 10, 2);

/**
 * Whether the current request targets the attendance page.
 *
 * @return bool
 */
function maca_menulist_is_attendance_request() {
    if (defined('MACA_MENULIST_ATTENDANCE_PAGE_REQUEST') && MACA_MENULIST_ATTENDANCE_PAGE_REQUEST) {
        return true;
    }

    maca_menulist_bootstrap_attendance_request_query_vars();

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

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

/**
 * Match attendance URL even when rewrite rules are stale.
 *
 * @return bool
 */
function maca_menulist_bootstrap_attendance_request_query_vars() {
    if ((string) get_query_var('maca_attendance') === '1') {
        return false;
    }

    if (!function_exists('maca_menulist_request_path_matches_slug')) {
        return false;
    }

    $path = isset($_SERVER['REQUEST_URI']) ? wp_unslash($_SERVER['REQUEST_URI']) : '';
    $slug = maca_menulist_get_attendance_slug();

    if (maca_menulist_request_path_matches_slug($path, $slug . '/kontroll')) {
        global $wp_query;
        if ($wp_query instanceof WP_Query) {
            set_query_var('maca_attendance', '1');
            set_query_var('maca_attendance_view', 'kontroll');
            $wp_query->is_404 = false;
            $wp_query->is_home = false;
            $wp_query->is_singular = false;
        }

        return true;
    }

    if (!maca_menulist_request_path_matches_slug($path, $slug)) {
        return false;
    }

    global $wp_query;
    if ($wp_query instanceof WP_Query) {
        set_query_var('maca_attendance', '1');
        $wp_query->is_404 = false;
        $wp_query->is_home = false;
        $wp_query->is_singular = false;
    }

    return true;
}

/**
 * Bootstrap attendance route during parse_request.
 *
 * @param WP $wp WordPress environment instance.
 * @return void
 */
function maca_menulist_parse_request_attendance_route($wp) {
    unset($wp);
    maca_menulist_bootstrap_attendance_request_query_vars();
}

/**
 * Prevent theme 404 on attendance URLs.
 *
 * @param bool|null $preempt  Whether to short-circuit 404 handling.
 * @param WP_Query  $wp_query Main query instance.
 * @return bool|null
 */
function maca_menulist_prevent_attendance_route_404($preempt, $wp_query) {
    if ($preempt) {
        return $preempt;
    }

    if ((string) get_query_var('maca_attendance') === '1') {
        if ($wp_query instanceof WP_Query) {
            $wp_query->is_404 = false;
        }

        return true;
    }

    if (maca_menulist_bootstrap_attendance_request_query_vars()) {
        return true;
    }

    return $preempt;
}

/**
 * Render the mobile attendance page.
 *
 * @return void
 */
function maca_menulist_handle_attendance_page() {
    if (!maca_menulist_is_attendance_request()) {
        return;
    }

    if (!defined('MACA_MENULIST_ATTENDANCE_PAGE_REQUEST')) {
        define('MACA_MENULIST_ATTENDANCE_PAGE_REQUEST', true);
    }

    if (!maca_menulist_attendance_enabled()) {
        status_header(200);
        wp_die(
            esc_html(maca_menulist_attendance_ui_string('Personalliggare is disabled.')),
            esc_html(maca_menulist_attendance_ui_string('Personalliggare')),
            array('response' => 200)
        );
    }

    if (maca_menulist_get_attendance_view() === 'kontroll') {
        maca_menulist_render_attendance_control_page();
        exit;
    }

    status_header(200);
    nocache_headers();

    $title = maca_menulist_attendance_ui_string('Personalliggare');
    $feedback = maca_menulist_get_attendance_pin_feedback();
    $rest_url = rest_url('maca-menulist/v1/attendance');
    $css_url = MACA_MENULIST_PLUGIN_URL . 'assets/css/attendance.css?ver=' . MACA_MENULIST_VERSION;
    $js_url = MACA_MENULIST_PLUGIN_URL . 'assets/js/attendance.js?ver=' . MACA_MENULIST_VERSION;

    $config = array(
        'restUrl' => esc_url_raw($rest_url),
        'i18n' => array(
            'enterCode' => maca_menulist_attendance_ui_string('Enter your personal code'),
            'continue' => maca_menulist_attendance_ui_string('Continue'),
            'clockIn' => maca_menulist_attendance_ui_string('Clock in'),
            'clockOut' => maca_menulist_attendance_ui_string('Clock out'),
            'switchUser' => maca_menulist_attendance_ui_string('Use another code'),
            'notClockedIn' => maca_menulist_attendance_ui_string('Not clocked in'),
            'clockedInSince' => maca_menulist_attendance_ui_string('Clocked in since %s'),
            'clockedOutAt' => maca_menulist_attendance_ui_string('Last clock out: %s'),
            'errorGeneric' => maca_menulist_attendance_ui_string('Something went wrong. Try again.'),
            'pinLocked' => maca_menulist_attendance_ui_string('PIN locked. Try again later.'),
        ),
        'pinFeedback' => $feedback,
    );

    // phpcs:disable WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet, WordPress.WP.EnqueuedResources.NonEnqueuedScript, WordPress.Security.EscapeOutput.OutputNotEscaped
    echo '<!DOCTYPE html>
<html lang="' . esc_attr(maca_menulist_attendance_html_lang()) . '">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-title" content="' . esc_attr($title) . '">
    <meta name="theme-color" content="#1a4d3e">
    <title>' . esc_html($title) . '</title>
    <link rel="stylesheet" href="' . esc_url($css_url) . '">
</head>
<body class="maca-attendance-page">
    <div id="maca-attendance-app" class="maca-attendance-app">
        <header class="maca-attendance-header">
            <h1>' . esc_html($title) . '</h1>
            <p class="maca-attendance-subtitle">' . esc_html(maca_menulist_attendance_ui_string('Enter your own personal code only. You cannot stamp in or out for someone else.')) . '</p>
        </header>

        <section id="maca-attendance-pin" class="maca-attendance-panel">
            <label for="maca-attendance-pin-input">' . esc_html(maca_menulist_attendance_ui_string('Your personal code')) . '</label>
            <input type="password" id="maca-attendance-pin-input" class="maca-attendance-pin-input" inputmode="numeric" autocomplete="off" maxlength="8" placeholder="••••">
            <p id="maca-attendance-pin-info" class="maca-attendance-pin-info">' . esc_html(
                $feedback['is_locked']
                    ? sprintf(
                        /* translators: %d: lockout minutes remaining */
                        maca_menulist_attendance_ui_string('PIN locked. Try again in %d min.'),
                        max(1, (int) ceil($feedback['locked_seconds_remaining'] / 60))
                    )
                    : sprintf(
                        /* translators: 1: attempts left, 2: max attempts */
                        maca_menulist_attendance_ui_string('Attempts left: %1$d of %2$d'),
                        (int) $feedback['attempts_left'],
                        (int) $feedback['max_attempts']
                    )
            ) . '</p>
            <button type="button" id="maca-attendance-pin-submit" class="maca-attendance-btn maca-attendance-btn--primary">' . esc_html(maca_menulist_attendance_ui_string('Continue')) . '</button>
            <p id="maca-attendance-pin-error" class="maca-attendance-error" hidden></p>
        </section>

        <section id="maca-attendance-clock" class="maca-attendance-panel" hidden>
            <p id="maca-attendance-employee-name" class="maca-attendance-employee-name"></p>
            <p id="maca-attendance-status" class="maca-attendance-status"></p>
            <button type="button" id="maca-attendance-clock-in" class="maca-attendance-btn maca-attendance-btn--primary">' . esc_html(maca_menulist_attendance_ui_string('Clock in')) . '</button>
            <button type="button" id="maca-attendance-clock-out" class="maca-attendance-btn maca-attendance-btn--secondary">' . esc_html(maca_menulist_attendance_ui_string('Clock out')) . '</button>
            <button type="button" id="maca-attendance-logout" class="maca-attendance-btn maca-attendance-btn--ghost">' . esc_html(maca_menulist_attendance_ui_string('Use another code')) . '</button>
            <p id="maca-attendance-clock-message" class="maca-attendance-message" hidden></p>
        </section>
    </div>
    <script>window.macaMenulistAttendance = ' . wp_json_encode($config) . ';</script>
    <script src="' . esc_url($js_url) . '"></script>
</body>
</html>';
    // phpcs:enable WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet, WordPress.WP.EnqueuedResources.NonEnqueuedScript, WordPress.Security.EscapeOutput.OutputNotEscaped

    exit;
}

/**
 * Render in-venue control view for Skatteverket inspections.
 *
 * @return void
 */
function maca_menulist_render_attendance_control_page() {
    status_header(200);
    nocache_headers();

    $title = maca_menulist_attendance_ui_string('Personalliggare — control view');
    $rest_url = rest_url('maca-menulist/v1/attendance');
    $css_url = MACA_MENULIST_PLUGIN_URL . 'assets/css/attendance.css?ver=' . MACA_MENULIST_VERSION;
    $js_url = MACA_MENULIST_PLUGIN_URL . 'assets/js/attendance-control.js?ver=' . MACA_MENULIST_VERSION;
    $today = function_exists('maca_menulist_wp_today') ? maca_menulist_wp_today() : wp_date('Y-m-d');
    $staff_pin_set = function_exists('maca_menulist_get_table_order_staff_pin')
        && maca_menulist_get_table_order_staff_pin() !== '';
    $pin_feedback = function_exists('maca_menulist_get_staff_pin_attempt_feedback')
        ? maca_menulist_get_staff_pin_attempt_feedback()
        : array('is_locked' => false, 'attempts_left' => 5, 'max_attempts' => 5, 'locked_seconds_remaining' => 0);

    $config = array(
        'restUrl' => esc_url_raw($rest_url),
        'today' => $today,
        'i18n' => array(
            'enterStaffPin' => maca_menulist_attendance_ui_string('Enter staff PIN'),
            'clockedIn' => maca_menulist_attendance_ui_string('Clocked in'),
            'clockedOut' => maca_menulist_attendance_ui_string('Not clocked in'),
            'noActivity' => maca_menulist_attendance_ui_string('No activity'),
            'noEmployees' => maca_menulist_attendance_ui_string('No employees registered.'),
            'errorGeneric' => maca_menulist_attendance_ui_string('Something went wrong. Try again.'),
        ),
    );

    // phpcs:disable WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet, WordPress.WP.EnqueuedResources.NonEnqueuedScript, WordPress.Security.EscapeOutput.OutputNotEscaped
    echo '<!DOCTYPE html>
<html lang="' . esc_attr(maca_menulist_attendance_html_lang()) . '">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <meta name="robots" content="noindex,nofollow">
    <title>' . esc_html($title) . '</title>
    <link rel="stylesheet" href="' . esc_url($css_url) . '">
</head>
<body class="maca-attendance-page maca-attendance-page--control">
    <div id="maca-attendance-control-app" class="maca-attendance-app maca-attendance-app--wide">
        <header class="maca-attendance-header maca-attendance-header--control">
            <h1>' . esc_html($title) . '</h1>
            <p class="maca-attendance-subtitle">' . esc_html(maca_menulist_attendance_ui_string('For in-venue inspection. Personal identity numbers are not shown here.')) . '</p>
        </header>';

    if (!$staff_pin_set) {
        echo '<section class="maca-attendance-panel"><p class="maca-attendance-error">' . esc_html(maca_menulist_attendance_ui_string('Staff PIN is not configured. Set it in maca Restu settings.')) . '</p></section>';
    } else {
        echo '
        <section id="maca-attendance-control-pin" class="maca-attendance-panel">
            <label for="maca-attendance-control-pin-input">' . esc_html(maca_menulist_attendance_ui_string('Staff PIN')) . '</label>
            <input type="password" id="maca-attendance-control-pin-input" class="maca-attendance-pin-input" inputmode="numeric" autocomplete="off">
            <p class="maca-attendance-pin-info">' . esc_html(
                !empty($pin_feedback['is_locked'])
                    ? sprintf(
                        /* translators: %d: lockout minutes remaining */
                        maca_menulist_attendance_ui_string('PIN locked. Try again in %d min.'),
                        max(1, (int) ceil((int) ($pin_feedback['locked_seconds_remaining'] ?? 0) / 60))
                    )
                    : sprintf(
                        /* translators: 1: attempts left, 2: max attempts */
                        maca_menulist_attendance_ui_string('Attempts left: %1$d of %2$d'),
                        (int) ($pin_feedback['attempts_left'] ?? 0),
                        (int) ($pin_feedback['max_attempts'] ?? 5)
                    )
            ) . '</p>
            <button type="button" id="maca-attendance-control-pin-submit" class="maca-attendance-btn maca-attendance-btn--primary">' . esc_html(maca_menulist_attendance_ui_string('Show register')) . '</button>
            <p id="maca-attendance-control-pin-error" class="maca-attendance-error" hidden></p>
        </section>

        <section id="maca-attendance-control-report" class="maca-attendance-panel" hidden>
            <div class="maca-attendance-control-toolbar no-print">
                <label for="maca-attendance-control-date">' . esc_html(maca_menulist_attendance_ui_string('Date')) . '</label>
                <input type="date" id="maca-attendance-control-date" value="' . esc_attr($today) . '">
                <button type="button" id="maca-attendance-control-today" class="maca-attendance-btn maca-attendance-btn--ghost">' . esc_html(maca_menulist_attendance_ui_string('Today')) . '</button>
                <button type="button" id="maca-attendance-control-refresh" class="maca-attendance-btn maca-attendance-btn--ghost">' . esc_html(maca_menulist_attendance_ui_string('Refresh')) . '</button>
                <button type="button" id="maca-attendance-control-print" class="maca-attendance-btn maca-attendance-btn--secondary">' . esc_html(maca_menulist_attendance_ui_string('Print')) . '</button>
                <button type="button" id="maca-attendance-control-logout" class="maca-attendance-btn maca-attendance-btn--ghost">' . esc_html(maca_menulist_attendance_ui_string('Lock')) . '</button>
            </div>
            <h2 id="maca-attendance-control-date-label" class="maca-attendance-report-title"></h2>
            <table class="maca-attendance-control-table">
                <thead>
                    <tr>
                        <th>' . esc_html(maca_menulist_attendance_ui_string('Name')) . '</th>
                        <th>' . esc_html(maca_menulist_attendance_ui_string('In')) . '</th>
                        <th>' . esc_html(maca_menulist_attendance_ui_string('Out')) . '</th>
                        <th>' . esc_html(maca_menulist_attendance_ui_string('Status')) . '</th>
                    </tr>
                </thead>
                <tbody id="maca-attendance-control-tbody"></tbody>
            </table>
            <p id="maca-attendance-control-report-error" class="maca-attendance-error" hidden></p>
        </section>';
    }

    echo '
    </div>
    <script>window.macaMenulistAttendanceControl = ' . wp_json_encode($config) . ';</script>
    <script src="' . esc_url($js_url) . '"></script>
</body>
</html>';
    // phpcs:enable WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet, WordPress.WP.EnqueuedResources.NonEnqueuedScript, WordPress.Security.EscapeOutput.OutputNotEscaped
}
