<?php
/**
 * Pdf main class file.
 *
 * This class handles all PDF-related functionality including file uploads,
 * DOCX processing, smart tag extraction, and PDF conversion.
 *
 * @since 1.9.0
 * @package sureforms-pro
 */

namespace SRFM_Pro\Inc\Business\Pdf;

use SRFM\Inc\Helper;
use SRFM_Pro\Inc\Helper as Pro_Helper;
use SRFM_Pro\Inc\Traits\Get_Instance;

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;

/**
 * Load Pdf feature related functionalities.
 *
 * This class provides methods for handling PDF operations including:
 * - File uploads and processing
 * - Smart tag extraction from DOCX files
 * - PDF conversion and generation
 * - Template processing with smart tags
 *
 * @since 1.9.0
 */
class Pdf {
	use Get_Instance;

	/**
	 * Check if the library exists.
	 *
	 * @var bool
	 */
	public $is_library_exists = false;

	/**
	 * Initialize Pdf.
	 *
	 * @since 1.9.0
	 */
	public function __construct() {
		$this->is_library_exists = Utils::check_if_library_exists();

		// Backend action hooks.
		add_action( 'enqueue_block_editor_assets', [ $this, 'enqueue_block_editor_scripts' ] );
		add_action( 'srfm_register_additional_post_meta', [ $this, 'register_pdf_meta' ] );
		add_action( 'wp_ajax_download_github_library', [ $this, 'download_github_library' ] );
		add_action( 'wp_ajax_delete_pdf_library', [ $this, 'delete_pdf_library' ] );
		add_action( 'srfm_pro_before_deleting_entry', [ $this, 'delete_pdf_files' ], 10, 1 );

		add_action( 'srfm_after_entry_notes', [ $this, 'render_pdf_link_in_entry_notes' ], 10, 1 );
		add_filter( 'srfm_before_entry_data', [ $this, 'add_pdf_link_in_entry' ], 10, 2 );
		// Add filter for the modified meta data.
		add_filter( 'rest_prepare_sureforms_form', [ $this, 'filter_pdf_meta_in_rest' ], 10, 1 );

		// Frontend action hooks.
		if ( $this->is_library_exists ) {
			add_filter( 'srfm_after_submit_confirmation_message', [ $this, 'filter_confirmation_message' ], 10, 3 );
			add_filter( 'srfm_email_notification', [ $this, 'filter_email_notification' ], 10, 4 );
			add_filter( 'srfm_smart_tag_view_link', [ $this, 'filter_smart_tag_view_link' ], 10, 2 );
		}
	}

