<?php

/**

 * Fichier  : api/brands.php

 * Auteur   : KREMER Régis

 * Version  : 2.2.0

 * Date     : 2026-07-22

 * Description : API REST — CRUD des marques produits

 *

 * 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

 */

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

// api/brands.php — CRUD global brands

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

error_reporting(E_ALL);

ini_set('display_errors', 0); // Don't display errors in response



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



// Check auth

startSession(); requireAuth();



header('Content-Type: application/json; charset=utf-8');



$method = $_SERVER['REQUEST_METHOD'];

$currentUser = currentUser();
$role = $currentUser['role'] ?? 'user';



// Admin only for write operations

if($method !== 'GET' && !hasAdminAccess()) {

    http_response_code(403);

    echo json_encode(['error' => 'Admin uniquement']);

    exit;

}



$body = json_decode(file_get_contents('php://input'), true) ?? [];



// CSRF protection for write operations

if ($method !== 'GET') csrfCheck();



try {

    // Ensure brands.json exists

    $brandsFile = __DIR__.'/../data/brands.json';

    if(!file_exists($brandsFile)) {

        file_put_contents($brandsFile, '[]');

    }

    

    switch($method) {

        case 'GET':

            // Get all brands

            $brands = loadData('brands');

            

            // Search filter

            $q = strtolower($_GET['q'] ?? '');

            if($q) {

                $brands = array_filter($brands, function($b) use ($q) {

                    return str_contains(strtolower($b['name'] ?? ''), $q);

                });

            }

            

            // Sort by name

            usort($brands, function($a, $b) {

                return strcasecmp($a['name'] ?? '', $b['name'] ?? '');

            });

            

            echo json_encode(array_values($brands));

            break;

            

        case 'POST':

            // Create brand

            $name = trim($body['name'] ?? '');

            

            if($name === '') {

                http_response_code(400);

                echo json_encode(['error' => 'Nom obligatoire']);

                exit;

            }

            

            // Check duplicate

            $brands = loadData('brands');

            foreach($brands as $b) {

                if(strcasecmp($b['name'], $name) === 0) {

                    http_response_code(400);

                    echo json_encode(['error' => 'Cette marque existe déjà']);

                    exit;

                }

            }

            

            $brand = addItem('brands', [

                'name' => $name,

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

            ]);

            

            http_response_code(201);

            echo json_encode($brand);

            break;

            

        case 'PUT':

            // Update brand

            $id = $body['id'] ?? null;

            $name = trim($body['name'] ?? '');

            

            if(!$id || $name === '') {

                http_response_code(400);

                echo json_encode(['error' => 'ID et nom requis']);

                exit;

            }

            

            // Check duplicate

            $brands = loadData('brands');

            foreach($brands as $b) {

                if(intval($b['id']) !== intval($id) && strcasecmp($b['name'], $name) === 0) {

                    http_response_code(400);

                    echo json_encode(['error' => 'Cette marque existe déjà']);

                    exit;

                }

            }

            

            $updated = updateItem('brands', $id, ['name' => $name]);

            

            if($updated) {

                // Update products using this brand

                $oldName = '';

                foreach($brands as $b) {

                    if(intval($b['id']) === intval($id)) {

                        $oldName = $b['name'];

                        break;

                    }

                }

                

                if($oldName) {

                    $products = loadData('products');

                    foreach($products as $idx => $p) {

                        if(($p['brand'] ?? '') === $oldName) {

                            $products[$idx]['brand'] = $name;

                        }

                    }

                    saveData('products', $products);

                }

                

                echo json_encode($updated);

            } else {

                http_response_code(404);

                echo json_encode(['error' => 'Marque introuvable']);

            }

            break;

            

        case 'DELETE':

            // Delete brand

            $id = $body['id'] ?? $_GET['id'] ?? null;

            

            if(!$id) {

                http_response_code(400);

                echo json_encode(['error' => 'ID requis']);

                exit;

            }

            

            // Get brand name before delete

            $brands = loadData('brands');

            $brandName = '';

            foreach($brands as $b) {

                if(intval($b['id']) === intval($id)) {

                    $brandName = $b['name'];

                    break;

                }

            }

            

            // Remove from suppliers

            $suppliers = loadData('suppliers');

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

                $linked = json_decode($s['linkedBrands'] ?? '[]', true);

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

                

                $linked = array_values(array_filter($linked, function($bid) use ($id) {

                    return intval($bid) !== intval($id);

                }));

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

            }

            saveData('suppliers', $suppliers);

            

            // Remove from products (set to empty)

            $products = loadData('products');

            foreach($products as $idx => $p) {

                if(($p['brand'] ?? '') === $brandName) {

                    $products[$idx]['brand'] = '';

                }

            }

            saveData('products', $products);

            

            // Delete brand

            deleteItem('brands', $id);

            

            echo json_encode(['ok' => true]);

            break;

            

        default:

            http_response_code(405);

            echo json_encode(['error' => 'Méthode non supportée']);

            break;

    }

    

} catch(Exception $e) {

    http_response_code(500);

    echo json_encode(['error' => $e->getMessage()]);

}

