<?php

namespace App\Http\Controllers\Api;

use App\Credential;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $credential = new Credential;
        $credential->credtype = $request->input('credtype');
        $credential->creddesc = $request->input('creddesc');
        $credential->creduser = $request->input('creduser');
        $credential->credpass = $request->input('credpass');
        if ($request->has('pcid')) {
            $credential->pcid = $request->input('pcid');
            $credential->groupid = 0;
        } else {
            $credential->groupid = $request->input('groupid');
            $credential->pcid = 0;
        }
        $credential->patterndata = ' ';
        $credential->credq = ' ';
        $credential->creda = ' ';
        $credential->save();
        event(new \App\Events\CredentialAdded($credential));
        return response()->json($credential, 200);
    }

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

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Credential  $credential
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Credential $credential)
    {
        $credential->credtype = $request->input('credtype');
        $credential->creddesc = $request->input('creddesc');
        $credential->creduser = $request->input('creduser');
        $credential->credpass = $request->input('credpass');
        $credential->save();
        event(new \App\Events\CredentialUpdated($credential));
        return response()->json($credential, 200);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Credential  $credential
     * @return \Illuminate\Http\Response
     */
    public function destroy(Credential $credential)
    {
        $deletedCred = $credential->toJson();
        $credential->delete();
        event(new \App\Events\CredentialDeleted($deletedCred));
        return response()->json("", 204);
    }
}
