<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Country;
use Illuminate\Http\Request;

class CountryController extends Controller
{
    public function index()
    {
        $countries = Country::all();
        return view('countries.index', compact('countries'));
    }

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

    public function store(Request $request)
    {
        $request->validate(['name' => 'required']);
        Country::create($request->only(['name', 'code']));
        return redirect()->route('countries.index')->with('success', 'Country created.');
    }

    public function edit($id)
    {
        $country = Country::findOrFail($id);
        return view('countries.edit', compact('country'));
    }

    public function update(Request $request,  $id)
    {
         $country = Country::findOrFail($id);
        $request->validate(['name' => 'required']);
        $country->update($request->only(['name', 'code']));
        return redirect()->route('countries.index')->with('success', 'Country updated.');
    }

    public function destroy( $id)
    {
         $country = Country::findOrFail($id);
        $country->delete();
        return redirect()->route('countries.index')->with('success', 'Country deleted.');
    }
}
