<?php
/**
 * Fichier  : api/warehouse-categories.php
 * Auteur   : KREMER Régis
 * Version  : 2.2.0
 * Date     : 2026-02-21
 * Description : API REST — Catégories personnalisées par magasin
 *
 * 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/warehouse-categories.php — CRUD categories per warehouse
// FIX: checkAuth() -> requireAuth(), CSRF, PUT (rename) implemented
// ================================================================
require_once __DIR__.'/../config.php';
startSession(); requireAuth();

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

$method = $_SERVER['REQUEST_METHOD'];

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

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

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

try {
    switch($method) {
        case 'GET':
            $warehouseId = intval($_GET['warehouseId'] ?? 0);

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

            $warehouses = loadData('warehouses');
            $wh = null;
            foreach($warehouses as $w) {
                if(intval($w['id']) === $warehouseId) { $wh = $w; break; }
            }

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

            $categories = json_decode($wh['categories'] ?? '[]', true);
            if(!is_array($categories)) $categories = [];

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

        case 'POST':
            $input = file_get_contents('php://input');
            $data = json_decode($input, true);

            if(json_last_error() !== JSON_ERROR_NONE) {
                http_response_code(400);
                echo json_encode(['error' => 'JSON invalide']);
                exit;
            }

            $warehouseId = intval($data['warehouseId'] ?? 0);
            $category = trim($data['category'] ?? '');

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

            $warehouses = loadData('warehouses');
            $whIndex = null;
            foreach($warehouses as $idx => $w) {
                if(intval($w['id']) === $warehouseId) { $whIndex = $idx; break; }
            }

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

            $categories = json_decode($warehouses[$whIndex]['categories'] ?? '[]', true);
            if(!is_array($categories)) $categories = [];

            if(in_array($category, $categories)) {
                http_response_code(400);
                echo json_encode(['error' => 'Catégorie existe déjà']);
                exit;
            }

            $categories[] = $category;
            sort($categories);

            $warehouses[$whIndex]['categories'] = json_encode($categories, JSON_UNESCAPED_UNICODE);
            saveData('warehouses', $warehouses);

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

        case 'PUT':
            // Rename category — was missing, now implemented
            $input = file_get_contents('php://input');
            $data = json_decode($input, true);

            if(json_last_error() !== JSON_ERROR_NONE) {
                http_response_code(400);
                echo json_encode(['error' => 'JSON invalide']);
                exit;
            }

            $warehouseId = intval($data['warehouseId'] ?? 0);
            $oldName = trim($data['oldCategory'] ?? '');
            $newName = trim($data['newCategory'] ?? '');

            if(!$warehouseId || !$oldName || !$newName) {
                http_response_code(400);
                echo json_encode(['error' => 'warehouseId, oldCategory et newCategory requis']);
                exit;
            }

            $warehouses = loadData('warehouses');
            $whIndex = null;
            foreach($warehouses as $idx => $w) {
                if(intval($w['id']) === $warehouseId) { $whIndex = $idx; break; }
            }

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

            $categories = json_decode($warehouses[$whIndex]['categories'] ?? '[]', true);
            if(!is_array($categories)) $categories = [];

            if(!in_array($oldName, $categories)) {
                http_response_code(404);
                echo json_encode(['error' => 'Catégorie introuvable']);
                exit;
            }

            if(in_array($newName, $categories) && $newName !== $oldName) {
                http_response_code(400);
                echo json_encode(['error' => 'Le nouveau nom existe déjà']);
                exit;
            }

            // Rename
            $categories = array_map(fn($c) => $c === $oldName ? $newName : $c, $categories);
            sort($categories);

            $warehouses[$whIndex]['categories'] = json_encode($categories, JSON_UNESCAPED_UNICODE);
            saveData('warehouses', $warehouses);

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

        case 'DELETE':
            $input = file_get_contents('php://input');
            $data = json_decode($input, true);

            if(json_last_error() !== JSON_ERROR_NONE) {
                http_response_code(400);
                echo json_encode(['error' => 'JSON invalide']);
                exit;
            }

            $warehouseId = intval($data['warehouseId'] ?? 0);
            $category = trim($data['category'] ?? '');

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

            $warehouses = loadData('warehouses');
            $whIndex = null;
            foreach($warehouses as $idx => $w) {
                if(intval($w['id']) === $warehouseId) { $whIndex = $idx; break; }
            }

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

            $categories = json_decode($warehouses[$whIndex]['categories'] ?? '[]', true);
            if(!is_array($categories)) $categories = [];

            $categories = array_values(array_filter($categories, fn($c) => $c !== $category));
            sort($categories);

            $warehouses[$whIndex]['categories'] = json_encode($categories, JSON_UNESCAPED_UNICODE);
            saveData('warehouses', $warehouses);

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