<?php

namespace App\Http\Controllers\Backend;

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

class LanguageController extends Controller
{
    public function language()
    {
        $records   =  LanguageModel::orderBy('name', 'ASC')->get();
        return view('backend.language.list', compact('records'));
    }

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

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