<?php

// Exit if accessed directly.
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(); 

		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_readfile.Found
		readfile( $file_path );
		
		exit;
	}
}