<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\{CompanySetting, SlaConfig, ActivityLog};
use Illuminate\Http\Request;

class SettingController extends Controller
{
    public function index()
    {
        $settings = CompanySetting::all()->keyBy('division');
        return view('admin.settings.index', compact('settings'));
    }

    public function update(Request $request)
    {
        foreach (['JPN','FixLab','Havva'] as $div) {
            if (!$request->has($div)) continue;
            $s = CompanySetting::firstOrNew(['division'=>$div]);
            $s->fill($request->input($div));
            if ($request->hasFile("{$div}.logo")) {
                $path = $request->file("{$div}.logo")->store("logos", 'public');
                $s->logo_path = $path;
            }
            $s->save();
        }
        return back()->with('success','Pengaturan disimpan.');
    }

    public function sla()
    {
        $configs = SlaConfig::all();
        return view('admin.settings.sla', compact('configs'));
    }

    public function updateSla(Request $request)
    {
        foreach ($request->input('configs',[]) as $id => $cfg) {
            SlaConfig::updateOrCreate(['id'=>$id], $cfg);
        }
        return back()->with('success','Konfigurasi SLA disimpan.');
    }

    public function activityLog(Request $request)
    {
        $q = ActivityLog::with('user')->orderByDesc('created_at');
        if ($request->module)  $q->where('module', $request->module);
        if ($request->user_id) $q->where('user_id', $request->user_id);
        $logs  = $q->paginate(50)->withQueryString();
        $users = \App\Models\User::all();
        return view('admin.settings.activity', compact('logs','users'));
    }
}
