<?php
/**
 * Fichier  : api/suppliers.php
 * Auteur   : KREMER Régis
 * Version  : 2.3.0
 * Date     : 2026-03-14
 * Description : API REST — CRUD des fournisseurs avancés
 */
require_once dirname(__DIR__).'/config.php';

startSession();
requireAuth();

$method = $_SERVER['REQUEST_METHOD'];
if ($method !== 'GET') {
    requireAdmin();
    csrfCheck();
}

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

function normalizeSupplierRecord(array $s): array {
    $linkedBrands = $s['linkedBrands'] ?? [];
    if (is_string($linkedBrands)) {
        $decoded = json_decode($linkedBrands, true);
        $linkedBrands = is_array($decoded) ? $decoded : [];
    }

    $contacts = $s['contacts'] ?? [];
    if (is_string($contacts)) {
        $decoded = json_decode($contacts, true);
        $contacts = is_array($decoded) ? $decoded : [];
    }

    $s['companyName'] = trim((string)($s['companyName'] ?? ''));
    $s['contact'] = trim((string)($s['contact'] ?? ''));
    $s['email'] = trim((string)($s['email'] ?? ''));
    $s['phone'] = trim((string)($s['phone'] ?? ''));
    $s['website'] = trim((string)($s['website'] ?? ''));
    $s['address'] = trim((string)($s['address'] ?? ''));
    $s['siret'] = trim((string)($s['siret'] ?? ''));
    $s['vatNumber'] = trim((string)($s['vatNumber'] ?? ''));
    $s['leadTime'] = (int)($s['leadTime'] ?? $s['leadTimeDays'] ?? 0);
    $s['minimumOrderAmount'] = round((float)($s['minimumOrderAmount'] ?? 0), 2);
    $s['freeShippingThreshold'] = round((float)($s['freeShippingThreshold'] ?? 0), 2);
    $s['paymentTerms'] = trim((string)($s['paymentTerms'] ?? ''));
    $status = trim((string)($s['status'] ?? 'active'));
    $s['status'] = in_array($status, ['active', 'watch', 'inactive', 'blocked'], true) ? $status : 'active';
    $s['notes'] = trim((string)($s['notes'] ?? ''));
    $s['linkedBrands'] = array_values(array_map('intval', array_filter(is_array($linkedBrands) ? $linkedBrands : [], static fn($v) => $v !== '' && $v !== null)));
    $s['contacts'] = array_values(array_filter(array_map(static function($contact) {
        if (!is_array($contact)) return null;
        return [
            'type' => trim((string)($contact['type'] ?? 'commercial')),
            'name' => trim((string)($contact['name'] ?? '')),
            'role' => trim((string)($contact['role'] ?? '')),
            'phone' => trim((string)($contact['phone'] ?? '')),
            'email' => trim((string)($contact['email'] ?? '')),
        ];
    }, is_array($contacts) ? $contacts : []), static fn($contact) => is_array($contact) && array_filter($contact)));

    return $s;
}

switch ($method) {
    case 'GET':
        $suppliers = array_map('normalizeSupplierRecord', loadData('suppliers'));
        $q = mb_strtolower(trim((string)($_GET['q'] ?? '')));
        if ($q !== '') {
            $suppliers = array_filter($suppliers, static function(array $s) use ($q): bool {
                $haystack = [
                    $s['name'] ?? '',
                    $s['companyName'] ?? '',
                    $s['contact'] ?? '',
                    $s['email'] ?? '',
                    $s['phone'] ?? '',
                    $s['website'] ?? '',
                    $s['address'] ?? '',
                    $s['siret'] ?? '',
                    $s['vatNumber'] ?? '',
                    $s['paymentTerms'] ?? '',
                    $s['notes'] ?? '',
                ];
                foreach (($s['contacts'] ?? []) as $c) {
                    $haystack[] = $c['name'] ?? '';
                    $haystack[] = $c['role'] ?? '';
                    $haystack[] = $c['phone'] ?? '';
                    $haystack[] = $c['email'] ?? '';
                }
                $blob = mb_strtolower(implode(' ', $haystack));
                return str_contains($blob, $q);
            });
        }
        jsonResponse(array_values($suppliers));

    case 'POST':
        $name = trim((string)($body['name'] ?? ''));
        if ($name === '') {
            jsonError('Nom obligatoire.');
        }
        $item = normalizeSupplierRecord(addItem('suppliers', [
            'name' => $name,
            'companyName' => trim((string)($body['companyName'] ?? '')),
            'contact' => trim((string)($body['contact'] ?? '')),
            'email' => trim((string)($body['email'] ?? '')),
            'phone' => trim((string)($body['phone'] ?? '')),
            'website' => trim((string)($body['website'] ?? '')),
            'address' => trim((string)($body['address'] ?? '')),
            'siret' => trim((string)($body['siret'] ?? '')),
            'vatNumber' => trim((string)($body['vatNumber'] ?? '')),
            'linkedBrands' => $body['linkedBrands'] ?? [],
            'leadTime' => (int)($body['leadTime'] ?? 0),
            'minimumOrderAmount' => round((float)($body['minimumOrderAmount'] ?? 0), 2),
            'freeShippingThreshold' => round((float)($body['freeShippingThreshold'] ?? 0), 2),
            'paymentTerms' => trim((string)($body['paymentTerms'] ?? '')),
            'status' => trim((string)($body['status'] ?? 'active')),
            'contacts' => $body['contacts'] ?? [],
            'notes' => trim((string)($body['notes'] ?? '')),
        ]));
        jsonResponse($item, 201);

    case 'PUT':
        $id = $body['id'] ?? null;
        if (!$id) {
            jsonError('ID manquant.');
        }
        $fields = [];
        foreach (['name','companyName','contact','email','phone','website','address','siret','vatNumber','linkedBrands','leadTime','minimumOrderAmount','freeShippingThreshold','paymentTerms','status','contacts','notes'] as $k) {
            if (array_key_exists($k, $body)) {
                $fields[$k] = $body[$k];
            }
        }
        $updated = updateItem('suppliers', $id, normalizeSupplierRecord($fields));
        $updated ? jsonResponse(normalizeSupplierRecord($updated)) : jsonError('Non trouvé.', 404);

    case 'DELETE':
        $id = $body['id'] ?? $_GET['id'] ?? null;
        if (!$id) {
            jsonError('ID manquant.');
        }
        $allSuppliers = loadData('suppliers');
        $supplierToDelete = findById($allSuppliers, $id);
        $supplierName = $supplierToDelete ? ($supplierToDelete['name'] ?? '') : '';

        $products = loadData('products');
        foreach ($products as &$p) {
            if (isset($p['supplier']) && (($supplierName !== '' && (string)$p['supplier'] === $supplierName) || (string)$p['supplier'] === (string)$id)) {
                $p['supplier'] = '';
            }
        }
        unset($p);
        saveData('products', $products);
        deleteItem('suppliers', $id);
        jsonResponse(['ok' => true]);

    default:
        jsonError('Méthode non supportée.', 405);
}
