<?php

namespace App\Http\Controllers;

use App\Models\Experience;
use Carbon\Carbon;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;

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

    public function store(Request $request)
    {
        try {
            $transaction = DB::transaction(function () use ($request) {
                $experience = $this->validateRequest($request);
                $experience['start_date'] = Carbon::parse($experience['start_date']);

                if (!$experience['currently_working_here']) {

                    $experience['end_date'] = Carbon::parse($experience['end_date']);

                }
                Experience::create(array_merge(
                    $experience,
                    [
                        'engineer_id' => $request->user()->engineer->id,
                    ]
                ));
            });
            return is_null($transaction) ? back(303)->with(['success' => 'success']) : $transaction;
        } catch (Exception $exception) {
            return back(303)->with(['error' => $exception->getMessage()]);
        }
    }

    protected function validateRequest(Request $request)
    {
        return $request->validate([
            'title' => 'required',
            'company_name' => 'required',
            'start_date' => 'required|date',
            'end_date' => 'exclude_if:does_not_expire,true|nullable|date',
            'location' => 'required',
            'currently_working_here' => 'required|bool'
        ]);
    }

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

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

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

    public function update(Request $request)
    {
        $experience = Experience::find($request->id);
        $exp = $this->validateRequest($request);
        $exp['start_date'] = Carbon::parse($exp['start_date']);

        $exp['end_date'] = !$exp['currently_working_here'] ? Carbon::parse($exp['end_date']) : null;
        $experience->update($exp);

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

    public function destroy(Request $request)
    {
        $experience = Experience::find($request->id);
        $experience->delete();
        return back(303)->with(['success' => 'success']);
    }
}
