<?php

namespace App\Http\Controllers\Leasing;

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

class BranchController extends Controller
{
    public function index()
    {
        $this->authorize('viewAny', Branch::class);
        $profile = auth()->user()->leasingProfile;

        $branches = $profile->branches()->latest()->paginate(10);
        return view('leasing.branches.index', compact('branches'));
    }

    public function create()
    {
        $this->authorize('create', Branch::class);
        return view('leasing.branches.create');
    }

    public function store(Request $request)
    {
        $this->authorize('create', Branch::class);
        
        $data = $request->validate([
            'branch_name' => 'required|string|max:255',
            'address' => 'nullable|string',
            'phone' => 'nullable|string|max:20',
        ]);

        $profile = auth()->user()->leasingProfile;

        $profile->branches()->create($data);

        return redirect()->route('leasing.branches.index')->with('success', 'Cabang baru berhasil ditambahkan.');
    }

    public function edit(Branch $branch)
    {
        $this->authorize('update', $branch);
        return view('leasing.branches.edit', compact('branch'));
    }

    public function update(Request $request, Branch $branch)
    {
        $this->authorize('update', $branch);
        
        $data = $request->validate([
            'branch_name' => 'required|string|max:255',
            'address' => 'nullable|string',
            'phone' => 'nullable|string|max:20',
        ]);

        $branch->update($data);

        return redirect()->route('leasing.branches.index')->with('success', 'Data cabang berhasil diperbarui.');
    }

    public function destroy(Branch $branch)
    {
        $this->authorize('delete', $branch);
        $branch->delete();
        return back()->with('success', 'Cabang berhasil dihapus.');
    }
}
