<?php

namespace App\Http\Controllers;

use App\Models\Place;
use App\Models\Province;
use Illuminate\Http\Request;

use function Psy\debug;

class PlaceController extends Controller
{
    public $paginate = 10;
    public function index()
    {
        $places = Place::orderBy('id', 'DESC')->paginate(5);

        return view('pages.places.index', compact('places'));
    }

    public function create()
    {
        $provinces = Province::orderBy('name_th', 'ASC')->get();
        return view('pages.places.create', compact('provinces'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
            // 'image' => 'required|image|mimes:jpeg,png,jpg|max:8192',
        ]);

        $input = $request->all();

        if($request['image'] != null){
            $request->validate([
                'image' => 'required|image|mimes:jpeg,png,jpg|max:8192',
            ]);
            $imageName = time() . '.' . $request->image->extension();
            $request->image->move(public_path('images/places'), $imageName);
            // $input['image_url'] = public_path('images/'. $imageName) ;
            $hostwithHttp = request()->getSchemeAndHttpHost();
            $input['image_url'] = $hostwithHttp . '/images/places/' . $imageName;
        }

        /* Store $imageName name in DATABASE from HERE */

        Place::create($input);

        return redirect()->route('places.index')
            ->with('success', 'Place created successfully.');
    }

    public function show(Place $place)
    {
        return view('pages.places.show', compact('place'));
    }

    public function edit(Place $place)
    {
        $provinces = Province::orderBy('name_th', 'ASC')->get();
        return view('pages.places.edit', compact('place', 'provinces'));
    }

    public function update(Request $request, Place $place)
    {
        $request->validate([
            'name' => 'required',
            'image' => 'nullable|image|mimes:jpeg,png,jpg|max:8192',
        ]);

        $input = $request->all();
        if($request->image != null){
            $imageName = time() . '.' . $request->image->extension();
            $request->image->move(public_path('images'), $imageName);
            // $input['image_url'] = public_path('images/'. $imageName) ;
            $hostwithHttp = request()->getSchemeAndHttpHost();
            $input['image_url'] = $hostwithHttp . '/images/' . $imageName;
        }


        $place->update($input);
        // $place->update($request->all());

        return redirect()->route('places.index')
            ->with('success', 'Place updated successfully');
    }

    public function destroy(Place $place)
    {
        $place->delete();

        return redirect()->route('places.index')
            ->with('success', 'Place deleted successfully');
    }
}
