<?php
/**
 * Free Design / Live Requests AJAX handlers.
 *
 * Owns the request/public-app AJAX endpoints that still lived in the kernel:
 * - noesia_swa_submit
 * - noesia_swa_get_requests
 * - noesia_swa_complete
 *
 * Action names and payloads stay the same for backward compatibility.
 *
 * @package Noesia_Smart_Waiter
 */

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

if ( ! class_exists( 'Noesia_SWA_Module_Design_Ajax' ) ) {
    /**
     * Design / Live Requests AJAX handlers.
     */
    class Noesia_SWA_Module_Design_Ajax {

        /**
         * Register AJAX endpoints.
         */
        public function __construct() {
            add_action( 'wp_ajax_noesia_swa_submit', array( $this, 'handle_submit_request' ) );
            add_action( 'wp_ajax_nopriv_noesia_swa_submit', array( $this, 'handle_submit_request' ) );

            add_action( 'wp_ajax_noesia_swa_get_requests', array( $this, 'handle_get_requests' ) );

            if ( defined( 'NOESIA_DEMO_MODE' ) && NOESIA_DEMO_MODE ) {
                add_action( 'wp_ajax_nopriv_noesia_swa_get_requests', array( $this, 'handle_get_requests' ) );
            }

            add_action( 'wp_ajax_noesia_swa_complete', array( $this, 'handle_complete_request' ) );
        }

        /**
         * Handle public request submissions.
         *
         * @return void
         */
        public function handle_submit_request() {
            check_ajax_referer( 'noesia_swa_nonce', 'nonce' );

            if ( ! current_user_can( 'manage_options' ) ) {
                $ip       = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '127.0.0.1';
                $lock_key = 'noesia_swa_lock_' . md5( $ip );

                if ( get_transient( $lock_key ) ) {
                    wp_send_json_error(
                        array(
                            'message' => '⏳ ' . __( 'Please wait 15s.', 'noesia-smart-waiter' ),
                        )
                    );
                    return;
                }

                set_transient( $lock_key, true, 15 );
            }

            $label    = isset( $_POST['label'] ) ? sanitize_text_field( wp_unslash( $_POST['label'] ) ) : '';
            $location = isset( $_POST['location'] ) ? sanitize_text_field( wp_unslash( $_POST['location'] ) ) : '';
            $type     = isset( $_POST['type'] ) ? sanitize_text_field( wp_unslash( $_POST['type'] ) ) : 'custom';

            $post_id = wp_insert_post(
                array(
                    'post_type'   => 'noesia_request',
                    'post_status' => 'publish',
                    'post_title'  => $label . ' - ' . $location,
                )
            );

            if ( $post_id ) {
                update_post_meta( $post_id, 'noesia_loc', $location );
                update_post_meta( $post_id, 'noesia_type', $type );
                update_post_meta( $post_id, 'noesia_label', $label );
                update_post_meta( $post_id, 'noesia_status', 'active' );
                update_post_meta( $post_id, 'noesia_time', current_time( 'timestamp' ) );

                wp_send_json_success(
                    array(
                        'message' => __( '✅ Request Sent!', 'noesia-smart-waiter' ),
                    )
                );
                return;
            }

            wp_send_json_error(
                array(
                    'message' => __( '❌ Database Error', 'noesia-smart-waiter' ),
                )
            );
        }

        /**
         * Handle active requests fetch.
         *
         * @return void
         */
        public function handle_get_requests() {
            check_ajax_referer( 'noesia_swa_nonce', 'nonce' );

            $is_demo_mode = defined( 'NOESIA_DEMO_MODE' ) && NOESIA_DEMO_MODE;

            if ( ! current_user_can( 'manage_options' ) && ! $is_demo_mode ) {
                wp_send_json_error( 'Unauthorized' );
                return;
            }

            $query = new WP_Query(
                array(
                    'post_type'      => 'noesia_request',
                    // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Active/completed request state is stored in post meta for this module and the current CPT volume is expected to stay small.
                    'meta_query'     => array(
                        array(
                            'key'   => 'noesia_status',
                            'value' => 'active',
                        ),
                    ),
                    'posts_per_page' => -1,
                    'orderby'        => 'date',
                    'order'          => 'ASC',
                )
            );

            $requests = array();

            while ( $query->have_posts() ) {
                $query->the_post();
                $post_id    = get_the_ID();
                $time_stamp = get_post_meta( $post_id, 'noesia_time', true );

                $requests[] = array(
                    'id'        => $post_id,
                    'location'  => get_post_meta( $post_id, 'noesia_loc', true ),
                    'type'      => get_post_meta( $post_id, 'noesia_type', true ),
                    'label'     => get_post_meta( $post_id, 'noesia_label', true ),
                    'time_diff' => human_time_diff( $time_stamp, current_time( 'timestamp' ) ),
                    'timestamp' => (int) $time_stamp,
                );
            }

            wp_reset_postdata();

            wp_send_json_success(
                array(
                    'requests' => $requests,
                    'count'    => count( $requests ),
                )
            );
        }

        /**
         * Mark a request as completed.
         *
         * @return void
         */
        public function handle_complete_request() {
            check_ajax_referer( 'noesia_swa_nonce', 'nonce' );

            if ( ! current_user_can( 'manage_options' ) ) {
                return;
            }

            if ( ! isset( $_POST['post_id'] ) ) {
                wp_send_json_error( 'Missing ID' );
                return;
            }

            $post_id = absint( wp_unslash( $_POST['post_id'] ) );

            update_post_meta( $post_id, 'noesia_status', 'completed' );
            wp_send_json_success();
        }
    }
}
