<?php

namespace SoftSAT\Locacao\Model;

use Dompdf\Dompdf;

use HwapX\Core\Library\Db\Sql\Mapper;
use Hwapx\Core\Library\Template;

class Veiculo {
    protected $f3;

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

    public function renderBlueprintPdf($veiculo_id) {
        $db           = $this->f3->get('db');
        $this->mapper = new Mapper($db, 'softsat_locacao_veiculo_detalhe');

        $data = array(
            'veiculo' => $this->mapper->findone(array('id = ?', $veiculo_id))
        );

        if(!$data['veiculo'])
            return null;

        $html = Template::instance()->render('softsat/locacao/veiculo/blueprint.html', null, $data);

        $dompdf = new Dompdf();
        $dompdf->loadHtml($html);

        $dompdf->setPaper('A4', 'portrait');

        $dompdf->render();

        return $dompdf->output();
    }

    public function blueprintPdf($veiculo_id) {
        $directory = $this->f3->get('UPLOADS').'veiculos';

        if(!file_exists($directory)) {
            mkdir($directory, 0755);
        }

        $filename = "$directory/planta_$veiculo_id.pdf";
        $data     = $this->renderBlueprintPdf($veiculo_id);

        if(!$data)
            return null;

        file_put_contents($filename, $data);

        return $filename;
    }
}