<?php

namespace App\Modules\Bookings;

use Illuminate\Support\Facades\Response;
use Exception;
use App\Http\Controllers\BaseController;
use Illuminate\Http\Request;

class TimeTrackingControllerRESTv1 extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function getIndex(Request $request)
    {
        $query = TimeTracking::with('user');

        if ($request->input('task_id')) {
            $query->where('task_id', $request->input('task_id'));
        }

        if ($request->input('task') && $request->input('task') != 'false') {
            $query->with('task');
        }

        // Determine if we should paginate or return a straight answer
        // with all the results
        // In this case, if we have a task id then we will return all the results
        if ($request->input('task_id')) {
            return [
                'success' => true,
                'data'    => $query->get(),
            ];
        }

        $query = $query->paginate($request->input('limit', 20));

        return [
            'success'      => true,
            'data'         => $query->getCollection()->toArray(),
            'total'        => $query->total(),
            'current_page' => $query->currentPage(),
            'last_page'    => $query->lastPage(),
            'per_page'     => $query->perPage(),
            'from'         => $query->firstItem(),
            'to'           => $query->lastItem(),
        ];
    }

    /**
     * Start the timer for a particular task & user.
     *
     * @return \App\Modules\Bookings\TimeTracking
     */
    public function postStart(Request $request)
    {
        // Check to see if we already have a running session for the current task
        if (TimeTracking::where('user_id', getAuthUserId())->where('task_id', $request->input('task_id'))->whereNull('ended_at')->count()) {
            throw new Exception('You are already tracking time for this task');
        }

        $log = TimeTracking::create([
            'user_id'    => getAuthUserId(),
            'task_id'    => $request->input('task_id'),
            'started_at' => date('Y-m-d H:i:s'),
        ]);

        return $log->load('user');
    }

    /**
     * Stops the timer for a particular task & user.
     *
     * @return \App\Modules\Bookings\TimeTracking
     */
    public function postStop(Request $request)
    {
        // Check to see if we already have a running session for the current task
        $log = TimeTracking::where('user_id', getAuthUserId())->where('task_id', $request->input('task_id'))->whereNull('ended_at')->first();

        if (! $log) {
            throw new Exception('There is no timer running for this task');
        }

        $log->ended_at = date('Y-m-d H:i:s');

        if (! $log->save()) {
            return Response::json(['errors' => $log->errors->all()], 400);
        }

        return $log->load('user');
    }
}
