<?php
/**
 * Personal — unified admin for staff (personalliggare, waiters, screens).
 *
 * @package Maca_Menu_List
 */

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

require_once __DIR__ . '/admin-personal-i18n.php';

/**
 * Admin page slug for Personal.
 *
 * @return string
 */
function maca_menulist_personal_admin_page() {
    return 'maca-restu-personal';
}

/**
 * Whether the current admin request targets Personal.
 *
 * @return bool
 */
function maca_menulist_is_personal_admin_request() {
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    if (!isset($_GET['page'])) {
        return false;
    }

    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    return sanitize_key(wp_unslash($_GET['page'])) === maca_menulist_personal_admin_page();
}

/**
 * Personal admin tab definitions.
 *
 * @return array<string, array{label: string, visible: bool}>
 */
function maca_menulist_get_personal_admin_tabs() {
    $tabs = array(
        'employees' => array(
            'label'   => __('Employees', 'maca-restu-pro'),
            'visible' => true,
        ),
        'report' => array(
            'label'   => __('Report', 'maca-restu-pro'),
            'visible' => true,
        ),
        'archive' => array(
            'label'   => __('Monthly archive', 'maca-restu-pro'),
            'visible' => true,
        ),
        'log' => array(
            'label'   => __('Change log', 'maca-restu-pro'),
            'visible' => true,
        ),
        'waiters' => array(
            'label'   => __('Waiters', 'maca-restu-pro'),
            'visible' => function_exists('maca_menulist_waiters_feature_available')
                && maca_menulist_waiters_feature_available(),
        ),
        'screens' => array(
            'label'   => __('Staff screens', 'maca-restu-pro'),
            'visible' => true,
        ),
    );

    /**
     * Filter Personal admin tabs.
     *
     * @param array<string, array{label: string, visible: bool}> $tabs Tab definitions.
     */
    return apply_filters('maca_menulist_personal_admin_tabs', $tabs);
}

/**
 * Active Personal admin tab.
 *
 * @return string
 */
function maca_menulist_get_active_personal_admin_tab() {
    $tabs = maca_menulist_get_personal_admin_tabs();
    $ids = array_keys($tabs);

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

    if ($tab === '' || !isset($tabs[ $tab ]) || empty($tabs[ $tab ]['visible'])) {
        return 'employees';
    }

    return in_array($tab, $ids, true) ? $tab : 'employees';
}

/**
 * Build Personal admin URL.
 *
 * @param array<string, string|int> $args Query args.
 * @return string
 */
function maca_menulist_personal_admin_url($args = array()) {
    return add_query_arg(
        array_merge(
            array('page' => maca_menulist_personal_admin_page()),
            $args
        ),
        admin_url('admin.php')
    );
}

/**
 * Render Personal tab navigation.
 *
 * @param string $active_tab Active tab slug.
 * @return void
 */
function maca_menulist_render_personal_admin_tab_nav($active_tab) {
    ?>
    <nav class="nav-tab-wrapper maca-personal-tabs">
        <?php foreach (maca_menulist_get_personal_admin_tabs() as $tab_id => $tab_def) : ?>
            <?php
            if (empty($tab_def['visible'])) {
                continue;
            }
            $classes = 'nav-tab';
            if ($active_tab === $tab_id) {
                $classes .= ' nav-tab-active';
            }
            ?>
            <a href="<?php echo esc_url(maca_menulist_personal_admin_url(array('tab' => $tab_id))); ?>"
               class="<?php echo esc_attr($classes); ?>">
                <?php echo esc_html((string) $tab_def['label']); ?>
            </a>
        <?php endforeach; ?>
    </nav>
    <?php
}

/**
 * Redirect legacy staff admin URLs to Personal tabs.
 *
 * @return void
 */
