<?php
/**
 * modulos-cd.php
 * CRUD de módulos asignados a un Centro de Distribución.
 *
 * GET  ?cd_id=N  → lista las keys de módulos activos para ese centro
 * POST { cd_id, modulos: ["key1","key2",...] } → reemplaza todos los módulos
 */

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }

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

// ── Auth ─────────────────────────────────────────────────────────────────────
$headers    = function_exists('getallheaders') ? getallheaders() : [];
$authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
if (!$authHeader && !empty($_SERVER['HTTP_AUTHORIZATION'])) {
    $authHeader = $_SERVER['HTTP_AUTHORIZATION'];
} elseif (!$authHeader && !empty($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
    $authHeader = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
}

if (!preg_match('/Bearer\s+(.+)/i', $authHeader, $m)) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'Token requerido']);
    exit;
}
$token = trim($m[1]);
$db    = getDB();
$now   = date('Y-m-d H:i:s');

$stmtSess = $db->prepare(
    "SELECT idusuarios_sist FROM admin_sessions WHERE token = ? AND expira > ? LIMIT 1"
);
$stmtSess->execute([$token, $now]);
if (!$stmtSess->fetch()) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'Sesión expirada o inválida']);
    exit;
}

// ── Whitelist de módulos válidos ─────────────────────────────────────────────
$MODULOS_VALIDOS = [
    'avisos', 'distribuidores', 'kyc', 'transacciones', 'productos',
    'ganancias-regs', 'voucher-grupal', 'notas-asignar', 'ordenes-pendientes',
    'inventario', 'pedidos-stock', 'nueva-compra', 'agrupaciones', 'entrega',
    'depositos-banco', 'reportes'
];

// ═══════════════════════════════════════════════════════════════════════════════
// GET — listar módulos de un centro
// ═══════════════════════════════════════════════════════════════════════════════
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $cdId = isset($_GET['cd_id']) ? (int)$_GET['cd_id'] : 0;
    if ($cdId <= 0) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'cd_id requerido']);
        exit;
    }

    $stmt = $db->prepare("SELECT modulo_key FROM cd_modulos WHERE cd_id = ? ORDER BY modulo_key");
    $stmt->execute([$cdId]);
    $modulos = $stmt->fetchAll(PDO::FETCH_COLUMN);

    echo json_encode(['ok' => true, 'cd_id' => $cdId, 'modulos' => $modulos]);
    exit;
}

// ═══════════════════════════════════════════════════════════════════════════════
// POST — guardar (reemplaza todos los módulos del centro)
// ═══════════════════════════════════════════════════════════════════════════════
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $body = json_decode(file_get_contents('php://input'), true);
    $cdId    = isset($body['cd_id'])   ? (int)$body['cd_id'] : 0;
    $modulos = isset($body['modulos']) ? $body['modulos']    : [];

    if ($cdId <= 0) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'cd_id requerido']);
        exit;
    }

    // Filtrar solo keys válidas
    $modulos = array_values(array_filter($modulos, function ($k) use ($MODULOS_VALIDOS) {
        return in_array($k, $MODULOS_VALIDOS, true);
    }));

    try {
        $db->beginTransaction();

        // Borrar todos los actuales
        $stmtDel = $db->prepare("DELETE FROM cd_modulos WHERE cd_id = ?");
        $stmtDel->execute([$cdId]);

        // Insertar nuevos
        if (count($modulos) > 0) {
            $stmtIns = $db->prepare("INSERT INTO cd_modulos (cd_id, modulo_key) VALUES (?, ?)");
            foreach ($modulos as $key) {
                $stmtIns->execute([$cdId, $key]);
            }
        }

        $db->commit();
        echo json_encode([
            'ok'      => true,
            'cd_id'   => $cdId,
            'modulos' => $modulos,
            'total'   => count($modulos)
        ]);
    } catch (PDOException $e) {
        $db->rollBack();
        http_response_code(500);
        echo json_encode(['ok' => false, 'error' => 'Error BD: ' . $e->getMessage()]);
    }
    exit;
}

http_response_code(405);
echo json_encode(['ok' => false, 'error' => 'Método no permitido']);
