<?php
/**
 * Notes ajax class.
 *
 * @package tripzzy
 */

namespace Tripzzy\Core\Ajax;

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;
use Tripzzy\Core\Traits\SingletonTrait;
use Tripzzy\Core\Http\Request;
use Tripzzy\Core\Http\Nonce;
use Tripzzy\Core\Bookings;
use Tripzzy\Core\Helpers\Strings;

if ( ! class_exists( 'Tripzzy\Core\Ajax\NotesAjax' ) ) {
	/**
	 * Notes Ajax Class.
	 *
	 * @since 1.1.8
	 */
	class NotesAjax {
		use SingletonTrait;

		/**
		 * All available strings.
		 *
		 * @var array
		 */
		private $strings;

		/**
		 * Constructor.
		 */
		public function __construct() {
			$this->strings = Strings::messages();
			add_action( 'wp_ajax_tripzzy_add_booking_note', array( $this, 'add_booking_note' ) );
			add_action( 'wp_ajax_nopriv_tripzzy_add_booking_note', array( $this, 'add_booking_note' ) );

			add_action( 'wp_ajax_tripzzy_delete_booking_note', array( $this, 'delete_booking_note' ) );
			add_action( 'wp_ajax_nopriv_tripzzy_delete_booking_note', array( $this, 'delete_booking_note' ) );
		}

		/**
		 * Ajax Callback to add new note.
		 *
		 * @since 1.3.4 Used tripzzy_get_booking_note_list_item function to get the note HTML.
		 * @since 1.1.8
		 */
		public function add_booking_note() {
			if ( ! Nonce::verify() ) {
				$message = array(
					'message' => $this->strings['nonce_verification_failed'],
				);
				wp_send_json_error( $message );
			}
			$data              = Request::sanitize_input( 'INPUT_PAYLOAD' );
			$booking_id        = $data['booking_id'] ?? 0;
			$booking_note      = $data['booking_note'] ?? '';
			$booking_note_type = $data['booking_note_type'] ?? '';
			$is_guest_note     = 'guest' === $booking_note_type ? 1 : 0;

			$comment_id = Bookings::add_note( $booking_id, $booking_note, $is_guest_note, true );
			$note       = Bookings::get_note( $comment_id );

			$response = array(
				'note' => Strings::trim_nl( tripzzy_get_booking_note_list_item( $note ) ),
			);
			wp_send_json_success( $response );
		}

		/**
		 * Ajax Callback to delete note.
		 *
		 * @since 1.1.8
		 */
		public function delete_booking_note() {
			if ( ! Nonce::verify() ) {
				$message = array(
					'message' => $this->strings['nonce_verification_failed'],
				);
				wp_send_json_error( $message );
			}
			$data = Request::sanitize_input( 'INPUT_PAYLOAD' );

			$note_id = $data['note_id'] ?? 0;

			Bookings::delete_note( $note_id );

			$response = array(
				'note_id' => $note_id,
			);
			wp_send_json_success( $response );
		}
	}

	NotesAjax::instance();
}
