<?php

namespace AcademyProStoreEngine\Ajax;

use Academy\Classes\AbstractAjaxHandler;
use StoreEngine\Integrations\IntegrationTrait;

class CourseBundle extends AbstractAjaxHandler {

	use IntegrationTrait;

	protected $namespace = ACADEMY_PRO_PLUGIN_SLUG . '_storeengine';

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

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

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

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

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

	public function save_product( array $payload ) {
		if ( ! isset( $payload['bundle_id'] ) ) {
			wp_send_json_error([
				'message' => esc_html__( 'bundle_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['bundle_id'] ) );
		$this->item_title = isset( $payload['bundle_title'] ) ? sanitize_text_field( $payload['bundle_title'] ) : 'Untitled product for Course Bundle';
		$this->prices = $payload['prices'] ?? [];

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