<?php

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

declare(strict_types=1);

ob_start(); // keine Ausgabe vor den PDF-Headern
require __DIR__ . '/../lib/fpdf.php';

// -------- Daten laden --------
$dataDir   = __DIR__ . '/../data/';
$storeParam = $_GET['store'] ?? null;

if ($storeParam === null) {
    http_response_code(400);
    exit('Fehler: Parameter "store" fehlt.');
}

$storeFile = basename((string)$storeParam);                  // Path Traversal verhindern
$jsonPath  = $dataDir . $storeFile;

if (!is_file($jsonPath)) {
    http_response_code(404);
    exit('Keine Artikel gefunden oder Datei existiert nicht.');
}

$articles = json_decode(file_get_contents($jsonPath), true);
if (!is_array($articles)) {
    http_response_code(500);
    exit('Fehler: JSON-Datei ist ungültig.');
}

// Anzeigename ohne .json
$storeName = ucfirst(pathinfo($storeFile, PATHINFO_FILENAME));

// Helper für FPDF-Encoding (Umlaute)
$enc = static function (string $s): string {
    // FPDF unterstützt ISO-8859-1; //TRANSLIT vermeidet harte Fehler
    return iconv('UTF-8', 'ISO-8859-1//TRANSLIT', $s);
};

// -------- PDF-Klasse --------
class PDF extends FPDF {
    public string $storeName = '';

    function Header(): void {
        $this->SetFont('Arial', 'B', 16);
        $this->Cell(0, 10, $this->storeName, 0, 1, 'C');
        $this->Ln(10);
    }

    function Footer(): void {
    $this->SetY(-15);
    $this->SetFont('Arial', 'I', 8);
    $raw  = 'Seite ' . $this->PageNo() . ' - © ' . date('Y') . ' by MiLe-Dev.com';
    $text = iconv('UTF-8', 'ISO-8859-1//TRANSLIT', $raw);
    $this->Cell(0, 10, $text, 0, 0, 'C');
    }
}

// -------- PDF aufbauen --------
$pdf = new PDF();
$pdf->storeName = $enc('Einkaufsliste: ' . $storeName);
$pdf->SetAutoPageBreak(true, 10);
$pdf->AddPage();

// Tabellenkopf
$pdf->SetFont('Arial', 'B', 12);
$pdf->SetFillColor(200, 200, 200);
$pdf->Cell(10, 10, '',              1, 0, 'C', true); // optionaler Platzhalter/Checkbox
$pdf->Cell(60, 10, $enc('Artikel'), 1, 0, 'C', true);
$pdf->Cell(30, 10, $enc('Menge'),   1, 0, 'C', true);
$pdf->Cell(30, 10, $enc('Einheit'), 1, 0, 'C', true);
$pdf->Cell(30, 10, $enc('Preis (EUR)'), 1, 0, 'C', true);
$pdf->Cell(30, 10, $enc('Summe (EUR)'), 1, 1, 'C', true);

// Tabellenzeilen
$pdf->SetFont('Arial', '', 12);
$totalSum = 0.0;
$fill = false;

if (count($articles) > 0) {
    foreach ($articles as $article) {
        $name   = isset($article['name'])   ? $enc((string)$article['name'])   : '';
        $amount = isset($article['amount']) ? (float)$article['amount']        : 0.0;
        $unit   = isset($article['unit'])   ? $enc((string)$article['unit'])   : '';
        $priceV = isset($article['price'])  ? (float)$article['price']         : 0.0;

        $sumV   = $amount * $priceV;
        $totalSum += $sumV;

        $priceS = number_format($priceV, 2, ',', '.');
        $sumS   = number_format($sumV,   2, ',', '.');

        $pdf->SetFillColor($fill ? 230 : 255, $fill ? 230 : 255, $fill ? 230 : 255);
        $pdf->Cell(10, 10, '',     1, 0, 'C', $fill);
        $pdf->Cell(60, 10, $name,  1, 0, 'L', $fill);
        $pdf->Cell(30, 10, $enc((string)($amount)), 1, 0, 'C', $fill);
        $pdf->Cell(30, 10, $unit,  1, 0, 'C', $fill);
        $pdf->Cell(30, 10, $enc($priceS . ' EUR'), 1, 0, 'C', $fill);
        $pdf->Cell(30, 10, $enc($sumS   . ' EUR'), 1, 1, 'C', $fill);

        $fill = !$fill;
    }
} else {
    $pdf->Cell(190, 10, $enc('Keine Artikel vorhanden.'), 1, 1, 'C');
}

// Gesamtsumme
$pdf->SetFont('Arial', 'B', 12);
$pdf->Cell(160, 10, $enc('Gesamtsumme:'), 1, 0, 'R');
$pdf->Cell(30, 10, $enc(number_format($totalSum, 2, ',', '.') . ' EUR'), 1, 1, 'C');

// -------- PDF im Browser anzeigen (keine Datei speichern) --------
if (ob_get_length()) { ob_end_clean(); } // Header sicher senden
$downloadName = 'Einkaufsliste_' . $storeName . '.pdf';
$pdf->Output('I', $downloadName);
exit;
