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

use TCPDF;

header('Content-Type: application/json');

$input = json_decode(file_get_contents('php://input'), true);
$bolId = $input['bol_id'] ?? null;          // può essere int o uuid (dipende dal tuo schema in uso)
$docId = $input['document_id'] ?? null;     // opzionale: bol_documents.id (uuid)
$copies = (int)($input['copies'] ?? 1);
if ($copies < 1) $copies = 1;

if (!$bolId) {
    http_response_code(400);
    echo json_encode(['ok'=>false,'error'=>'Missing bol_id']);
    exit;
}

/* =========================
   CARICA CAMPI LAYOUT
========================= */
$fields = $pdo->query("
  SELECT *
  FROM bol_fields
  WHERE template_id = 1
  ORDER BY sort_order
")->fetchAll(PDO::FETCH_ASSOC);

/* =========================
   VALORI DOCUMENTO
========================= */
$stmt = $pdo->prepare("SELECT field_id, value FROM bol_values WHERE bol_id = ?");
$stmt->execute([$bolId]);
$valuesByFieldId = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

/* =========================
   MERCI
========================= */
$stmt = $pdo->prepare("
  SELECT description, packages, weight, notes
  FROM bol_items
  WHERE bol_id = ?
  ORDER BY line_no
");
$stmt->execute([$bolId]);
$items = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* =========================
   TROVA PO E DATA (da bol_fields.code)
========================= */
$fieldIdByCode = [];
foreach ($fields as $f) $fieldIdByCode[$f['code']] = $f['id'];

$po = '';
$date = '';

if (isset($fieldIdByCode['customer_po'])) {
    $po = trim($valuesByFieldId[$fieldIdByCode['customer_po']] ?? '');
}
if (isset($fieldIdByCode['date'])) {
    $date = trim($valuesByFieldId[$fieldIdByCode['date']] ?? '');
}

/* fallback */
if ($po === '') $po = 'PO';
if ($date === '') $date = date('Y-m-d');

/* sanitize filename */
$poSafe = preg_replace('/[^A-Za-z0-9_\-]/', '_', $po);
$dateSafe = preg_replace('/[^0-9\-]/', '', $date);

/* =========================
   PATH SALVATAGGIO
========================= */
$year = date('Y');
$month = date('m');

$storageDir = realpath(__DIR__ . '/..') . "/storage/bol/$year/$month";
if (!is_dir($storageDir)) {
    if (!mkdir($storageDir, 0775, true) && !is_dir($storageDir)) {
        http_response_code(500);
        echo json_encode(['ok'=>false,'error'=>'Cannot create storage directory']);
        exit;
    }
}

$fileName = "BOL_{$poSafe}_{$dateSafe}_{$bolId}.pdf";
$absPath = $storageDir . "/" . $fileName;

/* path relativo per DB / link web */
$relativePath = "/smproduce/storage/bol/$year/$month/$fileName";

/* =========================
   PDF SETUP
========================= */
$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetMargins(0,0,0);
$pdf->SetAutoPageBreak(false);
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);

$templateBg = __DIR__ . '/../templates/BILL_OF_LADING_BG.png';
if (!file_exists($templateBg)) {
    http_response_code(500);
    echo json_encode(['ok'=>false,'error'=>'Template PNG not found: templates/BILL_OF_LADING_BG.png']);
    exit;
}

/* =========================
   FUNZIONI HELPER
========================= */
function setFontAndColor(TCPDF $pdf, array $f): void {
    $pdf->SetFont($f['font_family'] ?: 'helvetica', '', $f['font_size'] ?: 9);
    $hex = $f['font_color'] ?: '#000000';
    [$r,$g,$b] = sscanf($hex, "#%02x%02x%02x");
    $pdf->SetTextColor((int)$r,(int)$g,(int)$b);
}

function renderOneCopy(
    TCPDF $pdf,
    string $bgPath,
    array $fields,
    array $valuesByFieldId,
    array $items
): void {

    /* PAGINA 1 */
    $pdf->AddPage();
    $pdf->Image($bgPath, 0, 0, 210, 297);

    /* CAMPI */
    foreach ($fields as $f) {
        $val = $valuesByFieldId[$f['id']] ?? '';
        if ($val === '' || $val === null) continue;

        setFontAndColor($pdf, $f);

        $pdf->SetXY((float)$f['x_mm'], (float)$f['y_mm']);

        if (!empty($f['is_multiline'])) {
            $pdf->MultiCell(
                (float)$f['width_mm'],
                (float)$f['height_mm'],
                $val,
                0,
                $f['align'] ?: 'L',
                false
            );
        } else {
            $pdf->Cell(
                (float)$f['width_mm'],
                (float)$f['height_mm'],
                $val,
                0,
                0,
                $f['align'] ?: 'L'
            );
        }
    }

    /* MERCI MULTIPAGINA */
    $startY = 115;
    $rowH   = 6;
    $maxY   = 265;
    $y = $startY;

    $pdf->SetFont('helvetica', '', 8.5);
    $pdf->SetTextColor(0,0,0);

    foreach ($items as $row) {

        if ($y + $rowH > $maxY) {
            $pdf->AddPage();
            $pdf->Image($bgPath, 0, 0, 210, 297);
            $y = 30;
        }

        // Description (wrapping)
        $pdf->SetXY(15, $y);
        $pdf->MultiCell(120, $rowH, (string)$row['description'], 0, 'L', false);

        // Packages
        $pdf->SetXY(140, $y);
        $pdf->Cell(20, $rowH, (string)$row['packages'], 0, 0, 'R');

        // Weight
        $pdf->SetXY(165, $y);
        $pdf->Cell(30, $rowH, (string)$row['weight'], 0, 0, 'R');

        $y += $rowH;
    }
}

/* =========================
   GENERA COPIE
========================= */
for ($c=1; $c <= $copies; $c++) {
    renderOneCopy($pdf, $templateBg, $fields, $valuesByFieldId, $items);
}

/* =========================
   SALVA FILE
========================= */
$pdfData = $pdf->Output('', 'S');
file_put_contents($absPath, $pdfData);

/* =========================
   UPDATE bol_documents (se possibile)
   - Se docId passato, aggiorna quel record
   - Altrimenti prova a usare bolId come id (nel caso tu lo stia usando come uuid)
========================= */
try {
    $targetId = $docId ?: $bolId;

    $stmt = $pdo->prepare("
      UPDATE bol_documents
      SET generated_pdf = ?,
          status = 'completed',
          completed_at = NOW(),
          copies = ?
      WHERE id = ?
    ");
    $stmt->execute([$relativePath, $copies, $targetId]);
} catch (Throwable $e) {
    // non blocchiamo la generazione se la tabella non è allineata al tuo bol_id attuale
}

/* =========================
   RISPOSTA
========================= */
echo json_encode([
    'ok' => true,
    'path' => $relativePath,
    'url' => $relativePath,
    'copies' => $copies
]);