function maca_menulist_personal_legacy_admin_redirects() {
    if (!is_admin()) {
        return;
    }

    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    if (!isset($_GET['page'])) {
        return;
    }

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

    if ($page === 'maca-restu-attendance') {
        $args = array('page' => maca_menulist_personal_admin_page());
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if (isset($_GET['tab'])) {
            $args['tab'] = sanitize_key(wp_unslash($_GET['tab']));
        } else {
            $args['tab'] = 'employees';
        }

        foreach (array('employee_id', 'date_from', 'date_to', 'only_activity', 'correct_employee_id', 'correct_date', 'employee_saved', 'pin_reset') as $key) {
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            if (isset($_GET[ $key ])) {
                $args[ $key ] = sanitize_text_field(wp_unslash($_GET[ $key ]));
            }
        }

        wp_safe_redirect(maca_menulist_personal_admin_url($args));
        exit;
    }

    if ($page === 'maca-restu-waiters') {
        $args = array(
            'page' => maca_menulist_personal_admin_page(),
            'tab'  => 'waiters',
        );

        foreach (array('action', 'waiter_id') as $key) {
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            if (isset($_GET[ $key ])) {
                $args[ $key ] = sanitize_text_field(wp_unslash($_GET[ $key ]));
            }
        }

        wp_safe_redirect(maca_menulist_personal_admin_url($args));
        exit;
    }
}

/**
 * Save staff screen settings from Personal tab.
 *
 * @return void
 */
function maca_menulist_save_personal_screen_settings() {
    if (!maca_menulist_user_can_manage_plugin()) {
        return;
    }

    $table_order_staff_pin = isset($_POST['maca_table_order_staff_pin'])
        ? wp_unslash($_POST['maca_table_order_staff_pin'])
        : '';
    $table_order_staff_pin = is_string($table_order_staff_pin) ? trim($table_order_staff_pin) : '';

    $waiter_order_slug = isset($_POST['maca_waiter_order_slug'])
        ? sanitize_title(wp_unslash($_POST['maca_waiter_order_slug']))
        : 'meny-servitris';
    $kitchen_order_slug = isset($_POST['maca_kitchen_order_slug'])
        ? sanitize_title(wp_unslash($_POST['maca_kitchen_order_slug']))
        : 'meny-kok';
    $attendance_slug = isset($_POST['maca_attendance_slug'])
        ? sanitize_title(wp_unslash($_POST['maca_attendance_slug']))
        : 'stampla';

    if ($waiter_order_slug === '') {
        $waiter_order_slug = 'meny-servitris';
    }
    if ($kitchen_order_slug === '') {
        $kitchen_order_slug = 'meny-kok';
    }
    if ($attendance_slug === '') {
        $attendance_slug = 'stampla';
    }

    $previous_waiter_slug = get_option('maca_menulist_waiter_order_slug', 'meny-servitris');
    $previous_kitchen_slug = get_option('maca_menulist_kitchen_order_slug', 'meny-kok');
    $previous_attendance_slug = get_option('maca_menulist_attendance_slug', 'stampla');

    if (maca_menulist_admin_secret_should_update($table_order_staff_pin)) {
        update_option('maca_menulist_table_order_staff_pin', maca_menulist_hash_table_order_staff_pin($table_order_staff_pin), false);
        if (function_exists('maca_menulist_bump_table_order_staff_pin_revision')) {
            maca_menulist_bump_table_order_staff_pin_revision();
        }
        if (function_exists('maca_menulist_clear_all_staff_pin_lockouts')) {
            maca_menulist_clear_all_staff_pin_lockouts();
        } elseif (function_exists('maca_menulist_clear_staff_pin_failed_attempts')) {
            maca_menulist_clear_staff_pin_failed_attempts();
        }
        wp_cache_delete('maca_menulist_table_order_staff_pin', 'options');
    }

    update_option('maca_menulist_waiter_order_slug', $waiter_order_slug);
    update_option('maca_menulist_kitchen_order_slug', $kitchen_order_slug);
    update_option('maca_menulist_attendance_slug', $attendance_slug);
    update_option(
        'maca_menulist_attendance_enabled',
        !empty($_POST['maca_attendance_enabled']) ? '1' : '0'
    );

    if (
        $waiter_order_slug !== $previous_waiter_slug
        || $kitchen_order_slug !== $previous_kitchen_slug
        || $attendance_slug !== $previous_attendance_slug
    ) {
        update_option('maca_menulist_flush_rewrite', '1');
    }

    add_settings_error(
        'maca_personal',
        'screens_saved',
        __('Staff screen settings saved.', 'maca-restu-pro'),
        'success'
    );
}

