<?php

namespace AcademyProCourseBundle\Ajax;

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

use Academy\Classes\AbstractAjaxHandler;
use Academy\Classes\Sanitizer;

class Woocommerce extends AbstractAjaxHandler {
	protected $namespace = 'academy_pro_woo';
	public function __construct() {
		$this->actions = array(
			'create_or_update_course_bundle' => array(
				'callback' => array( $this, 'create_or_update_course_bundle' ),
				'capability' => 'manage_academy_instructor',
			),
			'get_bundle_product' => array(
				'callback' => array( $this, 'get_bundle_product' ),
				'capablity' => 'manage_academy_instructor',
			)
		);
	}

	public function create_or_update_course_bundle( $payload_data ) {
		$payload = Sanitizer::sanitize_payload([
			'id'                => 'integer',
			'title'             => 'string',
			'slug'              => 'string',
			'payment_id'        => 'integer',
			'regular_price'     => 'string',
			'sale_price'        => 'string',
		], $payload_data );

		$bundle_id = (int) isset( $payload['id'] ) ? $payload['id'] : 0;
		$product_id = isset( $payload['payment_id'] ) ? $payload['payment_id'] : 0;
		$bundle_title = isset( $payload['title'] ) ? $payload['title'] : '';
		$bundle_slug = isset( $payload['slug'] ) ? $payload['slug'] : '';
		$regular_price = isset( $payload['regular_price'] ) ? $payload['regular_price'] : '';
		$sale_price = isset( $payload['sale_price'] ) ? $payload['sale_price'] : '';
		$exist_product = get_post_meta( $bundle_id, 'academy_course_product_id', true );
		if ( $exist_product > 0 ) {
			$product_id = $exist_product;
		}
		// that's CRUD object
		$product = new \WC_Product_Simple( $product_id );
		$product->set_name( $bundle_title );
		$product->set_slug( $bundle_slug );
		$product->set_regular_price( $regular_price );
		if ( $sale_price ) {
			$product->set_sale_price( $sale_price );
		}
		$product_id = $product->save();

		if ( $product_id ) {
			update_post_meta( $product_id, '_academy_product', 'yes' );
		}
		if ( $bundle_id ) {
			update_post_meta( $bundle_id, 'academy_course_product_id', $product_id );
		}
		$response = [
			'product_id' => $product_id,
		];

		if ( $product->get_regular_price() ) {
			$response['regular_price'] = (float) $product->get_regular_price();
		}
		if ( $product->get_sale_price() ) {
			$response['sale_price'] = (float) $product->get_sale_price();
		}

		wp_send_json_success( $response );
	}

	public function get_bundle_product( $payload_data ) {
		$payload = Sanitizer::sanitize_payload([
			'productId' => 'integer',
		], $payload_data );

		$productId = isset( $payload['productId'] ) ? $payload['productId'] : 0;
		$product = new \WC_Product_Simple( $productId );

		$response = [
			'product_id' => $productId,
		];
		if ( $product->get_regular_price() ) {
			$response['regular_price'] = (float) $product->get_regular_price();
		}
		if ( $product->get_sale_price() ) {
			$response['sale_price'] = (float) $product->get_sale_price();
		}
		wp_send_json_success( $response );
	}
}
