<?php

namespace App\Http\Controllers\Backend;

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

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

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

    public function storeUpdateType(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([
                'type'          =>  "required|unique:type,type",
              
            ]);
           $insert = ProductTypeModel::create($dataArr);
           if($insert['id'] > 0)
           {
               return redirect()->route('type')->with('success', 'Type Saved Successfully');
           }else{
               return redirect()->route('type')->with('error', 'Something went wrong!');
           }
           
        } else {
            $request->validate([
                'type'          =>  "required",               
            ]);
            $update = ProductTypeModel::Where('id',$id)->update($dataArr);
            return redirect()->route('type')->with('success', 'Type Updated Successfully');;
        }        
    }
}