/**
 * Personal admin screen host.
 */
class Maca_MenuList_Admin_Personal {

    /**
     * @var Maca_MenuList_Admin_Attendance|null
     */
    private $attendance = null;

    /**
     * @var Maca_MenuList_Admin_Waiters|null
     */
    private $waiters = null;

    /**
     * Constructor.
     *
     * @param Maca_MenuList_Admin_Attendance|null $attendance Personalliggare admin.
     * @param Maca_MenuList_Admin_Waiters|null     $waiters    Waiters admin.
     */
    public function __construct($attendance = null, $waiters = null) {
        $this->attendance = $attendance;
        $this->waiters = $waiters;

        add_action('admin_menu', array($this, 'add_admin_menu'), 20);
        add_action('admin_init', 'maca_menulist_personal_legacy_admin_redirects', 1);
        add_action('admin_init', array($this, 'handle_actions'));
    }

    /**
     * Register Personal submenu.
     *
     * @return void
     */
    public function add_admin_menu() {
        add_submenu_page(
            'maca-restu',
            __('Personal', 'maca-restu-pro'),
            __('Personal', 'maca-restu-pro'),
            maca_menulist_admin_required_cap(),
            maca_menulist_personal_admin_page(),
            array($this, 'render_page')
        );
    }

    /**
     * Handle POST from Personal screens tab.
     *
     * @return void
     */
    public function handle_actions() {
        if (!isset($_POST['maca_personal_action'])) {
            return;
        }

        if (!isset($_POST['maca_personal_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['maca_personal_nonce'])), 'maca_personal')) {
            return;
        }

        if (!maca_menulist_user_can_manage_plugin()) {
            return;
        }

        $action = sanitize_key(wp_unslash($_POST['maca_personal_action']));

        if ($action === 'save_screens') {
            maca_menulist_save_personal_screen_settings();
            wp_safe_redirect(maca_menulist_personal_admin_url(array('tab' => 'screens')));
            exit;
        }

        if ($action === 'flush_rewrites') {
            if (function_exists('maca_menulist_flush_rewrite_rules')) {
                maca_menulist_flush_rewrite_rules();
            } else {
                flush_rewrite_rules(false);
            }

            add_settings_error(
                'maca_personal',
                'rewrites_flushed',
                __('Permalink rules refreshed.', 'maca-restu-pro'),
                'success'
            );

            wp_safe_redirect(maca_menulist_personal_admin_url(array('tab' => 'screens')));
            exit;
        }
    }

    /**
     * Render Personal admin page.
     *
     * @return void
     */
    public function render_page() {
        if (!maca_menulist_user_can_manage_plugin()) {
            return;
        }

        $tab = maca_menulist_get_active_personal_admin_tab();

        settings_errors('maca_attendance');
        settings_errors('maca_waiters');
        settings_errors('maca_personal');
        ?>
        <div class="wrap maca-personal-admin">
            <h1><?php esc_html_e('Personal', 'maca-restu-pro'); ?></h1>
            <p class="description"><?php esc_html_e('Personalliggare, servitörer and staff screens in one place.', 'maca-restu-pro'); ?></p>

            <?php maca_menulist_render_personal_admin_tab_nav($tab); ?>

            <div class="maca-personal-tab-panel" style="margin-top: 16px;">
                <?php
                if ($tab === 'waiters' && $this->waiters instanceof Maca_MenuList_Admin_Waiters) {
                    $this->waiters->render_panel();
                } elseif ($tab === 'screens') {
                    $this->render_screens_tab();
                } elseif ($this->attendance instanceof Maca_MenuList_Admin_Attendance) {
                    $this->attendance->render_panel($tab);
                }
                ?>
            </div>
        </div>
        <?php
    }

    /**
     * Staff screens and personalliggare URLs.
     *
     * @return void
     */
    private function render_screens_tab() {
        $table_order_staff_pin_set = function_exists('maca_menulist_get_table_order_staff_pin')
            && maca_menulist_get_table_order_staff_pin() !== '';
        $table_order_staff_pin_needs_resave = $table_order_staff_pin_set
            && function_exists('maca_menulist_table_order_staff_pin_is_hmac')
            && !maca_menulist_table_order_staff_pin_is_hmac(maca_menulist_get_table_order_staff_pin());
        $waiter_order_slug = function_exists('maca_menulist_get_waiter_order_slug')
            ? maca_menulist_get_waiter_order_slug()
            : 'meny-servitris';
        $kitchen_order_slug = function_exists('maca_menulist_get_kitchen_order_slug')
            ? maca_menulist_get_kitchen_order_slug()
            : 'meny-kok';
        $attendance_slug = function_exists('maca_menulist_get_attendance_slug')
            ? maca_menulist_get_attendance_slug()
            : 'stampla';
        $attendance_enabled = function_exists('maca_menulist_attendance_enabled')
            && maca_menulist_attendance_enabled();
        $staff_block_reason = function_exists('maca_menulist_get_staff_order_pages_block_reason')
            ? maca_menulist_get_staff_order_pages_block_reason()
            : '';
        ?>
        <h2><?php esc_html_e('Staff screens', 'maca-restu-pro'); ?></h2>
        <p class="description">
            <?php esc_html_e('PIN and URLs for waiter/kitchen pages and personalliggare. Table ordering options (delivery mode, guest order list) remain under Settings → Table ordering.', 'maca-restu-pro'); ?>
        </p>

        <form method="post" action="">
            <?php wp_nonce_field('maca_personal', 'maca_personal_nonce'); ?>
            <input type="hidden" name="maca_personal_action" value="save_screens">
            <table class="form-table" role="presentation">
                <tr>
                    <th scope="row"><?php esc_html_e('Staff PIN', 'maca-restu-pro'); ?></th>
                    <td>
                        <?php
                        $staff_pin_attrs = maca_menulist_admin_secret_input_attrs(
                            $table_order_staff_pin_set,
                            array(
                                'id' => 'maca_table_order_staff_pin',
                                'name' => 'maca_table_order_staff_pin',
                                'inputmode' => 'numeric',
                                'autocomplete' => 'new-password',
                                'autocapitalize' => 'off',
                                'spellcheck' => 'false',
                            )
                        );
                        ?>
                        <input <?php echo maca_menulist_admin_secret_field_attr_string($staff_pin_attrs); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>>
                        <p class="description">
                            <?php
                            if ($table_order_staff_pin_set) {
                                esc_html_e('Used for waiter/kitchen pages and personalliggare control view. Leave blank to keep existing PIN.', 'maca-restu-pro');
                            } else {
                                esc_html_e('Used for waiter/kitchen pages and personalliggare control view.', 'maca-restu-pro');
                            }
                            ?>
                        </p>
                        <?php if ($table_order_staff_pin_needs_resave) : ?>
                            <p><strong style="color:#b32d2e;"><?php esc_html_e('Enter your PIN again here and save once — required after the latest update.', 'maca-restu-pro'); ?></strong></p>
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php esc_html_e('Waiter page slug', 'maca-restu-pro'); ?></th>
                    <td>
                        <input type="text" name="maca_waiter_order_slug" value="<?php echo esc_attr($waiter_order_slug); ?>" class="regular-text">
                        <?php if (function_exists('maca_menulist_table_order_waiter_page_enabled') && maca_menulist_table_order_waiter_page_enabled()) : ?>
                            <p class="description"><a href="<?php echo esc_url(maca_menulist_get_waiter_order_url()); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html(maca_menulist_get_waiter_order_url()); ?></a></p>
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php esc_html_e('Kitchen page slug', 'maca-restu-pro'); ?></th>
                    <td>
                        <input type="text" name="maca_kitchen_order_slug" value="<?php echo esc_attr($kitchen_order_slug); ?>" class="regular-text">
                        <?php if (function_exists('maca_menulist_table_order_kitchen_page_enabled') && maca_menulist_table_order_kitchen_page_enabled()) : ?>
                            <p class="description"><a href="<?php echo esc_url(maca_menulist_get_kitchen_order_url()); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html(maca_menulist_get_kitchen_order_url()); ?></a></p>
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php esc_html_e('Personalliggare', 'maca-restu-pro'); ?></th>
                    <td>
                        <label>
                            <input type="checkbox" name="maca_attendance_enabled" value="1" <?php checked($attendance_enabled); ?>>
                            <?php esc_html_e('Enable personalliggare (clock in/out)', 'maca-restu-pro'); ?>
                        </label>
                        <p>
                            <label for="maca_attendance_slug"><strong><?php esc_html_e('Clock-in page slug', 'maca-restu-pro'); ?></strong></label><br>
                            <input type="text" id="maca_attendance_slug" name="maca_attendance_slug" value="<?php echo esc_attr($attendance_slug); ?>" class="regular-text">
                        </p>
                        <?php if (function_exists('maca_menulist_get_attendance_url')) : ?>
                            <p class="description">
                                <?php
                                printf(
                                    /* translators: 1: clock-in URL, 2: control URL */
                                    esc_html__('Clock-in: %1$s · Control view: %2$s', 'maca-restu-pro'),
                                    '<a href="' . esc_url(maca_menulist_get_attendance_url()) . '" target="_blank" rel="noopener">' . esc_html(maca_menulist_get_attendance_url()) . '</a>',
                                    '<a href="' . esc_url(maca_menulist_get_attendance_control_url()) . '" target="_blank" rel="noopener">' . esc_html(maca_menulist_get_attendance_control_url()) . '</a>'
                                );
                                ?>
                            </p>
                        <?php endif; ?>
                    </td>
                </tr>
            </table>
            <?php submit_button(__('Save staff screens', 'maca-restu-pro')); ?>
        </form>

        <?php if ($staff_block_reason !== '' || function_exists('maca_menulist_get_waiter_order_url')) : ?>
            <div class="notice <?php echo $staff_block_reason === '' ? 'notice-info' : 'notice-warning'; ?> inline" style="margin: 16px 0; padding: 8px 12px; max-width: 720px;">
                <p><strong><?php esc_html_e('Staff page status', 'maca-restu-pro'); ?></strong></p>
                <?php if ($staff_block_reason !== '') : ?>
                    <p><?php echo esc_html($staff_block_reason); ?></p>
                <?php endif; ?>
                <?php if (function_exists('maca_menulist_get_waiter_order_url')) : ?>
                    <ul style="margin: 6px 0 0 18px; list-style: disc;">
                        <li>
                            <?php esc_html_e('Waiter:', 'maca-restu-pro'); ?>
                            <code><?php echo esc_html(maca_menulist_get_waiter_order_url()); ?></code>
                        </li>
                        <li>
                            <?php esc_html_e('Kitchen:', 'maca-restu-pro'); ?>
                            <code><?php echo esc_html(maca_menulist_get_kitchen_order_url()); ?></code>
                        </li>
                    </ul>
                <?php endif; ?>
            </div>
        <?php endif; ?>

        <form method="post" action="" style="margin-top: 8px;">
            <?php wp_nonce_field('maca_personal', 'maca_personal_nonce'); ?>
            <input type="hidden" name="maca_personal_action" value="flush_rewrites">
            <?php submit_button(__('Refresh permalink rules', 'maca-restu-pro'), 'secondary', 'submit', false); ?>
            <span class="description" style="margin-left: 8px;"><?php esc_html_e('Use if staff URLs show “not found” after changing slugs.', 'maca-restu-pro'); ?></span>
        </form>
        <?php
    }
}
