<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class UserResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        return [
            'name' => $this->name ?? null,
            'surname' => $this->surname ?? null,
            'email' => $this->email ?? null,
            'birth_date' => $this->birth_date ?? null,
            'token' => $this->token ?? null,
            'birth_date_parts' => ($this->birth_date ?? null) ? [
                'year' => \Carbon\Carbon::createFromFormat("Y-m-d", $this->birth_date)->format('Y'),
                'month' => \Carbon\Carbon::createFromFormat("Y-m-d", $this->birth_date)->format('m'),
                'day' => \Carbon\Carbon::createFromFormat("Y-m-d", $this->birth_date)->format('d'),
            ] : [],
            'academy_id' => $this->attempt->academy_id ?? null,
            'memory_matrix_duration' => $this->attempt->academy->memory_matrix_duration,
            'speed_arithmetic_duration' => $this->attempt->academy->speed_arithmetic_duration,
            'duration' => $this->getDuration(),
            'query_string' => $this->query_string ?? null,
            'memory_matrix_result' => $this->attempt->memory_matrix_result,
            'memory_matrix_level' => $this->attempt->memory_matrix_level,
            'memory_matrix_sublevel' => $this->attempt->memory_matrix_sublevel,
            'speed_arithmetic_result' => $this->attempt->speed_arithmetic_result
        ];
    }

    private function getDuration()
    {
        if (!$this->attempt) {
            return null;
        };

        if (!$this->attempt->start_time) {
            $this->attempt->academy->duration;
        }

        return $this->attempt->academy->duration - (\Carbon\Carbon::now('Europe/Skopje')->diffInSeconds($this->attempt->start_time));
    }
}
