<?php

namespace App\Http\Controllers\API;

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

class BranchController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();
        $query = Branch::query();

        if ($user && in_array($user->role, ['super_admin', 'regional_manager'])) {
            // Super Admin and Regional Manager get access to all store branches
        } elseif ($user && in_array($user->role, ['store_manager', 'cashier'])) {
            $query->where('id', $user->branch_id ?? 1);
        }

        $branches = $query->orderBy('name')->get();

        return response()->json([
            'success' => true,
            'data' => $branches,
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50|unique:branches,code',
            'city' => 'nullable|string',
            'address' => 'nullable|string',
            'phone' => 'nullable|string',
            'gstin' => 'nullable|string',
        ]);

        $branch = Branch::create([
            'name' => $request->name,
            'code' => strtoupper($request->code),
            'city' => $request->city,
            'address' => $request->address,
            'phone' => $request->phone,
            'gstin' => $request->gstin,
            'status' => 'active',
        ]);

        // Copy existing product catalog to new branch stock with stock = 0
        $products = Product::all();
        foreach ($products as $p) {
            BranchProductStock::create([
                'branch_id' => $branch->id,
                'product_id' => $p->id,
                'current_stock' => 0,
                'min_stock_alert' => $p->min_stock_alert ?? 5,
            ]);
        }

        return response()->json([
            'success' => true,
            'message' => 'Branch location created successfully',
            'data' => $branch,
        ]);
    }

    public function update(Request $request, $id)
    {
        $branch = Branch::findOrFail($id);

        $request->validate([
            'name' => 'sometimes|string|max:255',
            'city' => 'nullable|string',
            'address' => 'nullable|string',
            'phone' => 'nullable|string',
            'gstin' => 'nullable|string',
            'status' => 'sometimes|in:active,inactive',
        ]);

        $branch->update($request->only(['name', 'city', 'address', 'phone', 'gstin', 'status']));

        return response()->json([
            'success' => true,
            'message' => 'Branch updated successfully',
            'data' => $branch,
        ]);
    }
}
