<?php
/**
 * Fichier  : api/supplier-brands.php
 * Auteur   : KREMER Régis
 * Version  : 2.2.0
 * Date     : 2026-07-22
 * Description : API REST — Association 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
 */
// ================================================================
// api/supplier-brands.php — CRUD brands per supplier
// FIX: checkAuth() -> requireAuth(), CSRF, brands stored as array
// ================================================================
require_once __DIR__.'/../config.php';
startSession(); requireAuth();

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

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

// CSRF protection for write operations
if ($method !== 'GET') csrfCheck();

// Admin only for write operations
if ($method !== 'GET' && !hasAdminAccess()) {
    http_response_code(403);
    echo json_encode(['error' => 'Admin uniquement']);
    exit;
}

try {
    switch($method) {
        case 'GET':
            // Get brands for a supplier
            $supplierId = intval($_GET['supplierId'] ?? 0);

            if(!$supplierId) {
                http_response_code(400);
                echo json_encode(['error' => 'supplierId requis']);
                exit;
            }

            $suppliers = loadData('suppliers');
            $supplier = null;
            foreach($suppliers as $s) {
                if(intval($s['id']) === $supplierId) {
                    $supplier = $s;
                    break;
                }
            }

            if(!$supplier) {
                http_response_code(404);
                echo json_encode(['error' => 'Fournisseur introuvable']);
                exit;
            }

            // brands is stored as a native PHP array (migrateSuppliers ensures this)
            $brands = $supplier['brands'] ?? [];
            if (!is_array($brands)) {
                // Legacy fallback: try to decode if stored as JSON string
                $brands = is_string($brands) ? (json_decode($brands, true) ?: []) : [];
            }

            echo json_encode(['brands' => array_values($brands)]);
            break;

        case 'POST':
            // Add brand to supplier
            $data = json_decode(file_get_contents('php://input'), true);
            $supplierId = intval($data['supplierId'] ?? 0);
            $brand = trim($data['brand'] ?? '');

            if(!$supplierId || !$brand) {
                http_response_code(400);
                echo json_encode(['error' => 'supplierId et brand requis']);
                exit;
            }

            $suppliers = loadData('suppliers');
            $supplierIndex = null;
            foreach($suppliers as $idx => $s) {
                if(intval($s['id']) === $supplierId) {
                    $supplierIndex = $idx;
                    break;
                }
            }

            if($supplierIndex === null) {
                http_response_code(404);
                echo json_encode(['error' => 'Fournisseur introuvable']);
                exit;
            }

            // brands stored as native array
            $brands = $suppliers[$supplierIndex]['brands'] ?? [];
            if (!is_array($brands)) {
                $brands = is_string($brands) ? (json_decode($brands, true) ?: []) : [];
            }

            // Check if already exists (case-insensitive)
            foreach($brands as $b) {
                if(strcasecmp($b, $brand) === 0) {
                    http_response_code(400);
                    echo json_encode(['error' => 'Marque existe déjà']);
                    exit;
                }
            }

            $brands[] = $brand;
            sort($brands);

            // Store as native array (not JSON-encoded string)
            $suppliers[$supplierIndex]['brands'] = array_values($brands);
            saveData('suppliers', $suppliers);

            echo json_encode(['success' => true, 'brands' => array_values($brands)]);
            break;

        case 'DELETE':
            // Remove brand from supplier
            $data = json_decode(file_get_contents('php://input'), true);
            $supplierId = intval($data['supplierId'] ?? 0);
            $brand = trim($data['brand'] ?? '');

            if(!$supplierId || !$brand) {
                http_response_code(400);
                echo json_encode(['error' => 'supplierId et brand requis']);
                exit;
            }

            $suppliers = loadData('suppliers');
            $supplierIndex = null;
            foreach($suppliers as $idx => $s) {
                if(intval($s['id']) === $supplierId) {
                    $supplierIndex = $idx;
                    break;
                }
            }

            if($supplierIndex === null) {
                http_response_code(404);
                echo json_encode(['error' => 'Fournisseur introuvable']);
                exit;
            }

            // brands stored as native array
            $brands = $suppliers[$supplierIndex]['brands'] ?? [];
            if (!is_array($brands)) {
                $brands = is_string($brands) ? (json_decode($brands, true) ?: []) : [];
            }

            $brands = array_values(array_filter($brands, fn($b) => strcasecmp($b, $brand) !== 0));
            sort($brands);

            // Store as native array
            $suppliers[$supplierIndex]['brands'] = array_values($brands);
            saveData('suppliers', $suppliers);

            echo json_encode(['success' => true, 'deleted' => true, 'brands' => array_values($brands)]);
            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()]);
}
