<?php
/**
 * Appointments AJAX handlers for Noesia Smart Waiter.
 *
 * @package Noesia_Smart_Waiter
 */

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

if ( ! class_exists( 'Noesia_Swa_Module_Appointments_Ajax' ) ) {
    /**
     * Module-local AJAX controller for Appointments.
     */
    class Noesia_Swa_Module_Appointments_Ajax {

        /**
         * Constructor.
         */
        public function __construct() {
            add_action( 'wp_ajax_noesia_swa_appointments_list', array( $this, 'handle_appointments_list' ) );
            add_action( 'wp_ajax_noesia_swa_appointments_save', array( $this, 'handle_appointments_save' ) );
            add_action( 'wp_ajax_noesia_swa_appointments_toggle', array( $this, 'handle_appointments_toggle' ) );
            add_action( 'wp_ajax_noesia_swa_appointments_delete', array( $this, 'handle_appointments_delete' ) );
        }

        /**
         * Build appointment response item.
         *
         * @param int $post_id Appointment post ID.
         * @return array|null
         */
        protected function get_appointment_item( $post_id ) {
            $post_id = absint( $post_id );

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

            $status           = sanitize_key( (string) get_post_meta( $post_id, 'noesia_appt_status', true ) );
            $allowed_statuses = array( 'scheduled', 'urgent', 'completed', 'cancelled', 'no_show' );

            if ( ! in_array( $status, $allowed_statuses, true ) ) {
                $status = 'scheduled';
            }

            return array(
                'id'         => $post_id,
                'date'       => sanitize_text_field( (string) get_post_meta( $post_id, 'noesia_appt_date', true ) ),
                'start'      => sanitize_text_field( (string) get_post_meta( $post_id, 'noesia_appt_start', true ) ),
                'end'        => sanitize_text_field( (string) get_post_meta( $post_id, 'noesia_appt_end', true ) ),
                'guestName'  => sanitize_text_field( (string) get_post_meta( $post_id, 'noesia_appt_guest_name', true ) ),
                'guestPhone' => sanitize_text_field( (string) get_post_meta( $post_id, 'noesia_appt_guest_phone', true ) ),
                'guestEmail' => sanitize_email( (string) get_post_meta( $post_id, 'noesia_appt_guest_email', true ) ),
                'reason'     => sanitize_text_field( (string) get_post_meta( $post_id, 'noesia_appt_reason', true ) ),
                'partySize'  => (string) absint( get_post_meta( $post_id, 'noesia_appt_party_size', true ) ),
                'location'   => sanitize_text_field( (string) get_post_meta( $post_id, 'noesia_appt_location', true ) ),
                'notes'      => sanitize_textarea_field( (string) get_post_meta( $post_id, 'noesia_appt_notes', true ) ),
                'status'     => $status,
                'createdAt'  => (int) get_post_meta( $post_id, 'noesia_appt_created', true ),
                'updatedAt'  => (int) get_post_modified_time( 'U', true, $post_id ),
            );
        }

        /**
         * List appointments.
         *
         * @return void
         */
        public function handle_appointments_list() {
            check_ajax_referer( 'noesia_swa_nonce', 'nonce' );

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

            $query = new WP_Query(
                array(
                    'post_type'      => 'noesia_appointment',
                    '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_appointment_item( $post_id );

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

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

        /**
         * Save an appointment.
         *
         * @return void
         */
        public function handle_appointments_save() {
            check_ajax_referer( 'noesia_swa_nonce', 'nonce' );

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

            $post_id     = isset( $_POST['post_id'] ) ? absint( wp_unslash( $_POST['post_id'] ) ) : 0;
            $date        = isset( $_POST['date'] ) ? sanitize_text_field( wp_unslash( $_POST['date'] ) ) : '';
            $status      = isset( $_POST['status'] ) ? sanitize_key( wp_unslash( $_POST['status'] ) ) : 'scheduled';
            $start       = isset( $_POST['start'] ) ? sanitize_text_field( wp_unslash( $_POST['start'] ) ) : '';
            $end         = isset( $_POST['end'] ) ? sanitize_text_field( wp_unslash( $_POST['end'] ) ) : '';
            $guest_name  = isset( $_POST['guest_name'] ) ? sanitize_text_field( wp_unslash( $_POST['guest_name'] ) ) : '';
            $guest_phone = isset( $_POST['guest_phone'] ) ? sanitize_text_field( wp_unslash( $_POST['guest_phone'] ) ) : '';
            $guest_email = isset( $_POST['guest_email'] ) ? sanitize_email( wp_unslash( $_POST['guest_email'] ) ) : '';
            $reason      = isset( $_POST['reason'] ) ? sanitize_text_field( wp_unslash( $_POST['reason'] ) ) : '';
            $party_size  = isset( $_POST['party_size'] ) ? absint( wp_unslash( $_POST['party_size'] ) ) : 0;
            $location    = isset( $_POST['location'] ) ? sanitize_text_field( wp_unslash( $_POST['location'] ) ) : '';
            $notes       = isset( $_POST['notes'] ) ? sanitize_textarea_field( wp_unslash( $_POST['notes'] ) ) : '';

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

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

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

            $allowed_statuses = array( 'scheduled', 'urgent', 'completed', 'cancelled', 'no_show' );

            if ( ! in_array( $status, $allowed_statuses, true ) ) {
                $status = 'scheduled';
            }

            if ( '' === $date || '' === $start || '' === $guest_name ) {
                wp_send_json_error( array( 'message' => __( 'Date, start time, and guest name are required.', 'noesia-smart-waiter' ) ) );
                return;
            }

            $title_source = $guest_name;

            if ( '' !== $reason ) {
                /* translators: 1: guest name, 2: appointment reason */
                $title_source = sprintf( __( '%1$s - %2$s', 'noesia-smart-waiter' ), $guest_name, $reason );
            }

            $title_source = wp_strip_all_tags( $title_source );
            $title        = function_exists( 'mb_substr' ) ? mb_substr( $title_source, 0, 120 ) : substr( $title_source, 0, 120 );

            if ( $post_id > 0 ) {
                if ( 'noesia_appointment' !== get_post_type( $post_id ) ) {
                    wp_send_json_error( array( 'message' => __( 'Invalid appointment.', '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_appointment',
                        'post_status' => 'publish',
                        'post_title'  => $title,
                    ),
                    true
                );
            }

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

            $saved_id = absint( $saved_id );

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

            update_post_meta( $saved_id, 'noesia_appt_date', $date );
            update_post_meta( $saved_id, 'noesia_appt_status', $status );
            update_post_meta( $saved_id, 'noesia_appt_start', $start );
            update_post_meta( $saved_id, 'noesia_appt_end', $end );
            update_post_meta( $saved_id, 'noesia_appt_guest_name', $guest_name );
            update_post_meta( $saved_id, 'noesia_appt_guest_phone', $guest_phone );
            update_post_meta( $saved_id, 'noesia_appt_guest_email', $guest_email );
            update_post_meta( $saved_id, 'noesia_appt_reason', $reason );
            update_post_meta( $saved_id, 'noesia_appt_party_size', $party_size );
            update_post_meta( $saved_id, 'noesia_appt_location', $location );
            update_post_meta( $saved_id, 'noesia_appt_notes', $notes );

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

        /**
         * Toggle appointment completion.
         *
         * @return void
         */
        public function handle_appointments_toggle() {
            check_ajax_referer( 'noesia_swa_nonce', 'nonce' );

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

            $post_id = isset( $_POST['post_id'] ) ? absint( wp_unslash( $_POST['post_id'] ) ) : 0;

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

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

            update_post_meta( $post_id, 'noesia_appt_status', $status );

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

        /**
         * Delete an appointment.
         *
         * @return void
         */
        public function handle_appointments_delete() {
            check_ajax_referer( 'noesia_swa_nonce', 'nonce' );

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

            $post_id = isset( $_POST['post_id'] ) ? absint( wp_unslash( $_POST['post_id'] ) ) : 0;

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

            wp_delete_post( $post_id, true );

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