<?php

namespace App\Http\Controllers\Api;

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

class BranchController extends Controller
{
    public function index(Request $request)
    {
        // Only branches the authenticated user may access.
        $ids = $request->user()?->accessibleBranchIds() ?? Branch::pluck('id')->all();

        return response()->json(['data' => Branch::whereIn('id', $ids)->where('is_active', true)->orderBy('name')->get()]);
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name' => ['required', 'string'],
            'code' => ['required', 'string', 'unique:branches,code'],
            'phone' => ['nullable', 'string'],
            'email' => ['nullable', 'email'],
            'address' => ['nullable', 'string'],
        ]);

        return response()->json(['data' => Branch::create($data)], 201);
    }

    public function update(Request $request, Branch $branch)
    {
        $branch->update($request->only(['name', 'code', 'phone', 'email', 'address', 'is_active']));

        return response()->json(['data' => $branch]);
    }

    public function destroy(Branch $branch)
    {
        $branch->delete();

        return response()->json(['success' => true]);
    }
}
