<?php
/**
 * EMU World App — CMS Sync
 *
 * Legge il database EmuCMS e genera i file JSON per il frontend.
 * Compatibile con PHP 5.5.9 / MySQL 5.5.62
 *
 * Posizione server: EmuCms/cms-sync.php
 * Output: EmuCms/app/data/*.json
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

// --- Connessione DB ---
require_once __DIR__ . '/include/db.php';
$conn->set_charset('utf8mb4');

// --- Config ---
$dataDir = __DIR__ . '/app/data';
$jsonFlags = JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE;

// --- Stato sync ---
$errors = array();
$stats = array(
    'files_written' => 0,
    'products' => 0,
    'cataloghi' => 0,
    'presskit' => 0,
    'campionari' => 0,
    'digitalkit' => 0,
    'tavole' => 0,
);

// --- Whitelist: sezioni che cms-sync è autorizzato a generare ---
// Solo i file in questa lista vengono scritti. Tutti gli altri JSON di sezione
// (company-profile, press-kit, merch-tools, new-products, ecc.) sono gestiti
// manualmente e NON vengono toccati. Fail-safe: dimenticare di aggiungere un
// file = JSON protetto, non sovrascritto.
$generatedSections = array(
    'section-products.json',
    'section-tavole-schede.json',
    'section-cataloghi.json',
    'section-digital-kit.json',
    'section-progettazione.json',
);

// --- Utility ---

function extractParentCode($codArticolo) {
    $cod = trim($codArticolo);
    // Solo codici lunghi del gestionale (>= 9 char) che iniziano con "3"
    if (strlen($cod) >= 9 && $cod[0] === '3') {
        if (substr($cod, 0, 2) === '30') {
            // Inizia con "30" -> 3 cifre da posizione 2
            return substr($cod, 2, 3);
        } else {
            // Inizia con "3" ma non "30" -> 4 cifre da posizione 1
            return substr($cod, 1, 4);
        }
    }
    // Tutto il resto (codici corti, "0xxx", ecc.) -> lascia com'e
    return $cod;
}

function writeJson($path, $data, $flags) {
    $json = json_encode($data, $flags);
    if ($json === false) {
        return 'json_encode failed: ' . json_last_error_msg();
    }
    $result = file_put_contents($path, $json);
    if ($result === false) {
        return 'file_put_contents failed: ' . $path;
    }
    return true;
}

function writeSectionJson($filename, $data, $flags, $dataDir, $generatedSections) {
    if (!in_array($filename, $generatedSections)) {
        return 'SKIPPED';
    }
    return writeJson($dataDir . '/' . $filename, $data, $flags);
}

function safeString($val) {
    if ($val === null) {
        return '';
    }
    return (string)$val;
}

// --- Assicura che la cartella data/ esista ---
if (!is_dir($dataDir)) {
    if (!mkdir($dataDir, 0755, true)) {
        $errors[] = "Impossibile creare la cartella: $dataDir";
    }
}

// --- Mappa immagini frontend (codice padre → file) ---
$imgDir = __DIR__ . '/app/assets/img';
$imageMap = array();
if (is_dir($imgDir)) {
    foreach (scandir($imgDir) as $file) {
        if ($file[0] === '.') continue;
        $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        if (!in_array($ext, array('jpg', 'jpeg', 'png', 'webp'))) continue;
        $name = pathinfo($file, PATHINFO_FILENAME);
        // Estrai codice base: primo segmento prima di "-" (es. "1371" da "1371-22-27-700_10")
        $parts = explode('-', $name);
        $baseCode = $parts[0];
        // Salva il file più recente per ogni codice base
        $imageMap[$baseCode] = $file;
        // Salva anche con nome completo (senza estensione) per match esatto
        $imageMap[$name] = $file;
    }
}

// ============================================================
// 1. MANIFEST
// ============================================================
$now = gmdate('Y-m-d\TH:i:s\Z');
$manifest = array(
    'version' => $now,
    'generated_at' => $now,
);
$res = writeJson($dataDir . '/manifest.json', $manifest, $jsonFlags);
if ($res !== true) {
    $errors[] = "manifest.json: $res";
} else {
    $stats['files_written']++;
}

// ============================================================
// 2. CONTEGGI per sections.json
// ============================================================

// Cataloghi + Listini
$r = $conn->query("SELECT COUNT(*) AS cnt FROM Uploads WHERE Categoria IN ('Cataloghi', 'Listini')");
$countCataloghi = $r ? (int)$r->fetch_assoc()['cnt'] : 0;
$stats['cataloghi'] = $countCataloghi;

// Digital Kit
$r = $conn->query("SELECT COUNT(*) AS cnt FROM Uploads WHERE TipoUploads IN ('DKFoto','DKVideo','DKRender')");
$countDK = $r ? (int)$r->fetch_assoc()['cnt'] : 0;
$stats['digitalkit'] = $countDK;

// Press Kit
$r = $conn->query("SELECT COUNT(*) AS cnt FROM Uploads WHERE Categoria = 'Presskit'");
$countPress = $r ? (int)$r->fetch_assoc()['cnt'] : 0;
$stats['presskit'] = $countPress;

// Merch Tools (Campionari + MarketingTools)
$r = $conn->query("SELECT COUNT(*) AS cnt FROM Uploads WHERE Categoria IN ('Campionari', 'MarketingTools')");
$countMerch = $r ? (int)$r->fetch_assoc()['cnt'] : 0;
$stats['campionari'] = $countMerch;

// Tavole & Schede
$r = $conn->query("SELECT COUNT(*) AS cnt FROM SchedeArticoli WHERE IDTavola IS NOT NULL");
$countTavole = $r ? (int)$r->fetch_assoc()['cnt'] : 0;
$stats['products'] = $countTavole;

// ============================================================
// 3. SECTIONS.JSON
// ============================================================
$sections = array(
    array('slug' => 'company-profile', 'title_it' => 'Company Profile', 'title_en' => 'Company Profile', 'icon' => 'building', 'position' => 1, 'item_count' => 1),
    array('slug' => 'cataloghi', 'title_it' => 'Cataloghi & Listini', 'title_en' => 'Catalogues & Price Lists', 'icon' => 'book', 'position' => 2, 'item_count' => $countCataloghi),
    array('slug' => 'digital-kit', 'title_it' => 'Digital Kit', 'title_en' => 'Digital Kit', 'icon' => 'image', 'position' => 3, 'item_count' => $countDK),
    array('slug' => 'progettazione', 'title_it' => 'Progettazione', 'title_en' => 'Design', 'icon' => 'compass', 'position' => 4, 'item_count' => 1),
    array('slug' => 'press-kit', 'title_it' => 'Press Kit', 'title_en' => 'Press Kit', 'icon' => 'newspaper', 'position' => 5, 'item_count' => $countPress),
    array('slug' => 'merch-tools', 'title_it' => 'Merch. Tools', 'title_en' => 'Merch. Tools', 'icon' => 'palette', 'position' => 6, 'item_count' => $countMerch),
    array('slug' => 'tavole-schede', 'title_it' => 'Tavole & Schede', 'title_en' => 'Boards & Sheets', 'icon' => 'table', 'position' => 7, 'item_count' => $countTavole),
);

$res = writeJson($dataDir . '/sections.json', $sections, $jsonFlags);
if ($res !== true) {
    $errors[] = "sections.json: $res";
} else {
    $stats['files_written']++;
}

// --- Mappa colori disponibili ---
$colorMap = array(); // key: "CodColore|Elemento" => {code, name, hex, element}
$rColori = $conn->query("SELECT CodColore, Elemento, NomeColore, HexColore FROM ColoriDisponibili");
if ($rColori) {
    while ($col = $rColori->fetch_assoc()) {
        $key = $col['CodColore'] . '|' . $col['Elemento'];
        $colorMap[$key] = array(
            'code' => $col['CodColore'],
            'name' => $col['NomeColore'],
            'hex' => $col['HexColore'] ? $col['HexColore'] : null,
            'element' => $col['Elemento'],
        );
    }
}

$swatchSuffix = array(
    'Struttura' => '',
    'Telo Olefin' => '-olefin-fabric',
    'Telo Acrylic' => '-acrylic-fabric',
);

function parseColoriArticolo($coloriStr, $colorMap, $swatchSuffix) {
    if (empty($coloriStr)) return array();
    $result = array();
    $groups = explode('|', $coloriStr);
    foreach ($groups as $group) {
        $parts = explode(':', $group, 2);
        if (count($parts) !== 2) continue;
        $elemento = trim($parts[0]);
        $suffix = isset($swatchSuffix[$elemento]) ? $swatchSuffix[$elemento] : '';
        $codes = explode(',', trim($parts[1]));
        foreach ($codes as $code) {
            $code = trim($code);
            $key = $code . '|' . $elemento;
            $swatch = '/app/assets/img/swatches/' . $code . $suffix . '.png';
            if (isset($colorMap[$key])) {
                $entry = $colorMap[$key];
                $entry['swatch'] = $swatch;
                $result[] = $entry;
            } else {
                $result[] = array(
                    'code' => $code,
                    'name' => '',
                    'hex' => null,
                    'element' => $elemento,
                    'swatch' => $swatch,
                );
            }
        }
    }
    return $result;
}

// ============================================================
// 4. SECTION-TAVOLE-SCHEDE.JSON
// ============================================================

$tavoleEn = array(
    // Current DescTavola values (from server Tavole table, aligned with dash-cms.php)
    'Area Antigua Living' => 'Antigua Living Area',
    'Area Antigua Dining' => 'Antigua Dining Area',
    'Area Collier Living' => 'Collier Living Area',
    'Area Collier Dining' => 'Collier Dining Area',
    'Area Saint Martin'   => 'Saint Martin Area',
    'Area Darwin'         => 'Darwin Area',
    'Area Tami'           => 'Tami Area',
    'Area Contract'       => 'Contract Area',
    'Riunioni Terramare'  => 'Meetings Terramare',
    'Riunioni Plus4 + Yard' => 'Meetings Plus4 + Yard',
    'Sgabelli Darwin'     => 'Darwin Stools',
    'Icone'               => 'Icons',
    'Biblioteca'          => 'Library',
    'L-ume'               => 'L-ume',
    'Altro'               => 'Other',
);

$categories = array();
$rTavole = $conn->query("SELECT * FROM Tavole ORDER BY IDTavola");
if ($rTavole) {
    while ($tavola = $rTavole->fetch_assoc()) {
        $idTavola = (int)$tavola['IDTavola'];
        $nameIt = safeString($tavola['DescTavola']);
        $nameEn = isset($tavoleEn[$nameIt]) ? $tavoleEn[$nameIt] : $nameIt;

        $items = array();
        $rArticoli = $conn->query("SELECT * FROM SchedeArticoli WHERE IDTavola = " . intval($idTavola) . " ORDER BY IDArticolo");

        while ($rArticoli && $art = $rArticoli->fetch_assoc()) {
            $image = '';
            if (!empty($art['NomeFileImmagine'])) {
                $image = '/app/assets/img/' . $art['NomeFileImmagine'];
            } else {
                // Fallback: cerca in imageMap per codice padre
                $parentCode = extractParentCode($art['CodArticolo']);
                if (isset($imageMap[$parentCode])) {
                    $image = '/app/assets/img/' . $imageMap[$parentCode];
                }
            }
            $techSheet = '';
            if (isset($art['NomeFileScheda']) && $art['NomeFileScheda'] !== '') {
                $techSheet = '/assets/articoli/schede/' . $art['NomeFileScheda'];
            }

            $colors = parseColoriArticolo(
                isset($art['ColoriArticolo']) ? $art['ColoriArticolo'] : '',
                $colorMap, $swatchSuffix
            );

            $product = array(
                'code' => extractParentCode($art['CodArticolo']),
                'title_it' => safeString($art['DescBreveArticolo']),
                'title_en' => safeString($art['DescBreveArticoloEN']),
                'description_it' => safeString($art['DescArticolo']),
                'description_en' => safeString($art['DescArticoloEN']),
                'collection' => safeString($art['CollArticolo']),
                'color' => safeString($art['ColArticolo']),
                'colors' => $colors,
                'price' => (float)$art['PrezArticolo'],
                'price_cif' => $art['PrezArticoloCIF'] !== null ? (float)$art['PrezArticoloCIF'] : null,
                'price_exw' => $art['PrezArticoloEXW'] !== null ? (float)$art['PrezArticoloEXW'] : null,
                'image' => $image,
                'tech_sheet' => $techSheet,
                'url_site' => safeString($art['UrlArticolo']),
                'tipo_collezione' => safeString($art['TipoCollezione']),
            );

            $items[] = array(
                'id' => (int)$art['IDArticolo'],
                'title_it' => safeString($art['DescBreveArticolo']),
                'title_en' => safeString($art['DescBreveArticoloEN']),
                'type' => 'product',
                'products' => array($product),
            );

            $stats['tavole']++;
        }
        $categories[] = array(
            'name_it' => $nameIt,
            'name_en' => $nameEn,
            'items' => $items,
        );
    }
}

$sectionTavole = array(
    'slug' => 'products',
    'title_it' => 'Prodotti',
    'title_en' => 'Products',
    'categories' => $categories,
);

// Genera con il nome usato dal router (products)
$res = writeSectionJson('section-products.json', $sectionTavole, $jsonFlags, $dataDir, $generatedSections);
if ($res === 'SKIPPED') {
    // non in whitelist
} elseif ($res !== true) {
    $errors[] = "section-products.json: $res";
} else {
    $stats['files_written']++;
}
// Genera anche col vecchio nome per backward compatibility
$res = writeSectionJson('section-tavole-schede.json', $sectionTavole, $jsonFlags, $dataDir, $generatedSections);
if ($res === 'SKIPPED') {
    // non in whitelist
} elseif ($res !== true) {
    $errors[] = "section-tavole-schede.json: $res";
} else {
    $stats['files_written']++;
}

// ============================================================
// 5. SECTION-CATALOGHI.JSON
// ============================================================

// Thumbnail automatica: thumb-{NomeFile senza prefisso timestamp}.jpg
function getCatalogThumb($nomeFile) {
    // Rimuove prefisso timestamp (es. "1772634533_") se presente
    $base = preg_replace('/^\d+_/', '', $nomeFile);
    $thumb = 'thumb-' . preg_replace('/\.pdf$/i', '.jpg', $base);
    $thumbPath = __DIR__ . '/app/assets/img/cataloghi/' . $thumb;
    if (file_exists($thumbPath)) {
        return '/app/assets/img/cataloghi/' . $thumb;
    }
    return '';
}

$catItems = array();
$rCat = $conn->query("SELECT * FROM Uploads WHERE Categoria = 'Cataloghi' ORDER BY DataUpload DESC");
if ($rCat) {
    while ($row = $rCat->fetch_assoc()) {
        $nomeFile = safeString($row['NomeFile']);
        $catItems[] = array(
            'id' => (int)$row['IDUploads'],
            'title_it' => safeString($row['Titolo']),
            'title_en' => '',
            'type' => 'pdf',
            'file_path' => '/assets/cataloghi/' . $nomeFile,
            'thumbnail_path' => getCatalogThumb($nomeFile),
        );
    }
}

// Listini
$listItems = array();
$rList = $conn->query("SELECT * FROM Uploads WHERE Categoria = 'Listini' ORDER BY DataUpload DESC");
if ($rList) {
    while ($row = $rList->fetch_assoc()) {
        $nomeFile = safeString($row['NomeFile']);
        $listItems[] = array(
            'id' => (int)$row['IDUploads'],
            'title_it' => safeString($row['Titolo']),
            'title_en' => '',
            'type' => 'pdf',
            'file_path' => '/assets/cataloghi/' . $nomeFile,
            'thumbnail_path' => getCatalogThumb($nomeFile),
        );
    }
}

$sectionCataloghi = array(
    'slug' => 'cataloghi',
    'title_it' => 'Cataloghi & Listini',
    'title_en' => 'Catalogues & Price Lists',
    'categories' => array(
        array(
            'name_it' => 'Cataloghi',
            'name_en' => 'Catalogues',
            'items' => $catItems,
        ),
        array(
            'name_it' => 'Listini',
            'name_en' => 'Price Lists',
            'items' => $listItems,
        ),
    ),
);

$res = writeSectionJson('section-cataloghi.json', $sectionCataloghi, $jsonFlags, $dataDir, $generatedSections);
if ($res === 'SKIPPED') {
    // non in whitelist
} elseif ($res !== true) {
    $errors[] = "section-cataloghi.json: $res";
} else {
    $stats['files_written']++;
}

// ============================================================
// 6. SECTION-PRESS-KIT.JSON — non in whitelist, gestito manualmente
// Il renderer press-kit.js usa formato {company_profile, press_releases},
// incompatibile con il formato {categories} generato dal DB.
// ============================================================

// ============================================================
// 7. SECTION-MERCH-TOOLS.JSON
// ============================================================

// --- Marketing Tools ---
$mtItems = array();
$rMT = $conn->query("SELECT * FROM Uploads WHERE Categoria = 'MarketingTools' ORDER BY DataUpload DESC");
if ($rMT) {
    while ($row = $rMT->fetch_assoc()) {
        $nome = safeString($row['NomeFile']);
        // Deduce lingua dal nome file (contiene "ita" o "eng")
        $isIta = strpos($nome, 'ita') !== false;
        $thumbFile = $isIta ? 'thumb-ita.jpg' : 'thumb-eng.jpg';
        $mtItems[] = array(
            'id' => (int)$row['IDUploads'],
            'title_it' => safeString($row['Titolo']),
            'title_en' => safeString($row['Titolo']),
            'type' => 'pdf',
            'file_path' => '/app/assets/docs/marketing-tools/' . $nome,
            'thumbnail_path' => '/app/assets/img/marketing-tools/' . $thumbFile,
        );
    }
}

// --- Campionari ---
$merchItems = array();
$rMerch = $conn->query("SELECT * FROM Uploads WHERE Categoria = 'Campionari' ORDER BY DataUpload DESC");
if ($rMerch) {
    while ($row = $rMerch->fetch_assoc()) {
        $item = array(
            'id' => (int)$row['IDUploads'],
            'title_it' => safeString($row['Titolo']),
            'title_en' => '',
            'type' => 'pdf',
            'file_path' => '/app/assets/campionari/schede/' . safeString($row['NomeFile']),
            'thumbnail_path' => '',
        );
        if (isset($row['Descrizione']) && $row['Descrizione'] !== '' && $row['Descrizione'] !== null) {
            $item['description_it'] = safeString($row['Descrizione']);
        }
        $merchItems[] = $item;
    }
}

// Costruisci categorie — mostra solo quelle con contenuto
$merchCategories = array();
if (!empty($mtItems)) {
    $merchCategories[] = array(
        'name_it' => 'Marketing Tools',
        'name_en' => 'Marketing Tools',
        'items' => $mtItems,
    );
}
if (!empty($merchItems)) {
    $merchCategories[] = array(
        'name_it' => 'Campionari',
        'name_en' => 'Samples',
        'items' => $merchItems,
    );
}

$sectionMerch = array(
    'slug' => 'merch-tools',
    'title_it' => 'Merch. Tools',
    'title_en' => 'Merch. Tools',
    'categories' => $merchCategories,
);

$res = writeSectionJson('section-merch-tools.json', $sectionMerch, $jsonFlags, $dataDir, $generatedSections);
if ($res === 'SKIPPED') {
    // non in whitelist
} elseif ($res !== true) {
    $errors[] = "section-merch-tools.json: $res";
} else {
    $stats['files_written']++;
}

// ============================================================
// 8. SECTION-DIGITAL-KIT.JSON
// ============================================================

$dkTypeMap = array(
    'DKFoto' => array('name_it' => 'Foto', 'name_en' => 'Photos', 'type' => 'image'),
    'DKVideo' => array('name_it' => 'Video', 'name_en' => 'Videos', 'type' => 'video'),
    'DKRender' => array('name_it' => 'Render', 'name_en' => 'Renders', 'type' => 'image'),
);

$dkCategories = array();
$rDK = $conn->query("SELECT * FROM Uploads WHERE TipoUploads IN ('DKFoto','DKVideo','DKRender') ORDER BY DataUpload DESC");
if ($rDK) {
    $grouped = array(
        'DKFoto' => array(),
        'DKVideo' => array(),
        'DKRender' => array(),
    );
    while ($row = $rDK->fetch_assoc()) {
        $tipo = $row['TipoUploads'];
        if (isset($grouped[$tipo])) {
            $grouped[$tipo][] = array(
                'id' => (int)$row['IDUploads'],
                'title_it' => safeString($row['Titolo']),
                'title_en' => '',
                'type' => $dkTypeMap[$tipo]['type'],
                'file_path' => 'assets/digitalkit/' . safeString($row['NomeFile']),
                'thumbnail_path' => '',
            );
        }
    }
    foreach ($dkTypeMap as $key => $meta) {
        if (!empty($grouped[$key])) {
            $dkCategories[] = array(
                'name_it' => $meta['name_it'],
                'name_en' => $meta['name_en'],
                'items' => $grouped[$key],
            );
        }
    }
}

$sectionDK = array(
    'slug' => 'digital-kit',
    'title_it' => 'Digital Kit',
    'title_en' => 'Digital Kit',
    'categories' => $dkCategories,
);

$res = writeSectionJson('section-digital-kit.json', $sectionDK, $jsonFlags, $dataDir, $generatedSections);
if ($res === 'SKIPPED') {
    // non in whitelist
} elseif ($res !== true) {
    $errors[] = "section-digital-kit.json: $res";
} else {
    $stats['files_written']++;
}

// company-profile: non in $generatedSections, protetto automaticamente

// ============================================================
// 10. SECTION-PROGETTAZIONE.JSON (statico)
// ============================================================

$sectionProg = array(
    'slug' => 'progettazione',
    'title_it' => 'Progettazione',
    'title_en' => 'Design',
    'categories' => array(
        array(
            'name_it' => '',
            'name_en' => '',
            'items' => array(
                array(
                    'id' => 20,
                    'title_it' => 'pCon Planner',
                    'title_en' => 'pCon Planner',
                    'description_it' => 'Configura i tuoi spazi con il planner 3D',
                    'description_en' => 'Design your spaces with the 3D planner',
                    'type' => 'link',
                    'url' => 'https://login.pcon-solutions.com/en/catalog/HPI1NO',
                    'hero_image' => '/app/assets/img/pcon-hero-original.png',
                ),
            ),
        ),
    ),
);

$res = writeSectionJson('section-progettazione.json', $sectionProg, $jsonFlags, $dataDir, $generatedSections);
if ($res === 'SKIPPED') {
    // non in whitelist
} elseif ($res !== true) {
    $errors[] = "section-progettazione.json: $res";
} else {
    $stats['files_written']++;
}

// ============================================================
// OUTPUT HTML
// ============================================================

$hasErrors = !empty($errors);
$statusClass = $hasErrors ? 'danger' : 'success';
$statusIcon = $hasErrors ? '&#10060;' : '&#9989;';
$statusText = $hasErrors ? 'Sync completata con errori' : 'Sync completata con successo';

?><!DOCTYPE html>
<html lang="it">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CMS Sync — EMU World App</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <style>
        body { background: #f4f6f9; }
        .sync-card { max-width: 700px; margin: 40px auto; }
        .stat-row { display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #eee; }
        .stat-row:last-child { border-bottom: none; }
        .stat-label { color: #666; }
        .stat-value { font-weight: 600; }
    </style>
</head>
<body>
    <div class="container">
        <div class="sync-card">
            <div class="text-center mb-4">
                <h2 class="mt-3">EMU World App</h2>
                <p class="text-muted">CMS Sync</p>
            </div>

            <div class="alert alert-<?php echo $statusClass; ?>" role="alert">
                <strong><?php echo $statusIcon; ?> <?php echo $statusText; ?></strong>
                <br><small>Generato: <?php echo $now; ?></small>
            </div>

            <?php if ($hasErrors): ?>
            <div class="card mb-3 border-danger">
                <div class="card-header bg-danger text-white">Errori</div>
                <div class="card-body">
                    <ul class="mb-0">
                        <?php foreach ($errors as $err): ?>
                        <li><?php echo htmlspecialchars($err); ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            </div>
            <?php endif; ?>

            <div class="card mb-3">
                <div class="card-header">Riepilogo</div>
                <div class="card-body">
                    <div class="stat-row">
                        <span class="stat-label">File JSON generati</span>
                        <span class="stat-value"><?php echo $stats['files_written']; ?></span>
                    </div>
                    <div class="stat-row">
                        <span class="stat-label">Prodotti (Tavole &amp; Schede)</span>
                        <span class="stat-value"><?php echo $stats['products']; ?></span>
                    </div>
                    <div class="stat-row">
                        <span class="stat-label">Cataloghi</span>
                        <span class="stat-value"><?php echo $stats['cataloghi']; ?></span>
                    </div>
                    <div class="stat-row">
                        <span class="stat-label">Digital Kit</span>
                        <span class="stat-value"><?php echo $stats['digitalkit']; ?></span>
                    </div>
                    <div class="stat-row">
                        <span class="stat-label">Press Kit</span>
                        <span class="stat-value"><?php echo $stats['presskit']; ?></span>
                    </div>
                    <div class="stat-row">
                        <span class="stat-label">Merch. Tools</span>
                        <span class="stat-value"><?php echo $stats['campionari']; ?></span>
                    </div>
                </div>
            </div>

            <div class="text-center">
                <a href="dash-cms.php" class="btn btn-primary">Torna alla Dashboard</a>
            </div>
        </div>
    </div>
</body>
</html>
