<?php

final class WPBOOKIT_Guest_Controller
{

    public function get_guest_list(WP_REST_Request $request)
    {
        $args =array();
        $args['offset'] = sanitize_text_field( $request->get_param('start') );
        if ($request->has_param('order')) :
            $args['order'] = strtoupper($request->get_param('order')[0]['dir'] ?? '');
            $args['order_by'] = $request->get_param('order')[0]['name'] ?? "";
        endif;

        if ($request->has_param('guest_search')) {
            $args['guest_name'] = $request->get_param('guest_search');
        }

        $guest_users = wpbookit_get_guest_users( $args );
        $data = array_map(function ($item) {
            return [
                'id'            => $item->get_id(),
                'guest_name'    => $item->get_guest_name(),
                'guest_email'   => $item->get_guest_email(),
                'guest_phone_number'   => $item->get_guest_phone_number()??'-',
            ];
        }, $guest_users->results);
        wp_send_json(
            array(
                "recordsTotal"      => $guest_users->total ?? 0,
                "recordsFiltered"   => $guest_users->total ?? 0,
                "data"              => $data
            )
        );

    }

    public function delete_guest_callback(WP_REST_Request $request)
    {
        // Require authentication
        if ( ! is_user_logged_in() ) {
            wp_send_json([
                'status'  => 'error',
                'message' => esc_html__('Authentication required.', 'wpbookit'),
            ]);
            return;
        }

        // Restrict capability to admins/site managers
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json([
                'status'  => 'error',
                'message' => esc_html__('You do not have permission to delete guest users.', 'wpbookit'),
            ]);
            return;
        }

        // Validate nonce
        if ( ! wp_verify_nonce( $request->get_param('_ajax_nonce'), 'wpb_ajax_nonce' ) ) {
            wp_send_json([
                'status'  => 'error',
                'message' => esc_html__('Invalid or missing token.', 'wpbookit'),
            ]);
            return;
        }

        // Validate guest ID
        $guest_id = absint( $request->get_param('guest_id') );
        if ( ! $guest_id ) {
            wp_send_json([
                'status'  => 'error',
                'message' => esc_html__('Invalid guest ID.', 'wpbookit'),
            ]);
            return;
        }

        // Delete the guest user
        if ( wpbookit_delete_guest_user( $guest_id ) ) {
            wp_send_json([
                'status'  => 'success',
                'message' => esc_html__('Guest user deleted successfully.', 'wpbookit'),
            ]);
            return;
        }

        wp_send_json([
            'status'  => 'error',
            'message' => esc_html__('Error deleting guest user.', 'wpbookit'),
        ]);
    }

}