<?php

namespace App\Repositories\Core;

use Barryvdh\Debugbar\Facades\Debugbar;
use Barryvdh\DomPDF\Facade\Pdf as DomPDF;
use Barryvdh\Snappy\Facades\SnappyPdf;
use GravityMedia\Ghostscript\Ghostscript;
use Imagick;
use Mpdf\Mpdf;
use Spatie\PdfToText\Pdf as PDFToText;
use Symfony\Component\Process\Process;

class PDF
{
    public static function view($view, $data, $filename = 'file.pdf')
    {
        Debugbar::disable();
        $pdf = DomPDF::loadView($view, $data);

        return $pdf->download($filename);
    }

    public static function countPages($filename)
    {
        $image = new Imagick();
        $image->pingImage($filename);

        return $image->getNumberImages();

        /*
        $pdftext = file_get_contents($filename);

        return preg_match_all("/\/Page\W*(\d+)/", $pdftext, $dummy);
        */
    }

    public function getPDFPages($document)
    {
        $cmd = '/path/to/pdfinfo';           // Linux
        $cmd = 'C:\\path\\to\\pdfinfo.exe';  // Windows

        // Parse entire output
        // Surround with double quotes if file name has spaces
        exec("$cmd \"$document\"", $output);

        // Iterate through lines
        $pagecount = 0;
        foreach ($output as $op) {
            // Extract the number
            if (preg_match("/Pages:\s*(\d+)/i", $op, $matches) === 1) {
                $pagecount = intval($matches[1]);
                break;
            }
        }

        return $pagecount;
    }

    public static function getText($filename)
    {
        return PDFToText::getText($filename);
    }

    public static function convertHTML($html)
    {
        $mpdf = new Mpdf();
        $mpdf->WriteHTML($html);

        return $mpdf->Output();
    }

    public static function convertURL($url, $filename = 'sample.pdf')
    {
        $pdf = SnappyPdf::loadFile($url);

        return $pdf->download($filename);
    }

    public static function convertIfNeeded($filename)
    {
        if (self::getVersion($filename) > 1.4) {
            self::downgrade2($filename);
        }
    }

    public static function getVersion($filename)
    {
        $pdf = fopen($filename, 'r');
        if (! $pdf) {
            echo 'error opening the file.';

            return false;
        }
        $lineFirst = fgets($pdf);
        fclose($pdf);
        preg_match_all('!\d+!', $lineFirst, $matches);
        $version = implode('.', $matches[0]);

        return (float) $version;
    }

    public static function downgrade($filename)
    {
        $newFilename = $filename.'-temp';
        $ghostscript = new Ghostscript([
            'quiet' => false,
        ]);

        $device = $ghostscript->createPdfDevice($newFilename);
        $device->setCompatibilityLevel(1.4);
        $process = $device->createProcess($filename);

        $process->run(function ($type, $buffer) {
            if ($type === Process::ERR) {
                throw new \RuntimeException($buffer);
            }
        });

        unlink($filename);
        rename($newFilename, $filename);
    }

    public static function downgrade2($filename)
    {
        $newFilename = $filename.'-temp';
        $options = '-dBATCH -dCompatibilityLevel=1.4 -dNOPAUSE -q -sDEVICE=pdfwrite';
        shell_exec("gs {$options} -sOutputFile=\"{$newFilename}\" \"{$filename}\"");
        unlink($filename);
        rename($newFilename, $filename);
    }
}
