<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;

class SettingController extends Controller
{
    public function index()
    {
        return view('admin.settings');
    }

    public function update(Request $request)
    {
        $data = $request->except(['_token', 'logo', 'favicon']);

        // Handle standard text inputs
        foreach ($data as $key => $value) {
            Setting::set($key, $value);
        }

        // Handle Logo Upload
        if ($request->hasFile('logo')) {
            $request->validate(['logo' => 'image|max:2048']);
            $file = $request->file('logo');
            $filename = 'logo_' . time() . '.' . $file->getClientOriginalExtension();
            $file->move(public_path('images/branding'), $filename);
            Setting::set('site_logo', $filename);
        }

        // Handle Favicon Upload
        if ($request->hasFile('favicon')) {
            $request->validate(['favicon' => 'image|max:512']);
            $file = $request->file('favicon');
            $filename = 'favicon_' . time() . '.' . $file->getClientOriginalExtension();
            $file->move(public_path('images/branding'), $filename);
            Setting::set('site_favicon', $filename);
        }

        // Clear views cache if site name/details changed
        Artisan::call('view:clear');

        return redirect()->back()->with('success', 'Settings updated successfully.');
    }
}
