<?php
/**
 * Reminders AJAX handler for Noesia Smart Waiter.
 *
 * Self-contained module-local AJAX class.
 * Keeps the existing action names and response payloads intact.
 *
 * @package Noesia_Smart_Waiter
 */

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

if ( ! class_exists( 'Noesia_Swa_Module_Reminders_Ajax' ) ) {
    /**
     * Module-local Reminders AJAX.
     */
    class Noesia_Swa_Module_Reminders_Ajax {

        /**
         * Register AJAX hooks.
         */
        public function __construct() {
            add_action( 'wp_ajax_noesia_swa_reminders_list', array( $this, 'handle_list' ) );
            add_action( 'wp_ajax_noesia_swa_reminders_save', array( $this, 'handle_save' ) );
            add_action( 'wp_ajax_noesia_swa_reminders_toggle', array( $this, 'handle_toggle' ) );
            add_action( 'wp_ajax_noesia_swa_reminders_delete', array( $this, 'handle_delete' ) );
        }

        /**
         * Enforce admin capability + nonce.
         *
         * @return bool
         */
        private function guard() {
            check_ajax_referer( 'noesia_swa_nonce', 'nonce' );

            if ( ! current_user_can( 'manage_options' ) ) {
                wp_send_json_error( array( 'message' => __( 'Unauthorized', 'noesia-smart-waiter' ) ) );
                return false;
            }

            return true;
        }

        /**
         * Read one posted integer value after AJAX guard verification.
         *
         * @param string $key Input key.
         * @return int
         */
        private function post_absint( $key ) {
            // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Every caller verifies the AJAX nonce in guard() before reading input.
            if ( ! isset( $_POST[ $key ] ) ) {
                return 0;
            }

            // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Every caller verifies the AJAX nonce in guard() before reading input.
            return absint( wp_unslash( $_POST[ $key ] ) );
        }

        /**
         * Read one posted text value after AJAX guard verification.
         *
         * @param string $key Input key.
         * @return string
         */
        private function post_text( $key ) {
            // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Every caller verifies the AJAX nonce in guard() before reading input.
            if ( ! isset( $_POST[ $key ] ) ) {
                return '';
            }

            // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Every caller verifies the AJAX nonce in guard() before reading input.
            return sanitize_text_field( wp_unslash( $_POST[ $key ] ) );
        }

        /**
         * Read one posted textarea value after AJAX guard verification.
         *
         * @param string $key Input key.
         * @return string
         */
        private function post_textarea( $key ) {
            // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Every caller verifies the AJAX nonce in guard() before reading input.
            if ( ! isset( $_POST[ $key ] ) ) {
                return '';
            }

            // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Every caller verifies the AJAX nonce in guard() before reading input.
            return sanitize_textarea_field( wp_unslash( $_POST[ $key ] ) );
        }

        /**
         * Normalize one reminder record for JS.
         *
         * @param int $post_id Reminder post ID.
         * @return array|null
         */
        private function get_item( $post_id ) {
            $post_id = absint( $post_id );

            if ( $post_id < 1 || 'noesia_reminder' !== get_post_type( $post_id ) ) {
                return null;
            }

            $status = sanitize_key( (string) get_post_meta( $post_id, 'noesia_rem_status', true ) );

            if ( ! in_array( $status, array( 'open', 'completed' ), true ) ) {
                $status = 'open';
            }

            return array(
                'id'          => $post_id,
                'type'        => sanitize_text_field( (string) get_post_meta( $post_id, 'noesia_rem_type', true ) ),
                'dueDate'     => sanitize_text_field( (string) get_post_meta( $post_id, 'noesia_rem_due_date', true ) ),
                'dueTime'     => sanitize_text_field( (string) get_post_meta( $post_id, 'noesia_rem_due_time', true ) ),
                'related'     => sanitize_text_field( (string) get_post_meta( $post_id, 'noesia_rem_related', true ) ),
                'message'     => sanitize_textarea_field( (string) get_post_meta( $post_id, 'noesia_rem_message', true ) ),
                'status'      => $status,
                'createdAt'   => (int) get_post_meta( $post_id, 'noesia_rem_created', true ),
                'updatedAt'   => (int) get_post_modified_time( 'U', true, $post_id ),
                'completedAt' => (int) get_post_meta( $post_id, 'noesia_rem_completed', true ),
            );
        }

        /**
         * List reminders.
         *
         * @return void
         */
        public function handle_list() {
            if ( ! $this->guard() ) {
                return;
            }

            $query = new WP_Query(
                array(
                    'post_type'      => 'noesia_reminder',
                    'post_status'    => 'publish',
                    'posts_per_page' => -1,
                    'orderby'        => 'modified',
                    'order'          => 'DESC',
                    'fields'         => 'ids',
                )
            );

            $items = array();

            if ( ! empty( $query->posts ) ) {
                foreach ( $query->posts as $post_id ) {
                    $item = $this->get_item( $post_id );

                    if ( is_array( $item ) ) {
                        $items[] = $item;
                    }
                }
            }

            wp_send_json_success( array( 'items' => $items ) );
        }

        /**
         * Save a reminder.
         *
         * @return void
         */
        public function handle_save() {
            if ( ! $this->guard() ) {
                return;
            }

            $post_id  = $this->post_absint( 'post_id' );
            $type     = $this->post_text( 'type' );
            $due_date = $this->post_text( 'due_date' );
            $due_time = $this->post_text( 'due_time' );
            $related  = $this->post_text( 'related' );
            $message  = $this->post_textarea( 'message' );

            if ( '' !== $due_date && ! preg_match( '/^\d{4}-\d{2}-\d{2}$/', $due_date ) ) {
                $due_date = '';
            }

            if ( '' !== $due_time && ! preg_match( '/^\d{2}:\d{2}$/', $due_time ) ) {
                $due_time = '';
            }

            if ( '' === $type && '' === $message ) {
                wp_send_json_error( array( 'message' => __( 'Type or message is required.', 'noesia-smart-waiter' ) ) );
                return;
            }

            $title_source = '' !== $type ? $type : $message;
            $title_source = wp_strip_all_tags( $title_source );
            $title        = function_exists( 'mb_substr' ) ? mb_substr( $title_source, 0, 80 ) : substr( $title_source, 0, 80 );

            if ( '' === $title ) {
                $title = __( 'Reminder', 'noesia-smart-waiter' );
            }

            if ( $post_id > 0 ) {
                if ( 'noesia_reminder' !== get_post_type( $post_id ) ) {
                    wp_send_json_error( array( 'message' => __( 'Invalid reminder.', 'noesia-smart-waiter' ) ) );
                    return;
                }

                $saved_id = wp_update_post(
                    array(
                        'ID'         => $post_id,
                        'post_title' => $title,
                    ),
                    true
                );
            } else {
                $saved_id = wp_insert_post(
                    array(
                        'post_type'   => 'noesia_reminder',
                        'post_status' => 'publish',
                        'post_title'  => $title,
                    ),
                    true
                );
            }

            if ( is_wp_error( $saved_id ) || ! $saved_id ) {
                wp_send_json_error( array( 'message' => __( 'Could not save reminder.', 'noesia-smart-waiter' ) ) );
                return;
            }

            $saved_id = absint( $saved_id );

            $existing_status = sanitize_key( (string) get_post_meta( $saved_id, 'noesia_rem_status', true ) );

            if ( ! in_array( $existing_status, array( 'open', 'completed' ), true ) ) {
                $existing_status = 'open';
            }

            if ( ! get_post_meta( $saved_id, 'noesia_rem_created', true ) ) {
                update_post_meta( $saved_id, 'noesia_rem_created', current_time( 'timestamp' ) );
            }

            update_post_meta( $saved_id, 'noesia_rem_type', $type );
            update_post_meta( $saved_id, 'noesia_rem_due_date', $due_date );
            update_post_meta( $saved_id, 'noesia_rem_due_time', $due_time );
            update_post_meta( $saved_id, 'noesia_rem_related', $related );
            update_post_meta( $saved_id, 'noesia_rem_message', $message );
            update_post_meta( $saved_id, 'noesia_rem_status', $existing_status );

            if ( 'completed' !== $existing_status ) {
                update_post_meta( $saved_id, 'noesia_rem_completed', 0 );
            }

            wp_send_json_success(
                array(
                    'message' => __( 'Reminder saved.', 'noesia-smart-waiter' ),
                    'item'    => $this->get_item( $saved_id ),
                )
            );
        }

        /**
         * Toggle reminder completion.
         *
         * @return void
         */
        public function handle_toggle() {
            if ( ! $this->guard() ) {
                return;
            }

            $post_id = $this->post_absint( 'post_id' );

            if ( $post_id < 1 || 'noesia_reminder' !== get_post_type( $post_id ) ) {
                wp_send_json_error( array( 'message' => __( 'Invalid reminder.', 'noesia-smart-waiter' ) ) );
                return;
            }

            $status = sanitize_key( (string) get_post_meta( $post_id, 'noesia_rem_status', true ) );
            $status = ( 'completed' === $status ) ? 'open' : 'completed';

            update_post_meta( $post_id, 'noesia_rem_status', $status );
            update_post_meta( $post_id, 'noesia_rem_completed', ( 'completed' === $status ) ? current_time( 'timestamp' ) : 0 );

            wp_send_json_success(
                array(
                    'message' => __( 'Reminder updated.', 'noesia-smart-waiter' ),
                    'item'    => $this->get_item( $post_id ),
                )
            );
        }

        /**
         * Delete a reminder.
         *
         * @return void
         */
        public function handle_delete() {
            if ( ! $this->guard() ) {
                return;
            }

            $post_id = $this->post_absint( 'post_id' );

            if ( $post_id < 1 || 'noesia_reminder' !== get_post_type( $post_id ) ) {
                wp_send_json_error( array( 'message' => __( 'Invalid reminder.', 'noesia-smart-waiter' ) ) );
                return;
            }

            wp_delete_post( $post_id, true );

            wp_send_json_success( array( 'message' => __( 'Reminder deleted.', 'noesia-smart-waiter' ) ) );
        }
    }
}
