<?php

namespace App\Http\Controllers;

use App\Models\Area;
use Illuminate\Http\Request;

class AreaController extends Controller
{
    public function index()
    {
        $areas = Area::orderBy('area_id', 'desc')->get();

        return view('area.list', compact('areas'));
    }

    public function create()
    {
        return view('area.add');
    }

    public function store(Request $request)
    {
        $request->validate([
            'area_name' => 'required|string|max:255|unique:area,area_name',
        ]);

        Area::create([
            'area_name' => $request->area_name,
        ]);

        return redirect()
            ->route('area.list')
            ->with('success', 'Area added successfully.');
    }

    public function edit($id)
    {
        $area = Area::findOrFail($id);

        return view('area.edit', compact('area'));
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'area_name' => 'required|string|max:255|unique:area,area_name,' . $id . ',area_id',
        ]);

        $area = Area::findOrFail($id);

        $area->update([
            'area_name' => $request->area_name,
        ]);

        return redirect()
            ->route('area.list')
            ->with('success', 'Area updated successfully.');
    }

    public function destroy($id)
    {
        $area = Area::findOrFail($id);

        $area->delete();

        return redirect()
            ->route('area.list')
            ->with('success', 'Area deleted successfully.');
    }
}