<?php

namespace App\Http\Controllers\Backend;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;

class ConfigController extends Controller
{
    public function index()
    {
        $company = auth()->user()->company;
        return view('backend.configs.index', compact('company'));
    }

    public function update(Request $request)
    {
        $this->validate($request, [
            'logo' => 'mimes:jpeg,jpg,png,gif'
        ],[
            'logo.mimes' => 'Le logo doit être au format jpeg,jpg,png',
            'logo.required' => 'Le logo est obligatoire'
        ]);

        $company = auth()->user()->company;
        //$company->description = $request->input('description');
        //$company->values = $request->input('values');
        $company->fill($request->except('logo'));
        $company->save();

        if( $request->hasFile('logo') ) {
            // Delete old file
            $path = 'public/companies/'. $company->id . '/' . $company->image;
            if(File::exists(storage_path('app/' . $path))) {
                Storage::delete($path);
            }
            // Upload new file
            $file = $request->file('logo');
            $path = 'public/companies/'. $company->id . '/';
            $path = $request->file('logo')->storeAs($path, 'logo.' . $file->getClientOriginalExtension());
            $company->image = 'logo.' . $file->getClientOriginalExtension();
            $company->save();
        }

        return redirect()->route('backend.configs.index');
    }
}
