<?php
declare(strict_types=1);

/**
 * store_pdf.php
 * Erzeugt eine PDF-Einkaufsliste pro Geschäft (nur Artikel mit Menge > 0).
 * Reihenfolge entspricht der Ansicht: sort_order, name.
 */

require __DIR__ . '/auth.php';
requireLogin();

require __DIR__ . '/lib/fpdf.php';

// FPDF nutzt standardmäßig Windows-1252 (kein UTF-8). Daher alles sauber konvertieren.
function pdf_text(string $s): string {
    $out = @iconv('UTF-8', 'Windows-1252//TRANSLIT', $s);
    if ($out === false) {
        // Fallback: ersetze nicht darstellbare Zeichen
        $out = @iconv('UTF-8', 'Windows-1252//IGNORE', $s);
        if ($out === false) {
            $out = $s; // letzter Fallback
        }
    }
    return $out;
}


$storeFile = $_GET['store'] ?? '';
$storeFile = is_string($storeFile) ? trim($storeFile) : '';

if ($storeFile === '' || !preg_match('~^[a-z0-9._-]+\.json$~i', $storeFile)) {
    abort404();
}

// Store aus DB holen
$stmt = $pdo->prepare('SELECT id, name FROM stores WHERE file = :file LIMIT 1');
$stmt->execute([':file' => $storeFile]);
$store = $stmt->fetch();

if (!$store) {
    abort404();
}

$storeId   = (int)$store['id'];
$storeName = (string)$store['name'];

