<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Bien;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;

class BienController extends Controller
{
    public function index(): View
    {
        $biens = Bien::query()->latest()->paginate(15);

        return view('admin.biens.index', compact('biens'));
    }

    public function create(): View
    {
        return view('admin.biens.create');
    }

    public function store(Request $request): RedirectResponse
    {
        $data = $this->validated($request, true);
        $data['image_path'] = $request->file('image')->store('biens', 'public');

        Bien::query()->create($data);

        return redirect()->route('admin.biens.index')->with('status', 'Bien ajouté.');
    }

    public function edit(Bien $bien): View
    {
        return view('admin.biens.edit', compact('bien'));
    }

    public function update(Request $request, Bien $bien): RedirectResponse
    {
        $data = $this->validated($request, false);

        if ($request->hasFile('image')) {
            if ($bien->image_path) {
                Storage::disk('public')->delete($bien->image_path);
            }
            $data['image_path'] = $request->file('image')->store('biens', 'public');
        }

        $bien->update($data);

        return redirect()->route('admin.biens.index')->with('status', 'Bien mis à jour.');
    }

    public function destroy(Bien $bien): RedirectResponse
    {
        if ($bien->image_path) {
            Storage::disk('public')->delete($bien->image_path);
        }
        $bien->delete();

        return redirect()->route('admin.biens.index')->with('status', 'Bien supprimé.');
    }

    /**
     * @return array<string, mixed>
     */
    private function validated(Request $request, bool $imageRequired): array
    {
        $rules = [
            'nom' => ['required', 'string', 'max:255'],
            'lieu' => ['required', 'string', 'max:255'],
            'superficie' => ['required', 'numeric', 'min:0'],
            'telephone' => ['required', 'string', 'max:32'],
            'prix' => ['nullable', 'numeric', 'min:0'],
        ];

        $rules['image'] = $imageRequired
            ? ['required', 'image', 'max:4096']
            : ['nullable', 'image', 'max:4096'];

        /** @var array<string, mixed> $data */
        $data = $request->validate($rules);

        unset($data['image']);

        if (! array_key_exists('prix', $data) || $data['prix'] === '' || $data['prix'] === null) {
            $data['prix'] = null;
        }

        return $data;
    }
}
