<?php
/**
 * Postomatic deactivation functionality.
 *
 * @package Postomatic
 * @subpackage Core
 * @since      1.0.0
 */

namespace Postomatic\Core;

use Postomatic\Constants;
use Postomatic\Utils;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Handles plugin deactivation functionality.
 *
 * This class contains methods to clean up after the plugin is deactivated
 * including removing options, dropping custom tables, and notifying external services.
 *
 * @since 1.0.0
 */
class Deactivator {

	/**
	 * Deactivates the plugin by cleaning up database entries and notifying API.
	 *
	 * @return void
	 * @since  1.0.0
	 */
	public static function deactivate() {
		self::send_post_to_laravel_deactive_api();
		self::delete_options();
	}

	/**
	 * Deletes plugin options from the WordPress database.
	 *
	 * @return void
	 * @since  1.0.0
	 */
	private static function delete_options() {
		delete_option( Constants::OPTION_CODE );
		delete_option( Constants::OPTION_API_SERVICE_KEY );
		delete_option( Constants::OPTION_API_WP_SECURE_KEY );
	}

	/**
	 * Notifies the external API that the plugin has been deactivated.
	 *
	 * @return mixed Response body on success, false on failure
	 * @since  1.0.0
	 */
	private static function send_post_to_laravel_deactive_api() {

		$base_url = Constants::API_BASE_URL ?? '';
		if ( empty( $base_url ) ) {
			return false;
		}

		$api_url = $base_url . '/api/services/postomatic/deactive';
		$code    = Utils::get_code_option();

		$data = array(
			'name'  => get_bloginfo( 'name' ),
			'url'   => get_site_url(),
			'email' => get_option( 'admin_email' ),
		);

		$args = array(
			'body'    => wp_json_encode( $data ),
			'headers' => array(
				'Content-Type'       => 'application/json',
				'Authorization-Code' => $code,
			),
			'method'  => 'POST',
			'timeout' => 45,
		);

		$response = wp_remote_post( $api_url, $args );

		if ( is_wp_error( $response ) ) {
			return false;
		}

		$response_code = wp_remote_retrieve_response_code( $response );
		$response_body = wp_remote_retrieve_body( $response );

		if ( 200 !== $response_code ) {
			return false;
		}

		return $response_body;
	}
}
