<?php

namespace App\Resources;

use Wibiesana\Padi\Core\Resource;

class ExamSupervisorResource extends Resource
{
    public function toArray($request): array
    {
        return [
            'id' => $this->id,
            'exam_id' => $this->exam_id,
            'teacher_id' => $this->teacher_id,
            'classroom_id' => $this->classroom_id,
            'description' => $this->description,

            // Relations
            'teacher' => $this->formatRelation($this->whenLoaded('teacher')),
            'classroom' => $this->formatRelation($this->whenLoaded('classroom')),
            'exam' => $this->formatRelation($this->whenLoaded('exam')),

            // Flattened Fields
            'teacher_name' => is_object($this->teacher) ? ($this->teacher->name ?? null) : ($this->teacher['name'] ?? null),
            'classroom_name' => is_object($this->classroom) ? ($this->classroom->name ?? null) : ($this->classroom['name'] ?? null),
            'exam_name' => is_object($this->exam) ? ($this->exam->name ?? null) : ($this->exam['name'] ?? null),

        ];
    }

    private function formatRelation($item)
    {
        if (is_null($item)) return null;

        if (is_array($item) && !isset($item['id']) && !isset($item['name']) && !isset($item['username'])) {
            $res = [];
            foreach ($item as $i) {
                if ($i) {
                    $id = is_object($i) ? ($i->id ?? null) : ($i['id'] ?? null);
                    $name = is_object($i) ? ($i->name ?? $i->username ?? null) : ($i['name'] ?? $i['username'] ?? null);
                    $res[] = ['id' => $id, 'name' => $name];
                }
            }
            return $res;
        }

        $id = is_object($item) ? ($item->id ?? null) : ($item['id'] ?? null);
        $name = is_object($item) ? ($item->name ?? $item->username ?? null) : ($item['name'] ?? $item['username'] ?? null);
        return ['id' => $id, 'name' => $name];
    }
}
