<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Dependants;

class DependantController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'name'=>'required',
            'dateofBirth' =>'required',
            'relation'=>'required',
            
          ]);
          $dependant = new Dependants([
            'name' => $request->get('name'),
            'dateofBirth'=> $request->get('dateofBirth'),
            'relation'=> $request->get('relation'),

          ]);
          $dependant->save();
          return redirect('/employees/create')->with('success', 'Dependant has been added');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $where = array('id' => $id);
        $dependant  = Dependants::where($where)->first();
 
        return Response::json($dependant);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $request->validate([
            'name'=>'required',
            'dateofBirth'   => 'required',
            'relation'=>'required',
          ]);
    
          $dependant = Dependants::find($id);
          $dependant->name = $request->get('name');
          $dependant->dateofBirth = $request->get('dateofBirth');
          $dependant->relation = $request->get('relation');
          $dependant->save();
    
          return redirect('/employees/create')->with('success', 'Dependant has been updated');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $dependant = Dependants::where('id',$id)->delete();
   
        return Response::json($dependant);
    }
}
