<?php

namespace App\Resources;

use Wibiesana\Padi\Core\Resource;

class QuestionBankResource extends Resource
{
    public function toArray($request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'description' => $this->description,
            'status' => $this->status,
            'teacher_id' => $this->teacher_id,
            'question_count' => $this->question_count,
            'answer_score_list' => $this->answer_score_list,

            // Relations
            'createdBy' => $this->formatRelation($this->whenLoaded('createdBy')),
            'updatedBy' => $this->formatRelation($this->whenLoaded('updatedBy')),
            'teacher' => $this->formatRelation($this->whenLoaded('teacher')),

            // Flattened Fields for Display
            'teacher_name' => is_object($this->teacher) ? $this->teacher->name : ($this->teacher['name'] ?? $this->teacher_name ?? null),
            'createdBy_name' => is_object($this->createdBy) ? ($this->createdBy->username ?? $this->createdBy->name ?? null) : ($this->createdBy['username'] ?? $this->createdBy_name ?? null),
            'updatedBy_name' => is_object($this->updatedBy) ? ($this->updatedBy->username ?? $this->updatedBy->name ?? null) : ($this->updatedBy['username'] ?? $this->updatedBy_name ?? null),
            'author' => is_object($this->teacher) ? $this->teacher->name : ($this->teacher['name'] ?? $this->teacher_name ?? null),
            'creator' => is_object($this->createdBy) ? ($this->createdBy->username ?? $this->createdBy->name ?? null) : ($this->createdBy['username'] ?? $this->createdBy_name ?? null),
            'editor' => is_object($this->updatedBy) ? ($this->updatedBy->username ?? $this->updatedBy->name ?? null) : ($this->updatedBy['username'] ?? $this->updatedBy_name ?? null),
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,

        ];
    }

    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];
    }
}
