<?php

namespace App\Http\Controllers;

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

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

    public function store(Request $request)
    {
        $lic = $this->validateRequest($request);
        $lic['start_date'] = Carbon::parse($lic['start_date']);
        if ($request['end_date'] != null) {
            $lic['end_date'] = Carbon::parse($lic['end_date']);
        }
        License::create(array_merge(
            $lic,
            [
                'firm_id' => $request->user()->firm->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' => 'nullable|bool'
        ]);
    }

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

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

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


    public function update(Request $request)
    {
        $license = License::find($request->id);

        $lic = $this->validateRequest($request);
        $lic['start_date'] = Carbon::parse($lic['start_date']);
        if ($request['end_date'] != null && array_key_exists('end_date', $lic)) {
            $lic['end_date'] = Carbon::parse($lic['end_date']);
        }
        $license->update($lic);
        return back(303)->with(['success' => 'success']);

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param License $license
     * @return Response
     */
    public function destroy(Request $request)
    {
        $license = License::find($request->id);
        $license->delete();
        return back(303)->with(['success' => 'success']);
    }
}
