<?php

namespace App\Utility;
use Knp\Snappy\Pdf;
use mysql_xdevapi\Exception;

class PdfWriter {

    private $binaryPath;

    public function __construct()
    {
        $this->binaryPath = config('snappy.pdf.binary');
    }

    public function createPdfWithConfiguration($data,$file_path) {
        //require WWW_ROOT.'epicvelocity/vendor/autoload.php';
        $html = $data['body_html'];
        $cover_html = isset($data['cover_html']) ? $data['cover_html']:"";
        $page_no_format = "";//Page [page] of [topage]
        if(!empty($data['page_no_format'])){
            $page_no_format = $data['page_no_format'];
        }

        $snappy = new Pdf();
        $snappy->setBinary($this->binaryPath);
        if(!empty($cover_html)){
            $snappy->setOption('cover',$cover_html);
        }
        if(!empty($data['margin'])){
            $snappy->setOption('margin-left', $data['margin']);
            $snappy->setOption('margin-right', $data['margin']);
            $snappy->setOption('margin-top', $data['margin']);
            $snappy->setOption('margin-bottom', $data['margin']);
        }else{
            if(!empty($data['margin_left'])){
                $snappy->setOption('margin-left', $data['margin_left']);
            }

            if(!empty($data['margin_right'])){
                $snappy->setOption('margin-right', $data['margin_right']);
            }

            if(!empty($data['margin_top'])){
                $snappy->setOption('margin-top', $data['margin_top']);
            }

            if(!empty($data['margin_bottom'])){
                $snappy->setOption('margin-bottom', $data['margin_bottom']);
            }
        }

        if(!empty($page_no_format)){
            $snappy->setOption('footer-right', $page_no_format);
        }

        if(!empty($data['footer_left'])){
            $snappy->setOption('footer-left', $data['footer_left']);
        }

        if(!empty($data['header_right'])){
            $snappy->setOption('header-right', $data['header_right']);
        }

        return $snappy->generateFromHtml($html,$file_path,
                array(
                      'encoding' => 'utf-8'

                    )
                );

    }

    public function write($html,$file_path) {

        $snappy = new Pdf();
//        dd($this->binaryPath);

        $snappy->setBinary($this->binaryPath);
        $snappy->setOption('enable-local-file-access', true);
        $snappy->setOption('margin-left', 5);
        $snappy->setOption('footer-right', "Page [page] of [topage]");
        $snappy->generateFromHtml($html,$file_path,array('encoding' => 'utf-8'));
        $snappy->setOption('password', true);
        chmod($file_path, 0664);
        //PDF::loadHTML($html)->setOption('margin-left', 5)->setOption('footer-right', "Page [page] of [topage]")->save($file_path);
//dd($snappy);
        return $snappy;

    }
    public function pdfcreate($html,$file_path){
        //require WWW_ROOT.'epicvelocity/vendor/autoload.php';
        $snappy = new Pdf();
        $snappy->setBinary($this->binaryPath);
        $snappy->setOption('margin-left', 5);
        $snappy->generateFromHtml($html, $file_path, array('encoding' => 'utf-8'));
        $file_url = $file_path;
    }

    public function download($html,$file_path){
        //require WWW_ROOT.'epicvelocity/vendor/autoload.php';
        /*$snappy = new Pdf();
        $snappy->setBinary($this->binaryPath);
        $snappy->setOption('page-size','LETTER');
        $snappy->setOption('encoding', 'UTF-8');

        $snappy->generateFromHtml($html, $file_path, array('encoding' => 'utf-8'));
        */
        PDF::loadHTML($html)->setOption('margin-left', 5)->setOption('footer-right', "Page [page] of [topage]")->save($file_path);
        $file_url = $file_path;
        header('Content-Type: application/octet-stream');
        header("Content-Transfer-Encoding: Binary");
        header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
        readfile($file_url);
        @unlink($file_path);
        //return $file_path;
    }

    public function mpdfWrite($html,$file_path,$file_name,$extra = []){
//        ini_set("pcre.backtrack_limit", "5000000");
//       include(WWW_ROOT."../vendor/mpdf_latest_vendor\vendor\autoload.php");
//        $html  = mb_convert_encoding($html, 'UTF-8', 'UTF-8');

        $mpdf = new \Mpdf\Mpdf(
                  [
                   'default_font_size'          => 12,
                   'default_font'               => 'sans-serif',
                  ]
        );

        $mpdf->SetProtection(array("print"));
        $mpdf->defaultfooterline = false;
        $mpdf->setFooter("Page {PAGENO} of {nb}");
        if(!empty($extra['footer'])){
            $mpdf->defaultfooterline = 0;
            $mpdf->setFooter($extra['footer']);
        }
//        $mpdf->SetVisibility('printonly');
//        $mpdf->SetVisibility('screenonly');
        $html=str_replace('</style>', ' b, strong {font-weight: 700 !important;}.span-ul,.span-blue,.span-large,.cb-br{font-size:14px !important;} .bg-yellow2{font-size:12px !important;} .crTableBackground {font-size:11px !important;} .h1, h1 {font-size:30px !important;}</style>', $html);

        $html=str_replace('<body', '<body style="font-size: 14px; margin-top: 120px;font-family: -webkit-body;color: black;margin-left: 50px;
                                 margin-right: 50px;text-align: justify;"', $html);
//        echo $html;exit;
        $mpdf->WriteHTML(utf8_encode($html));
        $mpdf->Output($file_path.$file_name);

        //$file_name = "invoice_" . $id . ".pdf"; //file name
        //return $file_path;
    }

    public function mpdfdownload($html,$file_path,$file_name, $extra = []){
        ini_set("pcre.backtrack_limit", "5000000");
        include(WWW_ROOT."../vendor/mpdf_latest_vendor\vendor\autoload.php");
        //$html  = mb_convert_encoding($html, 'UTF-8', 'UTF-8');
        $mpdf = new \Mpdf\Mpdf();
        $mpdf->SetProtection(array("print"));
        //$mpdf->SetDisplayMode('fullpage');
        $mpdf->defaultfooterline = 0;
        if(!empty($extra['footer'])){
            $mpdf->setFooter($extra['footer']);
        }
        //echo $html;exit;
        $mpdf->WriteHTML($html);
        //$file_name = "invoice_" . $id . ".pdf"; //file name
        $mpdf->Output($file_name, 'D'); // I=preview, D=download
        @unlink($file_path);
        //return $file_path;
    }

    public static function pdfDownload($file) {
        $file_name = basename($file);
        header('Pragma: public');
        header('Expires: -1');
        header('Cache-Control: public, must-revalidate, post-check=0, pre-check=0');
        header('Content-Transfer-Encoding: binary');
        header("Content-Disposition: attachment; filename=$file_name");
        header("Content-Type: application/zip");
        header("Content-Length: " . filesize($file));
        header("Content-Description: File Transfer");

        if ($fp = fopen($file, 'rb')) {
            ob_end_clean();
            while (!feof($fp) and ( connection_status() == 0)) {
                print(fread($fp, 8192));
                flush();
            }

            @fclose($fp);
        }
        @unlink($file);
    }
    public function snappyImage($html,$file_path) {

//        $snappy = new Pdf();
        $snappy = \App::make('snappy.image');
//        $snappy->setBinary($this->imageBinary);
        $snappy->setOption('width', 500);
        $nameImage=\Str::random(5).'.jpg';
        $snappy->generateFromHtml($html,$file_path.$nameImage);
//        dd('yes');
//        chmod($file_path, 0664);
//        return $snappy;

    }
}
