<?php
/**
 * Plugin activation functionality.
 *
 * @package Postomatic
 * @subpackage Core
 */

namespace Postomatic\Core;

// Class for handling plugin activation.
use Postomatic\Utils;

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

/**
 * Activates the plugin.
 *
 * Creates necessary database tables and notifies the API.
 *
 * @return void
 */
class Activator {

	/**
	 * Activates the plugin.
	 *
	 * Creates necessary database tables and notifies the API.
	 *
	 * @return bool
	 */
	public static function activate() {
		// Store activation info for admin notice.
		update_option( 'postomatic_activation_status', 'Postomatic plugin activated successfully' );

		// Create database table.
		self::create_table();

		// Send data to Laravel API.
		self::send_post_to_laravel_active_api();

		// Preventing multiple redirects after activation.
		set_transient( 'postomatic_do_activation_redirect', true, 30 );

		// Register admin notice hook.
		add_action( 'admin_notices', array( __CLASS__, 'activation_admin_notice' ) );

		return true;
	}


	/**
	 * Display admin notice after activation.
	 *
	 * @return void
	 */
	public static function activation_admin_notice() {
		$message = get_option( 'postomatic_activation_status' );
		if ( $message ) {
			echo '<div class="notice notice-success is-dismissible"><p>' . esc_html( $message ) . '</p></div>';
			delete_option( 'postomatic_activation_status' );
		}

		if ( get_option( 'postomatic_activation_error' ) ) {
			$error_messages = get_option( 'postomatic_activation_error' );
			foreach ( $error_messages as $error ) {
				echo '<div class="notice notice-error is-dismissible"><p>' . esc_html( $error ) . '</p></div>';
			}
			delete_option( 'postomatic_activation_error' );
		}
	}

	/**
	 * Creates the database table needed by the plugin.
	 *
	 * @return void
	 */
	private static function create_table() {
		global $wpdb;

		$table_name = $wpdb->prefix . \Postomatic\Constants::TABLE_TITLES;

		$sql = "CREATE TABLE IF NOT EXISTS $table_name (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            title varchar(255) NOT NULL,
            post_date datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
            PRIMARY KEY (id)
        );";

		include_once ABSPATH . 'wp-admin/includes/upgrade.php';
		dbDelta( $sql );
	}

	/**
	 * Sends activation data to the Laravel API endpoint.
	 *
	 * @return bool|string Response body on success, false on failure.
	 */
	private static function send_post_to_laravel_active_api() {

		$api_base_url = \Postomatic\Constants::API_BASE_URL ?? '';
		if ( empty( $api_base_url ) ) {
			// Store error for admin notice.
			self::add_activation_error( 'API Base URL is not defined' );

			return false;
		}

		$api_url = $api_base_url . '/api/services/postomatic/active';
		$wp_url  = get_site_url();
		$code    = self::generate_secure_key( 120 ); // Refresh Token.
		Utils::update_or_add_code_option( $code );

		$wp_api_secret = self::generate_secure_key( 120 ); // WP API secret.
		Utils::update_or_add_wp_api_secure_key( $wp_api_secret );

		$data = array(
			'url'                 => $wp_url,
			'blog_local_timezone' => wp_timezone_string(),
			'api_endpoint'        => $wp_url . '/wp-json/' . \Postomatic\Constants::API_WP_ENDPOINT_BASE,
			'code'                => $code,
			'wp_api_secret'       => $wp_api_secret,
		);

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

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

		if ( is_wp_error( $response ) ) {
			// Store error for admin notice.
			self::add_activation_error( 'API Request Failed: ' . $response->get_error_message() );

			return false;
		}

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

		if ( 200 !== $response_code ) { // Yoda condition fixed
			// Store errors for admin notice.
			self::add_activation_error( "API Request Failed with code: $response_code" );
			self::add_activation_error( "Response Body: $response_body" );

			return false;
		}

		return $response_body;
	}

	/**
	 * Generates a secure random key.
	 *
	 * @param  int $length Length of the key to generate.
	 * @return string Generated secure key.
	 */
	private static function generate_secure_key( $length ) {
		return bin2hex( random_bytes( $length / 2 ) );
	}

	/**
	 * Add activation error message for admin notice.
	 *
	 * @param  string $message Error message.
	 * @return void
	 */
	private static function add_activation_error( $message ) {
		$errors   = get_option( 'postomatic_activation_error', array() );
		$errors[] = $message;
		update_option( 'postomatic_activation_error', $errors );
	}
}
