<?php
/**
 * Admin UI for waiter profiles and table assignments.
 *
 * @package Maca_Menu_List
 */

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

if (!function_exists('maca_menulist_should_apply_personal_admin_sv')) {
    require_once __DIR__ . '/admin-personal-i18n.php';
}

/**
 * Waiters admin screen.
 */
class Maca_MenuList_Admin_Waiters {

    /**
     * Constructor.
     */
    public function __construct() {
        add_action('admin_init', array($this, 'handle_actions'));
    }

    /**
     * Personal admin URL for waiters views.
     *
     * @param array<string, string|int> $args Query args.
     * @return string
     */
    private function page_url($args = array()) {
        $args = array_merge(array('tab' => 'waiters'), $args);

        if (function_exists('maca_menulist_personal_admin_url')) {
            return maca_menulist_personal_admin_url($args);
        }

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

    /**
     * Handle POST actions.
     */
    public function handle_actions() {
        if (!isset($_POST['maca_waiters_action'])) {
            return;
        }

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

        if (!maca_menulist_user_can_manage_plugin() || !maca_menulist_waiters_feature_available()) {
            return;
        }

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

        if ($action === 'save_waiter') {
            $this->handle_save_waiter();
            return;
        }

        if ($action === 'delete_waiter') {
            $this->handle_delete_waiter();
        }
    }

    /**
     * Save waiter profile.
     */
    private function handle_save_waiter() {
        $waiter_id = isset($_POST['waiter_id']) ? absint(wp_unslash($_POST['waiter_id'])) : 0;
        $name = isset($_POST['waiter_name']) ? sanitize_text_field(wp_unslash($_POST['waiter_name'])) : '';
        $is_active = !empty($_POST['waiter_is_active']);
        $sort_order = isset($_POST['waiter_sort_order']) ? (int) wp_unslash($_POST['waiter_sort_order']) : 0;
        $table_numbers = isset($_POST['waiter_tables']) ? array_map('sanitize_text_field', (array) wp_unslash($_POST['waiter_tables'])) : array();

        if (empty($table_numbers) && isset($_POST['waiter_tables_manual'])) {
            $manual = sanitize_textarea_field(wp_unslash($_POST['waiter_tables_manual']));
            $table_numbers = preg_split('/\r\n|\r|\n/', $manual);
            $table_numbers = is_array($table_numbers) ? array_map('trim', $table_numbers) : array();
        }

        if ($name === '') {
            add_settings_error('maca_waiters', 'name_required', __('Enter a name for the waiter.', 'maca-restu-pro'), 'error');
            return;
        }

        $saved_id = maca_menulist_db_save_waiter(
            array(
                'id' => $waiter_id,
                'name' => $name,
                'is_active' => $is_active,
                'sort_order' => $sort_order,
            ),
            $table_numbers
        );

        if ($saved_id <= 0) {
            add_settings_error('maca_waiters', 'save_failed', __('Could not save waiter.', 'maca-restu-pro'), 'error');
            return;
        }

        add_settings_error('maca_waiters', 'saved', __('Waiter saved.', 'maca-restu-pro'), 'success');
        wp_safe_redirect($this->page_url(array('action' => 'edit', 'waiter_id' => (string) $saved_id)));
        exit;
    }

    /**
     * Delete waiter profile.
     */
    private function handle_delete_waiter() {
        $waiter_id = isset($_POST['waiter_id']) ? absint(wp_unslash($_POST['waiter_id'])) : 0;
        if ($waiter_id <= 0) {
            return;
        }

        if (maca_menulist_db_delete_waiter($waiter_id)) {
            add_settings_error('maca_waiters', 'deleted', __('Waiter deleted.', 'maca-restu-pro'), 'success');
        }

        wp_safe_redirect($this->page_url());
        exit;
    }

    /**
     * Render waiters tab inside Personal.
     *
     * @return void
     */
    public function render_panel() {
        if (!maca_menulist_user_can_manage_plugin()) {
            return;
        }

        if (!maca_menulist_waiters_feature_available()) {
            echo '<h2>' . esc_html__('Waiters', 'maca-restu-pro') . '</h2>';
            echo '<p>' . esc_html__('Enable table ordering with waiter or kitchen delivery under Settings → Table ordering.', 'maca-restu-pro') . '</p>';
            return;
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only view switch.
        $action = isset($_GET['action']) ? sanitize_key(wp_unslash($_GET['action'])) : 'list';
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only edit form.
        $waiter_id = isset($_GET['waiter_id']) ? absint(wp_unslash($_GET['waiter_id'])) : 0;

        ?>
        <h2><?php esc_html_e('Waiters', 'maca-restu-pro'); ?></h2>
        <p class="description">
            <?php esc_html_e('Create waiter profiles and assign tables. On the shared waiter page (protected by PIN), staff can view all tables or filter to one waiter’s assigned tables.', 'maca-restu-pro'); ?>
        </p>

        <?php
        if ($action === 'edit' || $action === 'add') {
            $this->render_edit_form($action === 'add' ? null : maca_menulist_db_get_waiter($waiter_id));
        } else {
            $this->render_list();
        }
    }

    /**
     * List waiters.
     */
    private function render_list() {
        $waiters = maca_menulist_db_get_waiters(false);
        ?>
        <p>
            <a href="<?php echo esc_url($this->page_url(array('action' => 'add'))); ?>" class="button button-primary">
                <?php esc_html_e('Add waiter', 'maca-restu-pro'); ?>
            </a>
        </p>

        <?php if (empty($waiters)) : ?>
            <p><?php esc_html_e('No waiters yet. Add profiles and assign tables from your booking list.', 'maca-restu-pro'); ?></p>
        <?php else : ?>
            <table class="widefat striped">
                <thead>
                    <tr>
                        <th><?php esc_html_e('Name', 'maca-restu-pro'); ?></th>
                        <th><?php esc_html_e('Tables', 'maca-restu-pro'); ?></th>
                        <th><?php esc_html_e('Active', 'maca-restu-pro'); ?></th>
                        <th><?php esc_html_e('Actions', 'maca-restu-pro'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($waiters as $waiter) : ?>
                        <?php $tables = maca_menulist_db_get_waiter_table_numbers((int) $waiter->id); ?>
                        <tr>
                            <td><strong><?php echo esc_html($waiter->name); ?></strong></td>
                            <td><?php echo esc_html($tables ? implode(', ', $tables) : '—'); ?></td>
                            <td><?php echo (int) $waiter->is_active ? esc_html__('Yes', 'maca-restu-pro') : esc_html__('No', 'maca-restu-pro'); ?></td>
                            <td>
                                <a href="<?php echo esc_url($this->page_url(array('action' => 'edit', 'waiter_id' => (string) (int) $waiter->id))); ?>">
                                    <?php esc_html_e('Edit', 'maca-restu-pro'); ?>
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
        <?php
    }

    /**
     * Edit/add form.
     *
     * @param object|null $waiter Waiter row or null for new.
     */
    private function render_edit_form($waiter) {
        $waiter_id = $waiter ? (int) $waiter->id : 0;
        $assigned = $waiter ? maca_menulist_db_get_waiter_table_numbers($waiter_id) : array();
        $assigned_map = array();

        foreach ($assigned as $table_number) {
            $assigned_map[maca_menulist_normalize_table_number($table_number)] = true;
        }

        $booking_tables = function_exists('maca_menulist_db_get_booking_tables')
            ? maca_menulist_db_get_booking_tables(true)
            : array();
        ?>
        <p><a href="<?php echo esc_url($this->page_url()); ?>">&larr; <?php esc_html_e('Back to list', 'maca-restu-pro'); ?></a></p>

        <form method="post" action="">
            <?php wp_nonce_field('maca_waiters', 'maca_waiters_nonce'); ?>
            <input type="hidden" name="maca_waiters_action" value="save_waiter">
            <input type="hidden" name="waiter_id" value="<?php echo esc_attr((string) $waiter_id); ?>">

            <table class="form-table" role="presentation">
                <tr>
                    <th scope="row"><label for="waiter_name"><?php esc_html_e('Name', 'maca-restu-pro'); ?></label></th>
                    <td>
                        <input type="text" id="waiter_name" name="waiter_name" class="regular-text" required value="<?php echo esc_attr($waiter ? $waiter->name : ''); ?>">
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="waiter_sort_order"><?php esc_html_e('Sort order', 'maca-restu-pro'); ?></label></th>
                    <td>
                        <input type="number" id="waiter_sort_order" name="waiter_sort_order" class="small-text" value="<?php echo esc_attr($waiter ? (string) (int) $waiter->sort_order : '0'); ?>">
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php esc_html_e('Active', 'maca-restu-pro'); ?></th>
                    <td>
                        <label>
                            <input type="checkbox" name="waiter_is_active" value="1" <?php checked(!$waiter || (int) $waiter->is_active); ?>>
                            <?php esc_html_e('Show in waiter filter on staff page', 'maca-restu-pro'); ?>
                        </label>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php esc_html_e('Assigned tables', 'maca-restu-pro'); ?></th>
                    <td>
                        <?php if (empty($booking_tables)) : ?>
                            <p class="description">
                                <?php
                                printf(
                                    /* translators: %s: admin page link */
                                    esc_html__('No tables found. Add tables under %s first, or enter table numbers manually below.', 'maca-restu-pro'),
                                    '<a href="' . esc_url(admin_url('admin.php?page=maca-restu-bookings')) . '">' . esc_html__('Bordsbokningar', 'maca-restu-pro') . '</a>'
                                );
                                ?>
                            </p>
                            <textarea name="waiter_tables_manual" rows="4" class="large-text" placeholder="<?php esc_attr_e('One table number per line, e.g. 1, 2, 12', 'maca-restu-pro'); ?>"><?php echo esc_textarea(implode("\n", $assigned)); ?></textarea>
                            <p class="description"><?php esc_html_e('Table numbers must match the QR URL (?bord=) and guest orders.', 'maca-restu-pro'); ?></p>
                        <?php else : ?>
                            <fieldset>
                                <?php foreach ($booking_tables as $table) : ?>
                                    <?php
                                    $checked = isset($assigned_map[maca_menulist_normalize_table_number($table->table_number)]);
                                    ?>
                                    <label style="display:block; margin-bottom:6px;">
                                        <input type="checkbox" name="waiter_tables[]" value="<?php echo esc_attr($table->table_number); ?>" <?php checked($checked); ?>>
                                        <?php
                                        echo esc_html(
                                            sprintf(
                                                /* translators: 1: table number, 2: seats */
                                                __('Table %1$s (%2$d seats)', 'maca-restu-pro'),
                                                $table->table_number,
                                                (int) $table->seats
                                            )
                                        );
                                        ?>
                                    </label>
                                <?php endforeach; ?>
                            </fieldset>
                        <?php endif; ?>
                    </td>
                </tr>
            </table>

            <?php submit_button($waiter ? __('Save waiter', 'maca-restu-pro') : __('Add waiter', 'maca-restu-pro')); ?>
        </form>

        <?php if ($waiter_id > 0) : ?>
            <form method="post" action="" onsubmit="return confirm('<?php echo esc_js(__('Delete this waiter?', 'maca-restu-pro')); ?>');">
                <?php wp_nonce_field('maca_waiters', 'maca_waiters_nonce'); ?>
                <input type="hidden" name="maca_waiters_action" value="delete_waiter">
                <input type="hidden" name="waiter_id" value="<?php echo esc_attr((string) $waiter_id); ?>">
                <?php submit_button(__('Delete waiter', 'maca-restu-pro'), 'delete', 'submit', false); ?>
            </form>
        <?php endif; ?>
        <?php
    }
}
