<?php

namespace Modules\User\Resources\Api;

use Illuminate\Http\Resources\Json\JsonResource;
use Modules\Canteen\Resources\Api\CanteenResource;
use Modules\School\Resources\Api\SchoolResource;
use Modules\PaymentLog\Services\PaymentLogService;

class UserResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        $return = [
            'id' => (int) $this->id,
            'photo' => $this->photo ? asset($this->photo) : null,
            'points' => (int) $this->points,
            'name' => $this->name,
            'last_name' => $this->last_name,
            'phone' => $this->phone,
            'pure_phone' => str_replace('966', '', $this->phone),
            'email' => $this->email,
            'id_number' => $this->id_number,
            'role' => (int) $this->role,
            'unread_notification' => (int) $this->unread_notification,
        ];

        if ($this->role === 6) {
            $return['canteen'] = $this->canteen ? new CanteenResource($this->canteen) : null;
            $return['school'] = $this->school ? new SchoolResource($this->school) : null;

            $return['orders'] = $this->totalOrders($this->canteen_id);
            $paymentLogService = resolve(PaymentLogService::class);
            $return['total'] = $this->canteen ? $paymentLogService->getTotal($this->canteen_id) : 0;
        }

        return $return;
    }
}
