<?php

/**

 * Fichier  : migrations/migrate-v2.1-architecture.php

 * Auteur   : KREMER Régis

 * Version  : 2.2.0

 * Date     : 2026-02-21

 * Description : Script de migration manuelle vers l'architecture v2.1

 *

 * 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

 */

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

// migrations/migrate-v2.1-architecture.php

// AUTO MIGRATION: Warehouse categories + Supplier brands + Product allowedWarehouses

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

require_once __DIR__.'/../config.php';



// HTML output mode

$isHtml = !isset($argv);

if($isHtml) {

    echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Migration V2.1</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_step($msg, $isOk = true) {

    global $isHtml;

    if($isHtml) {

        echo "<div class='step'>".($isOk ? "✅" : "❌")." ".$msg."</div>";

        flush();

    } else {

        echo $msg."\n";

    }

}



function migrateArchitecture() {

    log_step("<h1>🚀 MIGRATION V2.1 ARCHITECTURE</h1>");

    

    // 1. Add categories column to warehouses if not exists

    log_step("1️⃣ Ajout colonne 'categories' dans warehouses...");

    try {

        $test = DB::query("SELECT categories FROM warehouses LIMIT 1");

        log_step("   Colonne 'categories' existe déjà");

    } catch(Exception $e) {

        try {

            DB::query("ALTER TABLE warehouses ADD COLUMN categories TEXT DEFAULT '[]'");

            log_step("   Colonne 'categories' ajoutée avec succès");

        } catch(Exception $e2) {

            log_step("   ERREUR: ".$e2->getMessage(), false);

        }

    }

    

    // 2. Migrate existing global categories to each warehouse

    log_step("2️⃣ Migration catégories globales → par magasin...");

    try {

        $products = DB::query("SELECT DISTINCT category FROM products WHERE category IS NOT NULL AND category != ''");

        $globalCategories = array_unique(array_map(fn($p) => $p['category'], $products));

        

        if(count($globalCategories) > 0) {

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

            

            $warehouses = DB::query("SELECT * FROM warehouses");

            foreach($warehouses as $wh) {

                $current = json_decode($wh['categories'] ?? '[]', true);

                if(!is_array($current)) $current = [];

                

                if(empty($current)) {

                    // Assign all global categories to this warehouse

                    DB::query(

                        "UPDATE warehouses SET categories=? WHERE id=?",

                        [json_encode($globalCategories, JSON_UNESCAPED_UNICODE), $wh['id']]

                    );

                    log_step("   ✓ Magasin '<strong>{$wh['name']}</strong>': " . count($globalCategories) . " catégories");

                }

            }

        } else {

            log_step("   Aucune catégorie trouvée dans les produits");

        }

    } catch(Exception $e) {

        log_step("   ERREUR: ".$e->getMessage(), false);

    }

    

    // 3. Add brands column to suppliers if not exists

    log_step("3️⃣ Ajout colonne 'brands' dans suppliers...");

    try {

        $test = DB::query("SELECT brands FROM suppliers LIMIT 1");

        log_step("   Colonne 'brands' existe déjà");

    } catch(Exception $e) {

        try {

            DB::query("ALTER TABLE suppliers ADD COLUMN brands TEXT DEFAULT '[]'");

            log_step("   Colonne 'brands' ajoutée avec succès");

        } catch(Exception $e2) {

            log_step("   ERREUR: ".$e2->getMessage(), false);

        }

    }

    

    // 4. Migrate existing product brands to suppliers

    log_step("4️⃣ Migration marques → par fournisseur...");

    try {

        $products = DB::query("SELECT DISTINCT brand, supplier FROM products WHERE brand IS NOT NULL AND brand != '' AND supplier IS NOT NULL AND supplier != ''");

        

        $brandsBySupplier = [];

        foreach($products as $p) {

            $supplierId = intval($p['supplier']);

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

            if($supplierId > 0 && $brand) {

                if(!isset($brandsBySupplier[$supplierId])) {

                    $brandsBySupplier[$supplierId] = [];

                }

                if(!in_array($brand, $brandsBySupplier[$supplierId])) {

                    $brandsBySupplier[$supplierId][] = $brand;

                }

            }

        }

        

        if(count($brandsBySupplier) > 0) {

            foreach($brandsBySupplier as $supplierId => $brands) {

                sort($brands);

                DB::query(

                    "UPDATE suppliers SET brands=? WHERE id=?",

                    [json_encode($brands, JSON_UNESCAPED_UNICODE), $supplierId]

                );

                

                $supplier = DB::queryOne("SELECT name FROM suppliers WHERE id=?", [$supplierId]);

                log_step("   ✓ Fournisseur '<strong>{$supplier['name']}</strong>': " . count($brands) . " marques");

            }

        } else {

            log_step("   Aucune marque à migrer");

        }

    } catch(Exception $e) {

        log_step("   ERREUR: ".$e->getMessage(), false);

    }

    

    // 5. Add allowedWarehouses column to products if not exists

    log_step("5️⃣ Ajout colonne 'allowedWarehouses' dans products...");

    try {

        $test = DB::query("SELECT allowedWarehouses FROM products LIMIT 1");

        log_step("   Colonne 'allowedWarehouses' existe déjà");

    } catch(Exception $e) {

        try {

            DB::query("ALTER TABLE products ADD COLUMN allowedWarehouses TEXT DEFAULT '[]'");

            log_step("   Colonne 'allowedWarehouses' ajoutée avec succès");

        } catch(Exception $e2) {

            log_step("   ERREUR: ".$e2->getMessage(), false);

        }

    }

    

    // 6. Populate allowedWarehouses based on existing stock

    log_step("6️⃣ Calcul allowedWarehouses depuis stock existant...");

    try {

        $products = DB::query("SELECT * FROM products");

        $updated = 0;

        

        foreach($products as $p) {

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

            if(!is_array($current)) $current = [];

            

            if(empty($current)) {

                $warehouseIds = [];

                

                // Get warehouses where this product has stock

                $stock = DB::query("SELECT DISTINCT warehouseId FROM stock WHERE productId=?", [$p['id']]);

                foreach($stock as $s) {

                    $warehouseIds[] = intval($s['warehouseId']);

                }

                

                // If product has defaultWarehouse, include it

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

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

                }

                

                // Remove duplicates

                $warehouseIds = array_unique($warehouseIds);

                

                // If STILL no warehouses, allow in ALL warehouses

                if(empty($warehouseIds)) {

                    $allWarehouses = DB::query("SELECT id FROM warehouses");

                    $warehouseIds = array_map(fn($w) => intval($w['id']), $allWarehouses);

                    log_step("   → Produit '{$p['name']}': aucun stock, autorisé dans TOUS les magasins");

                } else {

                    log_step("   → Produit '{$p['name']}': autorisé dans " . count($warehouseIds) . " magasin(s)");

                }

                

                sort($warehouseIds);

                

                DB::query(

                    "UPDATE products SET allowedWarehouses=? WHERE id=?",

                    [json_encode($warehouseIds), $p['id']]

                );

                $updated++;

            }

        }

        

        log_step("   ✓ <strong>{$updated}</strong> produits mis à jour");

    } catch(Exception $e) {

        log_step("   ERREUR: ".$e->getMessage(), false);

    }

    

    // 7. Create migration marker

    log_step("7️⃣ Marqueur migration...");

    try {

        $settings = getSettings();

        $settings['migrationV21Architecture'] = date('Y-m-d H:i:s');

        saveSettings($settings);

        log_step("   ✓ Migration marquée comme complète");

    } catch(Exception $e) {

        log_step("   ERREUR: ".$e->getMessage(), false);

    }

    

    log_step("<h2 class='ok'>✅ MIGRATION TERMINÉE AVEC SUCCÈS !</h2>");

    log_step("<p><a href='../'>← Retour à l'application</a></p>");

}



// Run migration

if(php_sapi_name() === 'cli' || (isset($_GET['run']) && $_GET['run'] === 'migrate')) {

    try {

        migrateArchitecture();

    } catch(Exception $e) {

        log_step("ERREUR FATALE: ".$e->getMessage(), false);

    }

} else {

    echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Migration V2.1</title></head><body>';

    echo '<h1>Migration V2.1 Architecture</h1>';

    echo '<p>Pour lancer la migration, ajoutez <code>?run=migrate</code> à l\'URL</p>';

    echo '<p><a href="?run=migrate">Lancer la migration maintenant</a></p>';

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

}



if($isHtml) {

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

}

