<?php

namespace App\Http\Controllers\Client;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
use App\Models\Country;
use App\Models\Wilaya;
use App\Models\Commune;
use App\Models\Company;

class ConfigController extends Controller
{
    public function index()
    {
        $company = auth()->user()->company;
        $companies = Company::pluck('name', 'id');
        $countries = Country::pluck('name_fr', 'id');
        $wilayas = Wilaya::pluck('name', 'id');
        $communes = Commune::where('wilaya_id', $company->wilaya_id)->pluck('name', 'id');
        return view('clients.configs.index', compact('company', 'countries', 'wilayas', 'communes', 'companies'));
    }

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

        $company = auth()->user()->company;
        //$company->description = $request->input('description');
        //$company->values = $request->input('values');
        $company->fill($request->except(['optionsGroupe', 'image']));
        $company->save();

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

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

    public function communesSelect($wilaya_id)
    {
        $communes = Commune::where('wilaya_id', $wilaya_id)->get();
        return view('backend.companies.communes', compact('communes'));
    }
}
