<?php

namespace App\Http\Controllers;

use App\Models\Certificate;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

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

    public function store(Request $request)
    {
        $certificate = $this->validateRequest($request);
        $certificate['start_date'] = Carbon::parse($certificate['start_date']);
        if ($request['end_date'] != null) {
            $certificate['end_date'] = Carbon::parse($certificate['end_date']);
        }
        Certificate::create(array_merge(
            $certificate,
            [
                'engineer_id' => $request->user()->engineer->id,
            ]
        ));
        return back(303)->with(['success' => 'success']);
    }

    protected function validateRequest(Request $request)
    {
        return $request->validate([
            'name' => 'required',
            'issuing_org' => 'required',
            'start_date' => 'required|date',
            'end_date' => 'exclude_if:does_not_expire,true|nullable|date',
            'credential_id' => 'nullable',
            'credential_url' => 'nullable|url',
            'does_not_expire' => 'required|bool'
        ]);
    }

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

    /**
     * Display the specified resource.
     *
     * @param Certificate $certificate
     * @return Response
     */
    public function show(Certificate $certificate)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param Certificate $certificate
     * @return Response
     */
    public function edit(Certificate $certificate)
    {
        //
    }

    public function update(Request $request)
    {
        $certificate = Certificate::find($request->id);
        $cert = $this->validateRequest($request);
        $cert['start_date'] = Carbon::parse($cert['start_date']);
        if ($request['end_date'] != null && array_key_exists('end_date', $cert)) {
            $cert['end_date'] = Carbon::parse($cert['end_date']);
        }
        $certificate->update($cert);
        return back(303)->with(['success' => 'success']);
    }

    public function destroy(Request $request)
    {
        $certificate = Certificate::find($request->id);
        $certificate->delete();

        return back(303)->with(['success' => 'success']);
    }
}
