<?php
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../lib/fpdf/fpdf.php';

$bolId  = $_GET['bol_id'] ?? null;
$copies = max(1, (int)($_GET['copies'] ?? 1));
if (!$bolId) die('Missing BOL');

/* fields + values + overrides */
$stmt = $pdo->prepare("
SELECT f.*,
       COALESCE(p.font_family,f.font_family) AS font_family,
       COALESCE(p.font_size,f.font_size)     AS font_size,
       COALESCE(p.align,f.align)              AS align,
       COALESCE(p.is_multiline,f.is_multiline) AS is_multiline,
       v.value
FROM bol_fields f
LEFT JOIN bol_values v
  ON v.field_id=f.id AND v.bol_id=?
LEFT JOIN bol_document_field_props p
  ON p.field_id=f.id AND p.bol_id=?
WHERE f.template_id=1
ORDER BY f.sort_order,f.id
");
$stmt->execute([$bolId,$bolId]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* PO for filename */
$stmt = $pdo->prepare("
SELECT v.value
FROM bol_values v
JOIN bol_fields f ON f.id=v.field_id
WHERE v.bol_id=? AND f.code='po'
LIMIT 1
");
$stmt->execute([$bolId]);
$po = trim($stmt->fetchColumn());
$filename = $po ? preg_replace('/[^A-Za-z0-9_-]/','_',$po) : 'BOL';

/* save copies */
$pdo->prepare("
UPDATE bol_documents SET copies=? WHERE id=?
")->execute([$copies,$bolId]);

$pdf = new FPDF('P','mm','A4');

for ($i=0;$i<$copies;$i++){
  $pdf->AddPage();
  $pdf->Image(__DIR__.'/../templates/BILL_OF_LADING_BG.png',0,0,210,297);

  foreach ($rows as $r){
    if ($r['value']==='') continue;

    $pdf->SetFont($r['font_family'] ?: 'Helvetica','',(float)$r['font_size']);
    $pdf->SetXY($r['x_mm'],$r['y_mm']);

    $align = $r['align']==='C'?'C':($r['align']==='R'?'R':'L');

    if ($r['is_multiline']){
      $pdf->MultiCell($r['width_mm'],4,$r['value'],0,$align);
    } else {
      $pdf->Cell($r['width_mm'],$r['height_mm'],$r['value'],0,0,$align);
    }
  }
}

$pdf->Output('I',$filename.'.pdf');
