<?php

namespace App\Http\Controllers\Backend;

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

class BrandController extends Controller
{
     public function brand()
    {
        $records   =  ProductBrandModel::orderBy('id', 'ASC')->get();
        return view('backend.brand.list', compact('records'));
    }

    public function addBrand($id = '')
    {
        $record = '';
        if ($id > 0) {
            $record = ProductBrandModel::WHere('id', $id)->first();
        }
        return view('backend.brand.add_edit', compact('record'));
    }

    public function storeUpdateBrand(Request $request)
    {
        $input     = $request->all();
        $id        = isset($input['id']) ? $input['id'] : 0;

        $dataArr = [];
        foreach ($input as $key => $val) {
            if ($key != '_token' && $key != 'id' )
                $dataArr[$key] = $val;
        }

       
        if ($id == 0 || $id == '') {
            $request->validate([
                'brand'          =>  "required|unique:brand,brand",              
            ]);
           $insert = ProductBrandModel::create($dataArr);
           if($insert['id'] > 0)
           {
               return redirect()->route('brand')->with('success', 'Brand Saved Successfully');
           }else{
               return redirect()->route('brand')->with('error', 'Something went wrong!');
           }
           
        } else {
            $request->validate([
                'brand'          =>  "required",               
            ]);
            $update = ProductBrandModel::Where('id',$id)->update($dataArr);
            return redirect()->route('brand')->with('success', 'Brand Updated Successfully');;
        }        
    }
}
