<?php

namespace App\Http\Controllers\Client;

use App\Http\Controllers\Controller;
use App\Models\Branch;
use App\Models\Company;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;


class BranchController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:قائمة فروع الشركة', ['only' => ['index']]);
        $this->middleware('permission:اضافة فرع جديد', ['only' => ['create', 'store']]);
        $this->middleware('permission:حذف فرع', ['only' => ['delete']]);
    }

    public function index(){
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $branches = $company->branches;
        return view('client.branches.index',compact('company','company_id','branches'));
    }
    public function create()
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        return view('client.branches.create',compact('company_id','company'));
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'branch_name' => 'required',
            'branch_phone' => 'required|numeric',
            'branch_address' => 'required',
        ]);
        $data = $request->all();
        $branch = Branch::create($data);
        return response()->json(['message' => 'تم إضافة الفرع بنجاح', 'status' => true]);
    }

    public function edit($id)
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $branch = Branch::findOrFail($id);
        return view('client.branches.edit', compact('branch', 'company_id', 'company'));
    }
    public function update(Request $request)
    {
        $this->validate($request, [
            'branch_name' => 'required',
            'branch_phone' => 'required|numeric',
            'branch_address' => 'required',
        ]);
        $input = $request->all();
        $branch = Branch::findOrFail($request->id);
        $branch->update($input);
        return response()->json(['message' => 'تم تعديل الفرع بنجاح', 'status' => true]);
    }
    public function delete(Request $request)
    {
        $branch = Branch::findOrFail($request->id);
        $branch->delete();
        return response()->json(['message' => 'تم حذف الفرع بنجاح', 'status' => true]);
    }
}
