<?php

class DashboardConfigApiController extends Controller
{
    public function load(Request $request): void
    {
        $db = $this->db();

        $layout = $db->fetchOne(
            "SELECT * FROM dashboard_user_layouts WHERE user_id = ? AND is_default = 1",
            [Auth::id()]
        );

        $allWidgets = $db->fetchAll("SELECT * FROM dashboard_widgets WHERE is_active = 1 ORDER BY sort_order");

        $this->json([
            'success'    => true,
            'layout'     => $layout,
            'widgets'    => $allWidgets,
        ]);
    }

    public function save(Request $request): void
    {
        $db = $this->db();
        $widgets = $request->post('widgets', '[]');

        if (is_string($widgets)) {
            $decoded = json_decode($widgets, true);
            if ($decoded === null) {
                $this->json(['success' => false, 'message' => 'Invalid JSON'], 422);
                return;
            }
            $widgets = $decoded;
        }

        $existing = $db->fetchOne(
            "SELECT id FROM dashboard_user_layouts WHERE user_id = ? AND is_default = 1",
            [Auth::id()]
        );

        if ($existing) {
            $db->update('dashboard_user_layouts', [
                'widgets' => json_encode($widgets, JSON_UNESCAPED_UNICODE),
            ], 'id = ?', [$existing['id']]);
        } else {
            $db->insert('dashboard_user_layouts', [
                'user_id'     => Auth::id(),
                'layout_name' => 'default',
                'widgets'     => json_encode($widgets, JSON_UNESCAPED_UNICODE),
                'is_default'  => 1,
            ]);
        }

        $this->json(['success' => true, 'message' => lang('reports.dashboard_saved')]);
    }
}