<?php

namespace App\Http\Resources;

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

use Log;

class AttendanceResource extends JsonResource
{
    


    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        

        $date = Carbon::parse($request->date);

        if($request->type == 'staff'){
            return [
                'id'            => $this->id,
                'attendance'    => $this->attendance()->whereDate('checkin', '<', date('Y-m-d'))->orderBy('checkin', 'DESC')->limit(7)->get(),
                'today'         => $this->attendance()
                                        ->whereYear('checkin', '=', $date->year)
                                        ->whereMonth('checkin', '=', $date->month)
                                        ->whereDay('checkin', '=', $date->day)
                                        ->first(),                
                'code'          => $this->code,                    
                'first_name'    => $this->first_name,            
                'last_name'     => $this->last_name,                        
                'campus'        => $this->when($this->campus, function(){
                                        return $this->campus->only(['id', 'title']);
                                }),                
                'avatar'        => new MediaResource($this->avatar),                 
            ];
        }else{
            return [
                'id'            => $this->id,
                'attendance'    => $this->attendance()->whereDate('checkin', '<', date('Y-m-d'))->orderBy('checkin', 'DESC')->limit(7)->get(),
                'today'         => $this->attendance()
                                        ->whereYear('checkin', '=', $date->year)
                                        ->whereMonth('checkin', '=', $date->month)
                                        ->whereDay('checkin', '=', $date->day)
                                        ->first(),
                'number'        => $this->number,
                'code'          => $this->code,                    
                'first_name'    => $this->first_name,            
                'last_name'     => $this->last_name,                        
                'campus'        => $this->campus->only(['id', 'title']),
                'class'         => $this->grade->only(['id', 'title']),
                'section'       => $this->section->only(['id', 'title']),
                'avatar'        => new MediaResource($this->avatar),                 
            ];
        }
    }
}
