<?php

namespace App\Http\Controllers;

use App\Models\ClientDesignation;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class DesignationController extends Controller
{
    public function index(){
        $result= ClientDesignation::with('createdBy','updatedBy')->where('client_id',Auth::user()->client_id)->get();
        return view('backend.basicSetup.designation.index',compact('result'));
    }
    public function create(){
        return view('backend.basicSetup.designation.create');
    }
    public function store(Request $request){
        $exists= ClientDesignation::where('client_id',Auth::user()->client_id)->where('title',$request->title)->count();
        if($exists>0){
            return redirect()->back()->with('error','Duplicate record found!');
        }else{
            $obj = new ClientDesignation();
            $obj->client_id= Auth::user()->client_id;
            $obj->title= $request->title;
            $obj->created_by= Auth::id();
            $obj->updated_by= Auth::id();
            $obj->save();
            return redirect()->back()->with('success','Designation created Successfully!');
        }
    }
    public function edit( $id){
        $result = ClientDesignation::find($id);
        return view('backend.basicSetup.designation.edit',compact('result'));
    }
    public function update( Request $request, $id){
        $exists= ClientDesignation::where('client_id',Auth::user()->client_id)->where('title',$request->title)->where('id','!=',$id)->count();
        if($exists>0){
            return redirect()->back()->with('error','Duplicate record found!');
        }else{
            $result= ClientDesignation::where('client_id',Auth::user()->client_id)->where('id',$id)->first();
        }
        if($result){
            $result->title= $request->title;
            $result->created_by= Auth::id();
            $result->updated_by= Auth::id();
            $result->save();
            return redirect()->back()->with('success','Your Information updated Successfully!');
        }
    }
    public function destroy( $id){
        $exists= ClientDesignation::where('client_id',Auth::user()->client_id)->where('id',$id)->first();
        if($exists){
            $exists->delete();
            return redirect()->back()->with('success','Designation deleted successfully!');
        }
        return redirect()->back()->with('success','Sorry you are in wrong way!');
    }
}
