<?php

/**

 * Fichier  : repair-data.php

 * Auteur   : KREMER Régis

 * Version  : 2.2.0

 * Date     : 2026-02-21

 * Description : Utilitaire de réparation des données JSON corrompues

 *

 * 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.php - Répare les données existantes

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

require_once __DIR__.'/config.php';



echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Réparation Données</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>🔧 RÉPARATION DONNÉES STOCKMASTER</h1>");



try {

    // 1. Get all products

    log_msg("1️⃣ Chargement produits...");

    $products = loadData('products');

    log_msg("   ✅ " . count($products) . " produits trouvés");

    

    // 2. Get all warehouses

    log_msg("2️⃣ Chargement magasins...");

    $warehouses = loadData('warehouses');

    $allWhIds = array_map(fn($w) => intval($w['id']), $warehouses);

    log_msg("   ✅ " . count($warehouses) . " magasins trouvés");

    

    // 3. Get all stock

    log_msg("3️⃣ Chargement stock...");

    $stock = loadData('stock');

    log_msg("   ✅ " . count($stock) . " lignes de stock");

    

    // 4. Process each product

    log_msg("4️⃣ Réparation allowedWarehouses...");

    $fixed = 0;

    

    foreach($products as &$p) {

        $productName = $p['name'] ?? '?';

        $productId = $p['id'];

        

        // Find warehouses where this product has stock

        $productStock = array_filter($stock, fn($s) => intval($s['productId']) === intval($productId));

        $whIds = array_unique(array_map(fn($s) => intval($s['warehouseId']), $productStock));

        

        // Add defaultWarehouse if exists

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

            $whIds[] = intval($p['defaultWarehouse']);

            $whIds = array_unique($whIds);

        }

        

        // If no warehouse found, add to ALL warehouses

        if(empty($whIds)) {

            $whIds = $allWhIds;

            log_msg("   → <span style='color:#fa0'>Produit '$productName': aucun stock → autorisé dans TOUS les magasins</span>");

        } else {

            $whNames = [];

            foreach($whIds as $wid) {

                $wh = array_filter($warehouses, fn($w) => intval($w['id']) === $wid);

                if(!empty($wh)) {

                    $whNames[] = reset($wh)['name'];

                }

            }

            log_msg("   → Produit '<strong>$productName</strong>': autorisé dans " . implode(', ', $whNames));

        }

        

        sort($whIds);

        

        // Update product

        $p['allowedWarehouses'] = json_encode($whIds);

        $fixed++;

    }

    unset($p);

    

    // Save products

    saveData('products', $products);

    log_msg("   ✅ <strong>$fixed produits réparés et sauvegardés</strong>");

    

    // 5. Assign categories to warehouses

    log_msg("5️⃣ Attribution catégories aux magasins...");

    

    // Get all unique categories from products

    $categories = [];

    foreach($products as $p) {

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

            $cat = trim($p['category']);

            if(!in_array($cat, $categories)) {

                $categories[] = $cat;

            }

        }

    }

    sort($categories);

    

    if(!empty($categories)) {

        log_msg("   Catégories trouvées: <strong>" . implode(', ', $categories) . "</strong>");

        

        // Assign to each warehouse based on products in that warehouse

        foreach($warehouses as &$wh) {

            $whId = intval($wh['id']);

            

            // Get categories of products allowed in this warehouse

            $whCategories = [];

            foreach($products as $p) {

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

                    $allowed = json_decode($p['allowedWarehouses'] ?? '[]', true);

                    if(is_array($allowed) && in_array($whId, $allowed)) {

                        $cat = trim($p['category']);

                        if(!in_array($cat, $whCategories)) {

                            $whCategories[] = $cat;

                        }

                    }

                }

            }

            

            sort($whCategories);

            

            // If warehouse has no specific categories, give it ALL categories

            if(empty($whCategories)) {

                $whCategories = $categories;

            }

            

            $wh['categories'] = json_encode($whCategories, JSON_UNESCAPED_UNICODE);

            log_msg("   → Magasin '<strong>{$wh['name']}</strong>': " . count($whCategories) . " catégories (" . implode(', ', $whCategories) . ")");

        }

        unset($wh);

        

        // Save warehouses

        saveData('warehouses', $warehouses);

        log_msg("   ✅ Magasins sauvegardés");

    } else {

        log_msg("   ⚠️ Aucune catégorie trouvée dans les produits");

    }

    

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

    log_msg("<p>Retourne sur <a href='index.php?page=warehouses' style='color:#0cf'>Magasins</a> et recharge (F5)</p>");

    

} catch(Exception $e) {

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

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

}



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

