<?php

use setasign\Fpdi\Fpdi;

class DModelToolEtiqueta extends ResizeImg
{

  public function __construct($registry)
  {
    $this->registry = $registry;

    $this->setFolder('system/cache/cachefiles');
    $this->setDirpath(DIR_CACHE.'cachefiles/');
  }

  public function filepath($filename)
  {

    if (!file_exists($this->getDirpath() . $filename) || !is_file($this->getDirpath() . $filename)) {
      return;
    }

    return $this->urlloja->link('', '', 'SSL', false) . $this->getFolder() . '/' . $filename;

  }


  public function split($pathEtiqueta){

    $link = array();
    $pdf = new Fpdi();
    $pageCount = $pdf->setSourceFile($pathEtiqueta);
    $file = pathinfo($pathEtiqueta, PATHINFO_FILENAME);

    for ($i = 1; $i <= $pageCount; $i++) {
      $newFilename = sprintf('%s%s_%s.pdf', $this->getDirpath(), $file, $i);
      if(file_exists($newFilename)){
        unlink($newFilename);
      }
      $newPdf = new Fpdi();
      $newPdf->addPage();
      $newPdf->setSourceFile($pathEtiqueta);
      $newPdf->useTemplate($newPdf->importPage($i), ['adjustPageSize' => true]);
      $size = $newPdf->getTemplateSize($newPdf->importPage($i));
      $newPdf->output($newFilename, 'F');
      $newPdf->close();

      $link[] = array(
        'file'        => $this->filepath(sprintf('%s_%s.pdf', $file, $i)),
        'orientation' => $size['orientation']
      );

    }
    unlink($pathEtiqueta);
    return $link;

  }


}
