<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Setting;

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



   public function update(Request $request, $id)
    {
        $setting = Setting::findOrFail($id);

        $request->validate([
          'logo' => 'image|mimes:jpeg,png,jpg,webp',
          'favicon' => 'mimes:ico,webp'
        ]);

        $input = $request->all();

        if ($file = $request->file('logo')) {

          $name = 'logo_'.time().'_'.preg_replace('/[^a-zA-Z0-9._-]/', '', $file->getClientOriginalName());
          if ($setting->logo && file_exists(public_path().'/images/logo/'.$setting->logo)) {
              unlink(public_path().'/images/logo/'.$setting->logo);
          }
          $file->move('images/logo/', $name);
          $input['logo'] = $name;

        }

        if ($file2 = $request->file('favicon')) {

            $name2 = 'favicon_'.time().'_'.preg_replace('/[^a-zA-Z0-9._-]/', '', $file2->getClientOriginalName());
            if ($setting->favicon && file_exists(public_path().'/images/logo/'.$setting->favicon)) {
                unlink(public_path().'/images/logo/'.$setting->favicon);
            }
            $file2->move('images/logo/', $name2);
            $input['favicon'] = $name2;

        }

        $setting->update($input);
        return back()->with('updated', 'Settings have been saved');

    }
}
