<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Models\companyBranch;
use App\Models\company;

class companyBranchController extends Controller
{
    public function index()
    {
        // Fetch branches with their associated company names
        $branches = CompanyBranch::select('id', 'company_id', 'branchName', 'branchShortCode', 'wearHouse')
            ->with(['company' => function ($query) {
                $query->select('id', 'name'); // Only select the necessary fields from the company table
            }])
            ->get();

        // Transform the data to include the company name
        $formattedBranches = $branches->map(function ($branch) {
            return [
                'id' => $branch->id,
                'company_id' => $branch->company_id,
                'company_name' => $branch->company ? $branch->company->name : null, // Include company name
                'branchName' => $branch->branchName,
                'branchShortCode' => $branch->branchShortCode,
                'wearHouse' => $branch->wearHouse,
            ];
        });

        return response()->json($formattedBranches);
    }
    public function store(Request $request)
    {
        $request->validate([
            'company_id' => 'required | integer',
            'branchName' => 'required | max:255',
            'branchShortCode' => 'required | max:10',
            'wearHouse' => 'required|boolean',
        ]);

        $branch = CompanyBranch::create([
            'company_id' => $request->company_id,
            'branchName' => $request->branchName,
            'branchShortCode' => $request->branchShortCode,
            'wearHouse' => $request->wearHouse ? 1 : 0,
        ]);

        return response()->json($branch, 201);
    }

    public function update(Request $request, $id)
    {
        $branch = CompanyBranch::find($id);
        if (!$branch) {
            return response()->json(['message' => 'Branch not found'], 404);
        }

        request()->validate([
            'company_id' => 'required|integer',
            'branchName' => 'required',
            'branchShortCode' => 'required',
            'wearHouse' => 'required|boolean',
        ]);

        $branch->update([
            'company_id' => $request->company_id,
            'branchName' => $request->branchName,
            'branchShortCode' => $request->branchShortCode,
            'wearHouse' => $request->wearHouse ? 1 : 0,
        ]);

        return response()->json($branch);
    }

    public function show($id)
{
    $branches = CompanyBranch::where('company_id', $id)
        ->get(['id', 'branchName', 'branchShortCode']);

    if ($branches->isEmpty()) {
        return response()->json(['message' => 'No branches found for this company'], 404);
    }

    return response()->json($branches);
}
}
