<?php

namespace Limb_Chatbot\Includes\Integrations\Telegram\Utilities;

use Limb_Chatbot\Includes\Data_Objects\Config;
use Limb_Chatbot\Includes\Exceptions\Exception;
use Limb_Chatbot\Includes\Integrations\Telegram\Endpoints\Webhook\Webhook_Endpoint;
use Limb_Chatbot\Includes\Integrations\Telegram\Telegram;

/**
 * Telegram Webhook Utility
 *
 * Utility for managing Telegram bot webhooks.
 * Handles setting and deleting webhooks for event-based updates.
 *
 * @package Limb_Chatbot\Includes\Integrations\Telegram\Utilities
 * @since 1.0.11
 */
class Webhook_Utility {

	/**
	 * Telegram configuration object.
	 *
	 * @var Config|null
	 * @since 1.0.11
	 */
	public ?Config $config = null;

	/**
	 * Webhook endpoint.
	 *
	 * @var Webhook_Endpoint
	 * @since 1.0.11
	 */
	public Webhook_Endpoint $endpoint;

	/**
	 * Constructor.
	 *
	 * @param Config|null $config Configuration object.
	 *
	 * @since 1.0.11
	 */
	public function __construct( ?Config $config = null ) {
		if ( is_null( $config ) ) {
			$this->config = Config::where( [
				'default'    => true,
				'related_to' => Telegram::$id,
			] )->first();
		} else {
			$this->config = $config;
		}

		$this->endpoint = new Webhook_Endpoint( $this );
	}

	/**
	 * Set webhook for the bot.
	 *
	 * @param string $url          Webhook URL.
	 * @param string $secret_token Secret token for verification.
	 *
	 * @return array Response from Telegram API.
	 * @throws Exception
	 * @since 1.0.11
	 */
	public function set_webhook( string $url, string $secret_token = '' ): array {
		return $this->endpoint->set_webhook( $url, $secret_token );
	}

	/**
	 * Delete webhook for the bot.
	 *
	 * @param bool $drop_pending_updates Whether to drop pending updates.
	 *
	 * @return array Response from Telegram API.
	 * @throws Exception
	 * @since 1.0.11
	 */
	public function delete_webhook( bool $drop_pending_updates = false ): array {
		return $this->endpoint->delete_webhook( $drop_pending_updates );
	}

	/**
	 * Get current webhook info.
	 *
	 * @return array Webhook info from Telegram API.
	 * @throws Exception
	 * @since 1.0.11
	 */
	public function get_webhook_info(): array {
		return $this->endpoint->get_webhook_info();
	}

	/**
	 * Generate a secure secret token for webhook verification.
	 *
	 * @return string Random secret token (1-256 characters, A-Z, a-z, 0-9, _, -).
	 * @since 1.0.11
	 */
	public static function generate_secret_token(): string {
		$characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-';
		$length     = 64;
		$token      = '';

		for ( $i = 0; $i < $length; $i++ ) {
			$token .= $characters[ random_int( 0, strlen( $characters ) - 1 ) ];
		}

		return $token;
	}
}

