<?php

namespace App\Http\Controllers;

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

class BranchController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        // Retrieve all branches, ordered by name
        $branches = Branch::orderBy('name')->get();
        return view('branches.index', compact('branches'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:branches,name',
            'code' => 'required|string|max:5|unique:branches,code',
            'is_active' => 'sometimes|boolean',
        ]);

        Branch::create($validated);

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

    /**
     * Display the specified resource.
     */
    public function show(Branch $branch)
    {
        return view('branches.show', compact('branch'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Branch $branch)
    {
        $validated = $request->validate([
            // Ensure unique names/codes but ignore the current branch's own value
            'name' => ['required', 'string', 'max:255', Rule::unique('branches')->ignore($branch->id)],
            'code' => ['required', 'string', 'max:5', Rule::unique('branches')->ignore($branch->id)],
            'is_active' => 'sometimes|boolean',
        ]);

        $branch->update($validated);

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

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Branch $branch)
    {
        // You should add logic here to check if the branch can be deleted (e.g., no active users assigned)
        $branch->delete();

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