<?php

namespace AcademyProEasyDigitalDownloads\Ajax;

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

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

class Admin extends AbstractAjaxHandler {
	protected $namespace = 'academy_pro_edd';

	public function __construct() {
		$this->actions = array(
			'create_or_update_download' => array(
				'callback' => array( $this, 'edd_create_or_update_download' ),
				'capability' => 'manage_academy_instructor',
			),
		);
	}

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

		$course_id     = (int) isset( $payload['id'] ) ? $payload['id'] : 0;
		$course_title = isset( $payload['title'] ) ? $payload['title'] : '';
		$download_id   = isset( $payload['payment_id'] ) ? $payload['payment_id'] : 0;
		$price = isset( $payload['regular_price'] ) ? $payload['regular_price'] : 0;

		if ( 'undefined' === $course_id || 0 === $course_id ) {
			wp_send_json_error(
				esc_html__( 'Save Course Then Create Download', 'academy-pro' )
			);
		}

		$download_id = get_post_meta( $course_id, 'academy_course_download_id', true );
		$download = new \EDD_Download( $download_id );

		if ( ! $download_id ) {
			$args = [
				'post_type' => 'download',
				'post_status' => 'publish',
				'post_title' => $course_title,
			];
			$download_id = wp_insert_post( $args, true );
			$download = new \EDD_Download( $download_id );
		}

		if ( $download_id ) {
			update_post_meta( $download_id, '_academy_course', 'yes' );
			update_post_meta( $download_id, 'edd_price', $price );
		}

		if ( $course_id ) {
			update_post_meta( $course_id, 'academy_course_download_id', $download_id );
		}
		$response = [
			'download_id' => $download_id,
		];
		if ( $download->get_price() ) {
			$response['regular_price'] = (float) $download->get_price();
		}
		wp_send_json_success( $response );
	}
}
