<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use App\Models\SettingsTools;
use Illuminate\Support\Facades\Auth;

class SettingsToolsController extends Controller
{
    public function tools(): View
    {
        return view('admin.settings.tools.index', [
            'functions' => 'admin.settings.tools.function',
            'sidebar' => 'tools_settings',
            'pageName' => pageName([__('lang.settings'), __('lang.tools')]),
        ]);
    }

    public function tools_post(
        Request $request
    ): RedirectResponse {
        $request->validate([
            'convert' => 'required|in:0,1',
            'compress' => 'required|in:0,1',
            'resize' => 'required|in:0,1',
            'rotate-reflect' => 'required|in:0,1',
            'watermark' => 'required|in:0,1',
            'preferences' => 'required|in:0,1',
            'effects' => 'required|in:0,1',
            'exif-cleaner' => 'required|in:0,1',
            'autoremove' => 'required|in:0,1',
            'password' => 'required|in:0,1',
        ]);

        $inputs = $request->only([
            'convert',
            'compress',
            'resize',
            'rotate-reflect',
            'watermark',
            'preferences',
            'effects',
            'exif-cleaner',
            'autoremove',
            'password',
        ]);

        $userId = Auth::id();
        $userIp = $request->ip();

        foreach ($inputs as $key => $value) {
            $dbKey = str_replace("-", "_", $key);
            SettingsTools::where("name", $dbKey)
                ->update([
                    'updated_by_id' => $userId,
                    'updated_by_ip' => $userIp,
                    'value' => $value
                ]);
        }

        if (Cache::has('toolsSetting')) {
            Cache::forget('toolsSetting');
        }

        return back()
            ->with('success', __('lang.data_update'));
    }

}
