<?php

namespace App\Http\Resources;

use Carbon\Carbon;
use Illuminate\Http\Resources\Json\JsonResource;

class CMS_API_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 [
            'id' => $this->id,
            'name' => $this->name ?? null,
            'surname' => $this->surname ?? null,
            'email' => $this->email ?? null,
            'phone' => $this->phone ?? null,
            'highschool' => $this->highschool ?? null,
            'highschool_year' => $this->highschool_year ?? null,
            'birth_date' => $this->birth_date ?? null,
            'program' => $this->attempt->academy->name ?? null,
            'time' => $this->getTime(),
            'timeSeconds' => $this->getTime('%d'),
            'correctAnswers' => $this->correctAnswers,
            'memory_matrix_score' => $this->attempt->memory_matrix_result,
            'memory_matrix_level' => $this->attempt->memory_matrix_level,
            'memory_matrix_sublevel' => $this->attempt->memory_matrix_sublevel,
            'speed_arithmetic_score' => $this->attempt->speed_arithmetic_result,
            'created_at' => $this->created_at->format('Y-m-d'),
            'term' => $this->term_id,
            'query_string' => $this->query_string ?? null,
            'final_score' => $this->final_score
        ];
    }

    private function getTime($seconds = false)
    {
        if (!$this->attempt) {
            return 'Not started';
        };

        if ($this->attempt->end_time == null) {
            return 'Expired';
        }

        if ($seconds) {
            return \Carbon\Carbon::parse($this->attempt->end_time)->diffInSeconds($this->attempt->start_time);
        }

        return \Carbon\Carbon::parse($this->attempt->end_time)->diff($this->attempt->start_time)->format('%i min %s seconds');
    }
}