// Artikel holen: Einkaufsliste = Menge > 0
$stmt = $pdo->prepare('
    SELECT name, amount, unit, sort_order
    FROM items
    WHERE store_id = :sid AND amount > 0
    ORDER BY sort_order, name
');
$stmt->execute([':sid' => $storeId]);
$rows = $stmt->fetchAll();

class EKL_PDF extends FPDF
{
    public string $footerText = '';

    public function Footer(): void
    {
        if ($this->footerText === '') return;
        $this->SetY(-12);
        $this->SetFont('Arial','',9);
        $this->SetTextColor(80,80,80);
        $this->Cell(0, 10, pdf_text($this->footerText), 0, 0, 'C');
    }

    /** @return string[] */
    public function wrapText(string $text, float $w): array
    {
        $text = trim(preg_replace('/\s+/', ' ', $text));
        if ($text === '') return [''];

        $words = preg_split('/\s+/', $text) ?: [];
        $lines = [];
        $line = '';

        foreach ($words as $word) {
            $test = ($line === '') ? $word : ($line . ' ' . $word);
            if ($this->GetStringWidth($test) <= $w) {
                $line = $test;
                continue;
            }
            if ($line !== '') $lines[] = $line;
            // Notfalls Wort hart schneiden
            if ($this->GetStringWidth($word) <= $w) {
                $line = $word;
            } else {
                $chunk = '';
                $chars = preg_split('//u', $word, -1, PREG_SPLIT_NO_EMPTY) ?: [];
                foreach ($chars as $ch) {
                    $t = $chunk . $ch;
                    if ($this->GetStringWidth($t) <= $w) {
                        $chunk = $t;
                    } else {
                        if ($chunk !== '') $lines[] = $chunk;
                        $chunk = $ch;
                    }
                }
                $line = $chunk;
            }
        }
        if ($line !== '') $lines[] = $line;
        return $lines ?: [''];
    }
}

$pdf = new EKL_PDF('P', 'mm', 'A4');
$pdf->SetTitle('EKL Einkaufsliste - ' . pdf_text($storeName), true);
$pdf->footerText = '© 2025 MiLe-Dev.com & Michael Lemke';

$pdf->SetMargins(10, 12, 10);
$pdf->AddPage();

$pdf->SetFont('Arial','B',14);
$pdf->Cell(0, 7, pdf_text('EKL Einkaufsliste'), 0, 1, 'L');

$pdf->SetFont('Arial','',12);
$pdf->Cell(0, 6, pdf_text($storeName), 0, 1, 'L');

$pdf->SetFont('Arial','',10);
$pdf->Cell(0, 5, pdf_text('Stand: ' . date('d.m.Y H:i')), 0, 1, 'L');

$pdf->Ln(2);

// Spaltenbreiten (A4: 210mm, bei 10mm Rand bleiben 190mm)
$wName = 120;
$wQty  = 25;
$wUnit = 30;
$wBox  = 15;

$pdf->SetFont('Arial','B',10);
$pdf->SetFillColor(245,245,245);
$pdf->Cell($wName, 7, pdf_text('Artikel'), 1, 0, 'L', true);
$pdf->Cell($wQty, 7, pdf_text('Menge'), 1, 0, 'R', true);
$pdf->Cell($wUnit, 7, pdf_text('Einheit'), 1, 0, 'L', true);
$pdf->Cell($wBox, 7, pdf_text('OK'), 1, 1, 'C', true);

$pdf->SetFont('Arial','',10);
$lineH = 6;

if (!$rows) {
    $pdf->Cell($wName + $wQty + $wUnit + $wBox, 10, pdf_text('Keine Einträge (Menge > 0).'), 1, 1, 'L');
} else {
    foreach ($rows as $r) {
        $name = (string)($r['name'] ?? '');
        $amount = (float)($r['amount'] ?? 0);
        $unit = (string)($r['unit'] ?? '');

        $nameLines = $pdf->wrapText(pdf_text($name), $wName - 2);
        $unitLines = $pdf->wrapText(pdf_text($unit), $wUnit - 2);

        $numLines = max(count($nameLines), count($unitLines), 1);
        $rowH = $numLines * $lineH;

        // Seitenumbruch wenn nötig
        if ($pdf->GetY() + $rowH + 15 > $pdf->GetPageHeight()) {
            $pdf->AddPage();
            // Kopfzeile wiederholen
            $pdf->SetFont('Arial','B',10);
            $pdf->SetFillColor(245,245,245);
            $pdf->Cell($wName, 7, pdf_text('Artikel'), 1, 0, 'L', true);
            $pdf->Cell($wQty, 7, pdf_text('Menge'), 1, 0, 'R', true);
            $pdf->Cell($wUnit, 7, pdf_text('Einheit'), 1, 0, 'L', true);
            $pdf->Cell($wBox, 7, pdf_text('OK'), 1, 1, 'C', true);
            $pdf->SetFont('Arial','',10);
        }

        $x = $pdf->GetX();
        $y = $pdf->GetY();

        // Rahmen
        $pdf->Rect($x, $y, $wName, $rowH);
        $pdf->Rect($x + $wName, $y, $wQty, $rowH);
        $pdf->Rect($x + $wName + $wQty, $y, $wUnit, $rowH);
        $pdf->Rect($x + $wName + $wQty + $wUnit, $y, $wBox, $rowH);

        // Inhalt: Artikel
        $pdf->SetXY($x + 1, $y + 1);
        foreach ($nameLines as $i => $ln) {
            $pdf->Cell($wName - 2, $lineH, $ln, 0, 2, 'L');
        }

        // Menge
        $pdf->SetXY($x + $wName, $y);
        $amountStr = (floor($amount) == $amount) ? (string)(int)$amount : rtrim(rtrim(number_format($amount, 2, ',', ''), '0'), ',');
        $pdf->Cell($wQty, $rowH, pdf_text($amountStr), 0, 0, 'R');

        // Einheit
        $pdf->SetXY($x + $wName + $wQty + 1, $y + 1);
        foreach ($unitLines as $ln) {
            $pdf->Cell($wUnit - 2, $lineH, $ln, 0, 2, 'L');
        }

        // Checkbox
        $boxSize = 6;
        $bx = $x + $wName + $wQty + $wUnit + ($wBox - $boxSize) / 2;
        $by = $y + ($rowH - $boxSize) / 2;
        $pdf->Rect($bx, $by, $boxSize, $boxSize);

        // Nächste Zeile
        $pdf->SetXY($x, $y + $rowH);
    }
}

$filename = 'EKL_' . preg_replace('/[^a-z0-9_-]+/i', '_', pdf_text($storeName)) . '_' . date('Y-m-d') . '.pdf';
header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
$pdf->Output('I', $filename);
