<?php

/**
 * ============================================================
 *
 * @project   biiproject
 *
 * @author    Andika Debi Putra
 *
 * @email     andikadebiputra@gmail.com
 *
 * @website   https://biiproject.com
 *
 * @copyright Copyright (c) 2026 Andika Debi Putra
 * @license   Proprietary - All Rights Reserved
 *
 * @version   1.0.0
 *
 * @created   2026-05-01
 * ============================================================
 *
 * Unauthorized copying, modification, distribution, or use
 * of this file is strictly prohibited without prior written
 * permission from the author.
 * ============================================================
 */

namespace App\Http\Controllers;

use App\Models\DashboardWidgetPreference;
use App\Services\Monitoring\SystemMonitoringService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class DashboardController extends Controller
{
    public function __construct(
        protected SystemMonitoringService $monitor
    ) {}

    public function index()
    {
        $stats   = $this->monitor->getAll();
        $widgets = DashboardWidgetPreference::forUser(auth()->id());

        return view('pages.dashboard', compact('stats', 'widgets'));
    }

    /**
     * Save widget visibility + order for the authenticated user.
     */
    public function saveWidgetPreferences(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'widgets'              => ['required', 'array'],
            'widgets.*.key'        => ['required', 'string', 'max:64'],
            'widgets.*.visible'    => ['required', 'boolean'],
            'widgets.*.sort_order' => ['required', 'integer', 'min:0'],
        ]);

        $userId = auth()->id();

        foreach ($validated['widgets'] as $w) {
            DashboardWidgetPreference::updateOrCreate(
                ['user_id' => $userId, 'widget_key' => $w['key']],
                ['visible' => $w['visible'], 'sort_order' => $w['sort_order']]
            );
        }

        return response()->json(['status' => 'ok']);
    }

    /**
     * Reset widget preferences to defaults.
     */
    public function resetWidgetPreferences()
    {
        DashboardWidgetPreference::where('user_id', auth()->id())->delete();

        return back()->with('success', 'Dashboard layout reset to defaults.');
    }
}
