<?php
/**
 * @package CleverOgre
 * @subpackage woocommerce-download-template
 * @version 0.1.0
 * @since 0.1.0
 */

namespace WooCommerce\DownloadTemplate;

defined('ABSPATH') || exit;

class File {
    use Singleton;

    private $unoconv;
    public function __construct() {
        $this->unoconv = null;
    }

    private function load():bool {
        if (!class_exists('\Unoconv\Unoconv')) return false;
        if (is_null($this->unoconv)) $this->unoconv = \Unoconv\Unoconv::create();
        return true;
    }

    public function convert_to_pdf($path) {
        if (!$this->load()) return $path;

        $path_parts = pathinfo($path);
        $tmp_path = sprintf('%s/%s.pdf', sys_get_temp_dir(), $path_parts['filename']);

        $this->unoconv->transcode($path, 'pdf', $tmp_path);

        return $tmp_path;
    }

    public function output(string $path, bool $download = true) {
        if (!file_exists($path)) {
            wp_die(__('Invalid file path.', Plugin::get_textdomain()));
            exit;
        }

        $path_parts = pathinfo($path);

        header(sprintf('Content-Type: %s', mime_content_type($path)));
        header(sprintf('Content-Length: %d', filesize($path)));
        header(sprintf(
            "Content-Disposition: %s; filename=%s.%s;",
            !!$download ? 'attachment' : 'inline',
            $path_parts['filename'],
            $path_parts['extension']
        ));
        header('Cache-Control: public, must-revalidate, max-age=0');
        header('Pragma: public');
        header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
        header(sprintf('Last-Modified: %s GMT', gmdate('D, d M Y H:i:s')));
        readfile($path);

        exit;
    }

    public function get_path(string $url):string {
        $site_url = str_replace(['http:', 'https:'], '', get_site_url());
        if (strpos($url, $site_url) === false) return $url;
        $url = str_replace(['http:', 'https:'], '', $url);
        $url = ABSPATH . substr($url, strlen($site_url));
        $url = str_replace('//', '/', $url);
        return $url;
    }

}
