<?php

namespace App\Http\Controllers\Admin\Pages\Settings;

use App\Http\Controllers\Controller;
use App\Http\Requests\Settings\SettingsUpdateRequest;
use App\Models\Setting;
use App\Traits\FileUploader;
use App\Traits\ImageCompressor;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\File;



class SettingController extends Controller
{
    use ImageCompressor,FileUploader;

    public function __construct()
    {
        $this->middleware('permission:edit settings')->only('edit');
        $this->middleware('permission:update settings')->only('update');
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Setting $setting)
    {
        $compressionPercents = [
            20 => 20,
            25 => 25,
            30 => 30,
            35 => 35,
            40 => 40,
            45 => 45,
            50 => 50,
            55 => 55,
            60 => 60,
            65 => 65,
            70 => 70,
            75 => 75,
            80 => 80,
            85 => 85,
            90 => 90,
            95 => 95,
            100 => 100,
        ];
        return view('app.admin.pages.settings.edit-settings',compact([
            'setting',
            'compressionPercents'
        ]));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(SettingsUpdateRequest $request, Setting $setting)
    {
        $validatedData =$request->validated();

        if ($request->hasFile('logo_image')) {
            File::delete('/storage/images/' . $setting->getAttribute('logo_image'));
            $validatedData['image'] = self::compressImage($request->file('logo_image'), 'LogoImage');
        } else {
            $validatedData['logo_image'] = $setting->getAttribute('logo_image');
        }

        if ($request->hasFile('back_image')) {
            File::delete('/storage/images/' . $setting->getAttribute('back_image'));
            $validatedData['back_image'] = self::compressImage($request->file('back_image'), 'BackImage');
        } else {
            $validatedData['back_image'] = $setting->getAttribute('back_image');
        }




    //    if ($request->hasFile('back_image')) {
    //     $validatedData['back_image'] = self::compressImage($request->file('back_image'), 'BackImage');
    // }

        // if ($request->hasFile('ceoImage')) {
        //     $imageName = time().'.'.$request->ceoImage->extension();
        //     $request->ceoImage->move(public_path('storage/images'), $imageName);
        //     $validatedData['image'] = $imageName;
        // }

       $setting->update($validatedData);

       Cache::forget('settings');
       return back()->with('success',__('Data successfully updated!'));
    }
}
