<?php

namespace App\Http\Controllers;

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

class BranchController extends Controller
{
    public function index()
    {
        $branches = Branch::orderBy('name')->get();
        return view('branches', compact('branches'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|regex:/^[a-zA-Z0-9\s]+$/|unique:branches|max:255',
        ], [
            'name.regex' => 'Nama cabang hanya boleh berisi huruf, angka, dan spasi.',
            'name.unique' => 'Nama cabang ini sudah terdaftar.',
        ]);

        Branch::create([
            'name' => $request->name,
        ]);

        return back()->with('success', 'Cabang baru berhasil ditambahkan!');
    }

    public function destroy($id)
    {
        $branch = Branch::findOrFail($id);
        $branch->delete();
        
        return back()->with('success', 'Cabang berhasil dihapus!');
    }
}
