<?php

namespace App\Http\Controllers\Client;

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

class PlaceController extends Controller
{
    public function index(Request $request)
    {
        $query = !empty($request->get('q')) ? $request->get('q') : null;
        if($query) {
            $places = Place::Client()->search($query, null, true)->paginate(20);
        }else{
            $places = Place::Client()->paginate(20);
        }
        return view('clients.places.index', compact('places'));
    }

    public function create()
    {
        $countries = Country::pluck('name_fr', 'id');
        return view('clients.places.create', compact('countries'));
    }

    public function store(Request $request)
    {
        $place = Place::Client()->create($request->input());
        $place->company_id = auth()->user()->company_id;
        $place->save();

        if( $request->hasFile('image') ) {
            $file = $request->file('image');
            $path = 'public/companies/'. $place->company_id . '/places/';
            $path = $request->file('image')->storeAs($path, $place->id . '.' . $file->getClientOriginalExtension());
            $place->image = $place->id . '.' . $file->getClientOriginalExtension();
            $place->save();
        }

        return redirect()->route('clients.places.show', $place->id );
    }

    public function show($id)
    {
        $place = Place::Client()->findOrFail($id);
        return view('clients.places.show', compact('place'));
    }

    public function edit($id)
    {
        $countries = Country::pluck('name_fr', 'id');
        $place = Place::Client()->findOrFail($id);
        return view('clients.places.edit', compact('place', 'countries'));
    }

    public function update(Request $request, $id)
    {
        $place = Place::Client()->findOrFail($id);
        $place->fill($request->input());
        $place->save();

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

        return redirect()->route('clients.places.show', $place->id );
    }

    public function delete($id)
    {
        $place = Place::Client()->findOrFail($id);
        $place->delete();

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