<?php

namespace App\Modules\Hr\controllers\api\v1;

use Illuminate\Support\Facades\Response;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use App\Exceptions\PermissionDeniedException;
use App\Http\Controllers\BaseController;
use App\Modules\Hr\TimeLog;

class AdminTimeLogControllerREST extends BaseController
{
    public function index(Request $request)
    {
        // This function requires management access
        if (! Auth::user()->hasPermission('access_hr')) {
            throw new PermissionDeniedException();
        }

        // Retrieves all time logs grouped by month
        $query = TimeLog::with('pending_change_requests')->where('user_id', $request->input('user_id', Auth::user()->id))->period($request->input('startDate'), $request->input('endDate'))->orderBy('time', 'asc');

        // Paginate the results
        $query = $query->paginate($request->input('limit', 500));

        // Prepare the response
        $response = [
            '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(),
        ];

        // Return the response
        return $response;
    }

    public function store(Request $request)
    {
        // The user has requested to record a previous record
        // this also needs approval, so an approval request will
        // be created for it
        $record = new TimeLog($request->all());
        $record->new_record_request = 0;

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

        return $record;
    }

    public function update(Request $request, $id)
    {
        // This function requires management access
        if (! Auth::user()->hasPermission('access_hr')) {
            throw new PermissionDeniedException();
        }

        $log = TimeLog::findOrFail($id);
        $log->fill($request->all());

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

        return $log;
    }
}
