<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\File;
use Symfony\Component\Console\Output\Output;


class Librilladora extends Model {
    use HasFactory;

    public function procesar($fileName, $size) {
        $file = 'uploads/'.$fileName;

        $mpdf = new \Mpdf\Mpdf([
            'format' => 'A4-L',
            'margin_left' => 0,
            'margin_right' => 0,
            'margin_top' => 0,
            'margin_bottom' => 0,
            'margin_header' => 0,
            'margin_footer' => 0,
        ]);

        // DIVIDIR EL DOCUMENTO Y BOOKLETEAR LAS DIVISIONES
        $pageCount = $mpdf->SetSourceFile($file);
        $cantBooklets = ($pageCount / $size);
        for ($i = 0; $i < $cantBooklets; $i++) {
            $comienzo = ($size*$i)+1;
            $fin = ($size*($i+1) < $pageCount) ? $size*($i+1) : $pageCount;
            $docAux = new \Mpdf\Mpdf();
            $docAux->SetSourceFile($file);
            for ($j = $comienzo; $j <= $fin; $j++) {
                $tplId = $docAux->importPage($j);
                $docAux->useTemplate($tplId);
                if ($j != $fin) $docAux->AddPage();
            }
            $docAux->Output('uploads/'.$i."-".$fileName, \Mpdf\Output\Destination::FILE);
            $this->librillar('uploads/', $i."-".$fileName);
        }

        // MERGEAR LAS DIVISIONES
        $fileNames = array();
        for ($i = 0; $i < $cantBooklets; $i++)
            array_push($fileNames, 'uploads/librillo-'.$i."-".$fileName);
        $this->mergePDFFiles($fileNames);
    }


    private function librillar($dir, $filename) {
        $mpdf = new \Mpdf\Mpdf([
        'format' => 'A4-L',
        'margin_left' => 0,
        'margin_right' => 0,
        'margin_top' => 0,
        'margin_bottom' => 0,
        'margin_header' => 0,
        'margin_footer' => 0,
    ]);

        $pw = $mpdf->w / 2;
        $ph = $mpdf->h;

        $mpdf->SetDisplayMode('fullpage');

        $pagecount = $mpdf->SetSourceFile($dir.$filename);
        $pp = $this->GetBookletPages($pagecount);

        foreach ($pp as $v) {

            $mpdf->AddPage();

            if ($v[0] > 0 && $v[0] <= $pagecount) {
                $tplIdx = $mpdf->ImportPage($v[0]); //, 0, 0, $ow, $oh
                $mpdf->UseTemplate($tplIdx, 0, 0, $pw, $ph);
            }

            if ($v[1] > 0 && $v[1] <= $pagecount) {
                $tplIdx = $mpdf->ImportPage($v[1]); //, 0, 0, $ow, $oh
                $mpdf->UseTemplate($tplIdx, $pw, 0, $pw, $ph);
            }
        }

        $mpdf->Output($dir.'librillo-'.$filename, \Mpdf\Output\Destination::FILE);
    }


    private function GetBookletPages($np, $backcover = true) {
        $lastpage = $np;
        $np = 4 * ceil($np / 4);
        $pp = [];

        for ($i = 1; $i <= $np / 2; $i++) {

            $p1 = $np - $i + 1;

            if ($backcover) {
                if ($i == 1) {
                    $p1 = $lastpage;
                } elseif ($p1 >= $lastpage) {
                    $p1 = 0;
                }
            }

            $pp[] = ($i % 2 == 1) ?
                [ $i, $p1 ] : [ $p1,  $i ];
        }

        return $pp;
    }

    function mergePDFFiles(Array $filenames) {
        $mpdf = new \Mpdf\Mpdf([
            'format' => 'A4-L',
            'margin_left' => 0,
            'margin_right' => 0,
            'margin_top' => 0,
            'margin_bottom' => 0,
            'margin_header' => 0,
            'margin_footer' => 0,
        ]);

        if ($filenames) {

            $filesTotal = sizeof($filenames);
            $fileNumber = 1;

            foreach ($filenames as $fileName) {
                if (file_exists($fileName)) {
                    $pagesInFile = $mpdf->SetSourceFile($fileName);
                    for ($i = 1; $i <= $pagesInFile; $i++) {
                        $tplId = $mpdf->ImportPage($i); // in mPdf v8 should be 'importPage($i)'
                        $mpdf->UseTemplate($tplId);
                        if (($fileNumber < $filesTotal) || ($i != $pagesInFile)) {
                            $mpdf->WriteHTML('<pagebreak />');
                        }
                    }
                }
                $fileNumber++;
            }

            $mpdf->Output();
        }
    }
}

