<?php
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../vendor/autoload.php';

use Dompdf\Dompdf;
use Dompdf\Options;

$id = $_GET['id'] ?? '';
if (!$id) die('Missing id');

$stmt = $pdo->prepare("SELECT * FROM bol_documents WHERE id=?");
$stmt->execute([$id]);
$doc = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$doc) die('Document not found');

$stmt = $pdo->prepare("
    SELECT *
    FROM bol_fields
    WHERE template_id=?
    ORDER BY sort_order, id
");
$stmt->execute([$doc['template_id']]);
$fields = $stmt->fetchAll(PDO::FETCH_ASSOC);

$stmt = $pdo->prepare("
    SELECT field_id, value
    FROM bol_values
    WHERE bol_id=?
");
$stmt->execute([$id]);
$values = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

$options = new Options();
$options->set('isRemoteEnabled', true);
$options->set('defaultFont', 'helvetica');
$dompdf = new Dompdf($options);

$bg = realpath(__DIR__ . '/../templates/BILL_OF_LADING_BG.png');

$html = '
<style>
@page { size:A4; margin:0; }
.page {
  position:relative;
  width:210mm;
  height:297mm;
  background:url("'.$bg.'") no-repeat;
  background-size:210mm 297mm;
}
.field {
  position:absolute;
  white-space:pre-wrap;
  font-family:helvetica;
}
</style>
<div class="page">
';

foreach ($fields as $f) {
    $val = $values[$f['id']] ?? '';
    if ($val === '') continue;

    $align = $f['align'] === 'C' ? 'center' : ($f['align'] === 'R' ? 'right' : 'left');

    $html .= '
    <div class="field" style="
      left:'.$f['x_mm'].'mm;
      top:'.$f['y_mm'].'mm;
      width:'.$f['width_mm'].'mm;
      height:'.$f['height_mm'].'mm;
      font-size:'.$f['font_size'].'pt;
      text-align:'.$align.';
    ">'.nl2br($val).'</div>';
}

$html .= '</div>';

$dompdf->loadHtml($html);
$dompdf->render();
$dompdf->stream('BOL_'.$id.'.pdf', ['Attachment'=>false]);