	/**
	 * AJAX callback to download and extract a GitHub ZIP library using WordPress APIs.
	 *
	 * @since 1.9.0
	 * @return void
	 */
	public function download_github_library() {
		// Check nonce for security.
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'srfm_pdf_nonce' ) ) {
			wp_send_json_error( [ 'message' => __( 'Security check failed.', 'sureforms-pro' ) ] );
		}

		require_once ABSPATH . 'wp-admin/includes/file.php';
		require_once ABSPATH . 'wp-admin/includes/misc.php';
		require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';

		$url      = 'https://raw.githubusercontent.com/brainstormforce/sureforms-libraries/master/pdf.zip';
		$tmp_file = download_url( $url );

		if ( is_wp_error( $tmp_file ) ) {
			wp_send_json_error(
				[
					'message' => __( 'Unable to download the PDF library. Please check your internet connection or try again later.', 'sureforms-pro' ),
				]
			);
		}

		WP_Filesystem();
		global $wp_filesystem;

		$plugin_dir      = WP_PLUGIN_DIR;
		$library_root    = $plugin_dir . '/sureforms-libraries';
		$pdf_folder_path = $library_root;

		// Step 1: Create root library folder if it doesn't exist.
		if ( ! $wp_filesystem->is_dir( $library_root ) ) {
			if ( ! $wp_filesystem->mkdir( $library_root ) ) {
				wp_send_json_error(
					[
						'message' => __( 'Unable to create the root library directory. Please check folder permissions.', 'sureforms-pro' ),
					]
				);
			}
		}

		// Step 2: Clean up existing PDF folder.
		if ( $wp_filesystem->is_dir( $pdf_folder_path ) ) {
			if ( ! $wp_filesystem->delete( $pdf_folder_path, true ) ) {
				wp_send_json_error(
					[
						'message' => __( 'Unable to remove the existing PDF library folder. Please check permissions.', 'sureforms-pro' ),
					]
				);
			}
		}

		// Step 3: Create PDF folder for extraction.
		if ( ! $wp_filesystem->mkdir( $pdf_folder_path ) ) {
			wp_send_json_error(
				[
					'message' => __( 'Failed to prepare the PDF library folder. Make sure your server has proper write permissions.', 'sureforms-pro' ),
				]
			);
		}

		// Step 4: Extract ZIP contents.
		$result = unzip_file( $tmp_file, $pdf_folder_path );
		unlink( $tmp_file );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error(
				[
					'message' => sprintf(
						/* translators: %s: Error message from the exception */
						__( 'Failed to extract the PDF library: %s', 'sureforms-pro' ),
						$result->get_error_message()
					),
				]
			);
		}

		// Get the base upload directory using WordPress API.
		$upload_dir = wp_upload_dir();
		$temp_dir   = trailingslashit( $upload_dir['basedir'] ) . 'sureforms/temp';

		// Create the temp directory if it doesn't exist.
		if ( ! file_exists( $temp_dir ) ) {
			wp_mkdir_p( $temp_dir );
		}

		wp_send_json_success(
			[
				'message' => __( 'PDF library downloaded and installed successfully.', 'sureforms-pro' ),
			]
		);
	}

	/**
	 * AJAX callback to delete the sureforms-libraries folder.
	 *
	 * @since 1.9.0
	 * @return void
	 */
	public function delete_pdf_library() {
		// Check nonce for security.
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'srfm_pdf_nonce' ) ) {
			wp_send_json_error( [ 'message' => __( 'Security check failed.', 'sureforms-pro' ) ] );
		}

		require_once ABSPATH . 'wp-admin/includes/file.php';

		WP_Filesystem();
		global $wp_filesystem;

		$plugin_dir   = WP_PLUGIN_DIR;
		$library_root = $plugin_dir . '/sureforms-libraries';

		// Check if the library folder exists.
		if ( ! $wp_filesystem->is_dir( $library_root ) ) {
			wp_send_json_error(
				[
					'message' => __( 'PDF library folder does not exist.', 'sureforms-pro' ),
				]
			);
		}

		// Delete the entire sureforms-libraries folder.
		if ( ! $wp_filesystem->delete( $library_root, true ) ) {
			wp_send_json_error(
				[
					'message' => __( 'Unable to delete the PDF library folder. Please check folder permissions.', 'sureforms-pro' ),
				]
			);
		}

		wp_send_json_success(
			[
				'message' => __( 'PDF library deleted successfully.', 'sureforms-pro' ),
			]
		);
	}

	/**
	 * Register additional post meta for PDF.
	 * This function registers a custom meta key `_srfm_pdf_meta` for storing PDF related data.
	 *
	 * @hook srfm_register_additional_post_meta
	 *
	 * @since 1.9.0
	 * @return void
	 */
	public function register_pdf_meta() {
		register_post_meta(
			'sureforms_form',                  // Object type (post).
			'_srfm_pdf_meta',         // Your custom meta key.
			[
				'type'              => 'string',  // Will store as JSON string.
				'single'            => true,    // Store as single value.
				'show_in_rest'      => [
					'schema' => [
						'type'    => 'string',
						'context' => [ 'edit' ],
					],
				],
				'sanitize_callback' => [ Utils::class, 'pdf_array_sanitizer' ],
				'auth_callback'     => static function () {
					return Helper::current_user_can(); // Permissions.
				},
			]
		);
	}

	/**
	 * Enqueue Admin Scripts.
	 *
	 * @since 1.9.0
	 * @return void
	 */
	public function enqueue_block_editor_scripts() {
		$script = [
			'unique_file'        => 'srfmPdf',
			'unique_handle'      => 'srfm-pdf',
			'extra_dependencies' => [],
		];

		$script_dep_path = SRFM_PRO_DIR . 'dist/package/business/' . $script['unique_file'] . '.asset.php';
		$script_dep_data = file_exists( $script_dep_path )
			? include $script_dep_path
			: [
				'dependencies' => [],
				'version'      => SRFM_PRO_VER,
			];
		$script_dep      = array_merge( $script_dep_data['dependencies'], $script['extra_dependencies'] );

		// Scripts.
		wp_enqueue_script(
			SRFM_PRO_SLUG . '-' . $script['unique_handle'], // Handle.
			SRFM_PRO_URL . 'dist/package/business/' . $script['unique_file'] . '.js',
			$script_dep, // Dependencies, defined above.
			$script_dep_data['version'], // SRFM_VER.
			true // Enqueue the script in the footer.
		);

		// Localize the srfmPDFData.nonce, ajaxurl, and srfmPDFData.ajaxurl.
		wp_localize_script(
			SRFM_PRO_SLUG . '-' . $script['unique_handle'],
			'srfmPDFData',
			[
				'nonce'                 => wp_create_nonce( 'srfm_pdf_nonce' ),
				'ajaxUrl'               => admin_url( 'admin-ajax.php' ),
				'library_exists'        => $this->is_library_exists,
				'editor_default_styles' => Utils::editor_default_styles(),
			]
		);

		wp_enqueue_editor();

		// Register script translations.
		Pro_Helper::register_script_translations( SRFM_PRO_SLUG . '-' . $script['unique_handle'] );
	}

	/**
	 * Filter PDF meta data in REST response.
	 *
	 * @param \WP_REST_Response $response The response object.
	 *
	 * @since 1.9.0
	 * @return \WP_REST_Response The filtered response object.
	 */
	public function filter_pdf_meta_in_rest( $response ) {
		if ( ! $response instanceof \WP_REST_Response ) {
			return $response;
		}

		if ( ! $this->is_library_exists ) {
			return $response;
		}

		$data = $response->get_data();
		if ( ! is_array( $data ) ) {
			return $response;
		}

		if ( isset( $data['meta']['_srfm_pdf_meta'] ) && ! empty( $data['meta']['_srfm_pdf_meta'] ) ) {
			$data['meta']['_srfm_pdf_meta'] = Utils::filter_pdf_meta_retrieval( $data['meta']['_srfm_pdf_meta'] );
			$response->set_data( $data );
		}

		return $response;
	}

	/**
	 * Filter the confirmation message to handle PDF generation and email processing.
	 *
	 * @param string $confirmation_message The confirmation message.
	 * @param array  $form_data Form submission data.
	 * @param array  $submission_data Additional submission data.
	 *
	 * @since 1.9.0
	 * @return string Modified confirmation message.
	 */
	public function filter_confirmation_message( $confirmation_message, $form_data, $submission_data ) {
		if ( empty( $form_data ) || empty( $form_data['form-id'] ) ) {
			return $confirmation_message;
		}

		return Utils::process_pdf_link( $confirmation_message, $form_data, $submission_data );
	}

	/**
	 * Filter the email notification to handle PDF generation and email processing.
	 *
	 * @param array $email_notification The email notification.
	 * @param array $submission_data Additional submission data.
	 * @param array $item The item.
	 * @param array $form_data Form submission data.
	 *
	 * @since 1.9.0
	 * @return array Modified email notification.
	 */
	public function filter_email_notification( $email_notification, $submission_data, $item, $form_data ) {
		if ( empty( $email_notification ) || ! is_array( $email_notification ) || ! is_array( $item ) || ! is_array( $form_data ) ) {
			return $email_notification;
		}

		// Process the pdf link in the $email_notification.message.
		if ( isset( $email_notification['message'] ) && is_string( $email_notification['message'] ) ) {
			$email_notification['message'] = Utils::process_pdf_link( $email_notification['message'], $form_data, $submission_data );
		}

		return $email_notification;
	}

	/**
	 * Add PDF link in entry.
	 *
	 * @param array $entries_data The entry data.
	 * @param array $args The arguments.
	 *
	 * @since 1.9.0
	 * @return array
	 */
	public function add_pdf_link_in_entry( $entries_data, $args ) {
		if ( empty( $entries_data ) || ! is_array( $entries_data ) ) {
			return $entries_data;
		}

		$pdf_links = Utils::process_pdf_link_in_entry( $args );

		if ( empty( $pdf_links ) ) {
			return $entries_data;
		}

		$get_extra_data              = $entries_data['extras'] ?? [];
		$get_extra_data['pdf_links'] = $pdf_links;

		$entries_data['extras'] = $get_extra_data;

		return $entries_data;
	}

	/**
	 * Delete PDF files.
	 *
	 * @param array $entry The entry data.
	 *
	 * @since 1.9.0
	 * @return void
	 */
	public function delete_pdf_files( $entry ) {
		if ( empty( $entry['extras']['pdf_links'] ) || ! is_array( $entry['extras']['pdf_links'] ) ) {
			return;
		}

		foreach ( $entry['extras']['pdf_links'] as $pdf_link ) {
			if ( ! empty( $pdf_link ) ) {
				Pro_Helper::delete_upload_file_from_subdir( $pdf_link, 'sureforms/pdfs/' );
			}
		}
	}

	/**
	 * Filters the smart tag view link to render base64-encoded image if applicable.
	 *
	 * @param string $view_link Original view link output.
	 * @param array  $args      Arguments including submission data and config.
	 *
	 * @return string Modified view link or an <img> tag if base64 image is detected.
	 */
	public function filter_smart_tag_view_link( $view_link, $args ) {
		// Validate form data.
		if ( empty( $args['form_data'] ) || ! is_array( $args['form_data'] ) ) {
			return $view_link;
		}

		// Validate required config flag.
		if ( empty( $args['form_data']['pdf_generation'] ) ) {
			return $view_link;
		}

		// Validate the submission item key.
		if ( empty( $args['submission_item_key'] ) || 0 !== strpos( $args['submission_item_key'], 'srfm-signature-' ) ) {
			return $view_link;
		}

		$submission_item_key = $args['submission_item_key'];

		$form_data = $args['form_data'];

		// Check if the submission value exists and is a base64 image.
		if ( empty( $form_data[ $submission_item_key ] ) ) {
			return $view_link;
		}

		$submission_item_value = $form_data[ $submission_item_key ];

		// Verify base64-encoded image string.
		if ( is_string( $submission_item_value ) && preg_match( '/^data:image\/(png|jpeg|jpg|gif);base64,[A-Za-z0-9+\/=]+$/', $submission_item_value ) ) {
			// Return a safe image tag (with fixed width for safety, optional).
			ob_start();
			?>
			<img src="<?php echo esc_attr( $submission_item_value ); ?>" alt="<?php esc_attr_e( 'Signature Image', 'sureforms-pro' ); ?>" style="max-width: 100%; height: auto;" />
			<?php
			$view_link = ob_get_clean();
			$view_link = is_string( $view_link ) ? $view_link : '';
		}

		return $view_link;
	}

	/**
	 * Render PDF link in entry notes.
	 *
	 * @param array $entry The entry data.
	 *
	 * @since 1.9.0
	 * @return void
	 */
	public function render_pdf_link_in_entry_notes( $entry ) {
		if ( empty( $entry['extras']['pdf_links'] ) || ! is_array( $entry['extras']['pdf_links'] ) ) {
			return;
		}

		?>
		<div id="submitdiv" class="postbox entry-notes">
			<div class="postbox-header">
				<h2><?php esc_html_e( 'PDF Files', 'sureforms-pro' ); ?></h2>
			</div>
			<div class="inside">
				<div class="srfm-entry-note-wrapper">
					<table style="border-collapse: separate; border-spacing: 5px 5px;">
						<tbody>
							<?php foreach ( $entry['extras']['pdf_links'] as $pdf_name => $pdf_link ) { ?>
								<tr>
									<td style="width: 100%;"><b><?php echo esc_html( $pdf_name ); ?></b></td>
									<td style="white-space: nowrap;"><a style="display: inline-block;" href="<?php echo esc_url( $pdf_link ); ?>" target="_blank"><svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M17.5 12.5V15.8333C17.5 16.2754 17.3244 16.6993 17.0118 17.0118C16.6993 17.3244 16.2754 17.5 15.8333 17.5H4.16667C3.72464 17.5 3.30072 17.3244 2.98816 17.0118C2.67559 16.6993 2.5 16.2754 2.5 15.8333V12.5" stroke="#D54407" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M5.8335 8.33398L10.0002 12.5007L14.1668 8.33398" stroke="#D54407" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M10 12.5V2.5" stroke="#D54407" stroke-linecap="round" stroke-linejoin="round"/>
</svg></a></td>
								</tr>
							<?php } ?>
						</tbody>
					</table>
				</div>
			</div>
		</div>
		<?php
	}
}
