<?php

/**

 * Fichier  : repair-data-brands.php

 * Auteur   : KREMER Régis

 * Version  : 2.2.0

 * Date     : 2026-02-21

 * Description : Utilitaire de réparation des associations marques/fournisseurs

 *

 * Changelog :

 *   v2.1.0 (2026-02-21) — Version initiale auditée et sécurisée

 *   v2.1.1 (2026-02-21) — Corrections sécurité (CSRF, MIME, session, migrateSuppliers)

 *   v2.2.0 (2026-02-21) — Permissions magasins, bons de commande, rapport d'écart,

 *                      import CSV, historique prix, bon de livraison multi-lignes

 */

// ================================================================

// repair-data-brands.php — Migrer vers système marques globales

// ================================================================

require_once __DIR__.'/config.php';



echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Migration Marques</title>';

echo '<style>body{font-family:monospace;padding:40px;background:#1a1a1a;color:#eee}h1{color:#0cf}.step{margin:20px 0;padding:15px;background:#2a2a2a;border-left:4px solid #0cf}.ok{color:#0f0}.err{color:#f00}</style>';

echo '</head><body>';



function log_msg($msg) {

    echo "<div class='step'>$msg</div>";

    flush();

}



log_msg("<h1>🔧 MIGRATION SYSTÈME MARQUES GLOBALES</h1>");



try {

    // 1. Create brands table if not exists

    log_msg("1️⃣ Création table brands...");

    if(!file_exists(__DIR__.'/data/brands.json')) {

        file_put_contents(__DIR__.'/data/brands.json', '[]');

        log_msg("   ✅ Fichier brands.json créé");

    } else {

        log_msg("   ℹ️ brands.json existe déjà");

    }

    

    // 2. Extract unique brands from products

    log_msg("2️⃣ Extraction marques des produits...");

    $products = loadData('products');

    $uniqueBrands = [];

    

    foreach($products as $p) {

        if(!empty($p['brand']) && trim($p['brand']) !== '') {

            $brand = trim($p['brand']);

            if(!in_array($brand, $uniqueBrands)) {

                $uniqueBrands[] = $brand;

            }

        }

    }

    

    sort($uniqueBrands);

    log_msg("   Marques trouvées: <strong>" . implode(', ', $uniqueBrands) . "</strong>");

    

    // 3. Create brand records

    log_msg("3️⃣ Création enregistrements marques...");

    $brands = loadData('brands');

    $created = 0;

    $brandMap = []; // name => id

    

    foreach($brands as $b) {

        $brandMap[$b['name']] = $b['id'];

    }

    

    foreach($uniqueBrands as $brandName) {

        if(!isset($brandMap[$brandName])) {

            $newBrand = addItem('brands', [

                'name' => $brandName,

                'createdAt' => date('Y-m-d H:i:s')

            ]);

            $brandMap[$brandName] = $newBrand['id'];

            $created++;

            log_msg("   → Marque créée: <strong>$brandName</strong> (ID: {$newBrand['id']})");

        }

    }

    

    log_msg("   ✅ $created nouvelles marques créées");

    

    // 4. Link brands to suppliers based on products

    log_msg("4️⃣ Liaison marques → fournisseurs...");

    $suppliers = loadData('suppliers');

    

    foreach($suppliers as $idx => $supplier) {

        $suppId = $supplier['id'];

        $suppName = $supplier['name'];

        

        // Find products from this supplier

        $supplierProducts = array_filter($products, fn($p) => 

            isset($p['supplier']) && intval($p['supplier']) === intval($suppId)

        );

        

        // Get unique brand names

        $supplierBrands = [];

        foreach($supplierProducts as $p) {

            if(!empty($p['brand'])) {

                $brandName = trim($p['brand']);

                if(isset($brandMap[$brandName]) && !in_array($brandMap[$brandName], $supplierBrands)) {

                    $supplierBrands[] = $brandMap[$brandName];

                }

            }

        }

        

        // Save linkedBrands

        if(!empty($supplierBrands)) {

            $suppliers[$idx]['linkedBrands'] = json_encode($supplierBrands);

            log_msg("   → Fournisseur '<strong>$suppName</strong>': " . count($supplierBrands) . " marque(s) liée(s)");

        } else {

            $suppliers[$idx]['linkedBrands'] = '[]';

        }

        

        // Remove old 'brands' field if exists

        unset($suppliers[$idx]['brands']);

    }

    

    saveData('suppliers', $suppliers);

    log_msg("   ✅ Fournisseurs mis à jour");

    

    // 5. Clean up products (brands are still stored as names)

    log_msg("5️⃣ Vérification produits...");

    log_msg("   ℹ️ Les produits gardent le nom de la marque (pas l'ID)");

    log_msg("   ✅ Aucune modification nécessaire");

    

    log_msg("<h2 style='color:#0f0'>✅ MIGRATION TERMINÉE !</h2>");

    log_msg("<p>📊 Résumé :</p>");

    log_msg("<ul>");

    log_msg("<li>✅ " . count($uniqueBrands) . " marques globales créées</li>");

    log_msg("<li>✅ " . count($suppliers) . " fournisseurs mis à jour</li>");

    log_msg("<li>✅ " . count($products) . " produits conservés</li>");

    log_msg("</ul>");

    log_msg("<p><a href='index.php?page=brands' style='color:#0cf'>→ Aller à la page Marques</a></p>");

    log_msg("<p><a href='index.php?page=suppliers' style='color:#0cf'>→ Aller à la page Fournisseurs</a></p>");

    

} catch(Exception $e) {

    log_msg("<div class='err'>❌ ERREUR: " . $e->getMessage() . "</div>");

    log_msg("<pre>" . $e->getTraceAsString() . "</pre>");

}



echo '</body></html>';

