<?php

namespace AcademyProStoreEngine\Ajax;

use Academy\Classes\AbstractAjaxHandler;
use StoreEngine\Classes\Price;
use StoreEngine\Classes\Product\SimpleProduct;
use StoreEngine\Integrations\IntegrationTrait;
use StoreEngine\Utils\Helper;

class TutorBooking extends AbstractAjaxHandler {

	use IntegrationTrait;

	protected $namespace = ACADEMY_PRO_PLUGIN_SLUG . '_storeengine';

	public function __construct() {
		$this->init_integration();

		$this->actions = array(
			'get_tutor_booking_product' => array(
				'callback' => array( $this, 'get_product' ),
				'capability' => 'manage_academy_instructor',
			),
			'save_tutor_booking_product' => array(
				'callback' => array( $this, 'save_product' ),
				'capability' => 'manage_academy_instructor',
			),
		);
	}

	protected function set_integration_config(): void {
		$this->integration_name = 'storeengine/tutor-booking';
	}

	public function get_product( array $payload ) {
		if ( ! isset( $payload['booking_id'] ) ) {
			wp_send_json_error([
				'message' => esc_html__( 'booking_id is required', 'academy-pro' )
			]);
		}

		$this->item_id = absint( sanitize_text_field( $payload['booking_id'] ) );
		$this->get_integrations();
	}

	public function save_product( array $payload ) {
		if ( ! isset( $payload['booking_id'] ) ) {
			wp_send_json_error([
				'message' => esc_html__( 'booking_id is required', 'academy-pro' )
			]);
		}

		if ( isset( $payload['prices'] ) ) {
			$payload['prices'] = json_decode( $payload['prices'], true );
			if ( ! is_array( $payload['prices'] ) ) {
				wp_send_json_error([
					'message' => 'prices are required'
				]);
			}
		}

		// set the basic payload data
		$this->item_id = absint( sanitize_text_field( $payload['booking_id'] ) );
		$this->item_title = isset( $payload['booking_title'] ) ? sanitize_text_field( $payload['booking_title'] ) : 'Untitled product for Academy Pro Course Bundle';
		$this->prices = $payload['prices'] ?? [];

		$booking_type = get_post_meta( $this->item_id, '_academy_booking_type', true );
		if ( 'paid' !== $booking_type ) {
			update_post_meta( $this->item_id, '_academy_booking_type', 'paid' );
		}

		// handle integrations
		$this->handle_integrations();
		$this->get_integrations();
	}
}
