<?php

declare(strict_types=1);

namespace MauticPlugin\DealFlowBundle\Controller;

use Mautic\CoreBundle\Controller\CommonController;
use Mautic\DashboardBundle\Model\DashboardModel;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

class DashboardAjaxController extends CommonController
{
    public function saveWidgetConfigAction(Request $request, DashboardModel $dashboardModel): JsonResponse
    {
        $widgetId = (int) $request->request->get('widgetId');
        $params = $request->request->all('params');

        if (!$widgetId) {
            return new JsonResponse(['success' => false, 'error' => 'Missing widget ID'], 400);
        }

        $widget = $dashboardModel->getEntity($widgetId);

        if (!$widget) {
            return new JsonResponse(['success' => false, 'error' => 'Widget not found'], 404);
        }

        $existingParams = $widget->getParams() ?? [];
        foreach ($params as $key => $value) {
            if ($value === '' || $value === null) {
                unset($existingParams[$key]);
            } else {
                $existingParams[$key] = $value;
            }
        }
        $widget->setParams($existingParams);
        $dashboardModel->saveEntity($widget);

        return new JsonResponse(['success' => true]);
    }
}
