<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
/**
 *
 * Handles forcing a browser download for a generated file.
 */
final class Sifency_File_Downloader {

	public function download_file( $type ) {
		$file_path = Sifency_Demo_Helper::get_filepath( $type );
		$file_name = Sifency_Demo_Helper::get_filename( $type );

		if ( empty( $file_path ) || ! file_exists( $file_path ) ) {
			wp_die( esc_html__( 'File not found. Please generate the file using the "Update" button first.', 'sifency-addons' ) );
		}

		// Set headers to force a download.
		header( 'Content-Description: File Transfer' );
		header( 'Content-Type: application/octet-stream' );
		header( 'Content-Disposition: attachment; filename="' . $file_name . '"' );
		header( 'Expires: 0' );
		header( 'Cache-Control: must-revalidate' );
		header( 'Pragma: public' );
		header( 'Content-Length: ' . filesize( $file_path ) );

		// Clear output buffer.
		flush();

		global $wp_filesystem;
		if ( empty( $wp_filesystem ) ) {
			require_once ABSPATH . 'wp-admin/includes/file.php';
			WP_Filesystem();
		}

		if ( $wp_filesystem ) {
			// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Binary file download, escaping would corrupt the data.
			echo $wp_filesystem->get_contents( $file_path );
		}

		exit;
	}
}
