<?php

namespace App\Http\Controllers\Backend;

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

class HairController extends Controller
{
    public function hair()
    {
        $records   =  HairModel::orderBy('hair_color', 'ASC')->get();
        return view('backend.hair.list', compact('records'));
    }

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

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