<?php
/**
 * Postomatic Plugin - Delete Post Handler class.
 *
 * PHP Version 5.6
 *
 * @package  Postomatic
 * @category Plugin
 * @license  GPL-2.0-or-later https://www.gnu.org/licenses/gpl-2.0.html
 * @link     https://buildomatics.com/postomatics
 * @since    1.0.0
 */

namespace Postomatic\Api;

use Postomatic\Constants;
use Postomatic\Utils;

/**
 * Delete Post Handler class.
 *
 * This class handles the delete post functionality.
 *
 * @category Plugin
 * @license  GPL-2.0-or-later https://www.gnu.org/licenses/gpl-2.0.html
 * @link     https://buildomatics.com/postomatics
 * @since    1.0.0
 */
class Delete_Post_Handler {

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_action( 'wp_ajax_postomatic_delete_post', array( $this, 'delete_post' ) );
	}

	/**
	 * Delete post.
	 *
	 * This method handles the delete post request.
	 *
	 * @return void
	 */
	public function delete_post() {
		// Check nonce for security.
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'postomatic_admin_nonce' ) ) {
			wp_send_json_error( array( 'message' => 'Invalid nonce.' ), 403 );

			return;
		}

		// Check if user has permission.
		if ( ! current_user_can( 'edit_posts' ) ) {
			wp_send_json_error( array( 'message' => 'Permission denied' ), 403 );

			return;
		}

		// Get post ID.
		$post_id = isset( $_POST['post_id'] ) ? sanitize_text_field( wp_unslash( $_POST['post_id'] ) ) : 0;
		if ( empty( $post_id ) ) {
			wp_send_json_error( array( 'message' => 'Invalid post ID' ), 400 );

			return;
		}

		// Delete post.
		$result = $this->delete_post_data( $post_id );

		// Check if there was an error.
		if ( isset( $result['error'] ) ) {
			wp_send_json_error( $result['error'], $result['status_code'] );

			return;
		}

		// Return success response.
		wp_send_json_success( $result );
	}

	/**
	 * Delete post data.
	 *
	 * @param  int $post_id The post ID to delete.
	 * @return array The response from the API.
	 */
	private function delete_post_data( $post_id ) {
		// Get API key.
		$api_key = Utils::get_api_service_key();

		// Set API URL.
		$api_url = str_replace( '%postid%', $post_id, Constants::API_POSTS_DELETE );
		// Send request to API.
		$response = wp_remote_request(
			$api_url,
			array(
				'method'      => 'DELETE',
				'timeout'     => 45,
				'redirection' => 5,
				'httpversion' => '1.0',
				'blocking'    => true,
				'headers'     => array(
					'Content-Type' => 'application/json',
					'Api-Key'      => $api_key,
				),
				'cookies'     => array(),
			)
		);

		// Check for errors.
		if ( is_wp_error( $response ) ) {
			return array(
				'error'       => array( 'message' => $response->get_error_message() ),
				'status_code' => 500,
			);
		}

		// Get response code.
		$response_code = wp_remote_retrieve_response_code( $response );

		// Get response body.
		$body   = wp_remote_retrieve_body( $response );
		$result = json_decode( $body, true );
		// Check if response is successful.
		if ( 200 !== $response_code || JSON_ERROR_NONE !== json_last_error() ) {
			return array(
				'error'       => array( 'message' => 'Failed to delete post' ),
				'status_code' => $response_code,
			);
		}

		// Return the result.
		return $result;
	}
}

// Initialize the class.
new Delete_Post_Handler();
