<?php

namespace App\Resources;

use Wibiesana\Padi\Core\Resource;

class ExamResource extends Resource
{
    public function toArray($request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'exam_event_id' => $this->exam_event_id,
            'question_bank_id' => $this->question_bank_id,
            'subject_id' => $this->subject_id,
            'semester_id' => $this->semester_id,
            'status' => $this->status,
            'token' => $this->token,
            'has_token' => !empty($this->token),
            'test_duration' => $this->test_duration,
            'use_dynamic_token' => $this->use_dynamic_token,
            'show_pg' => $this->show_pg,
            'show_essay' => $this->show_essay,
            'show_result' => $this->show_result,
            'percentage_mc_value' => $this->percentage_mc_value,
            'percentage_essay_value' => $this->percentage_essay_value,
            'start_date' => $this->start_date,
            'end_date' => $this->end_date,
            'is_random' => $this->is_random,
            'randomize_questions' => $this->randomize_questions,
            'randomize_options' => $this->randomize_options,
            'lock_on_switch' => $this->lock_on_switch,
            'require_supervisor' => $this->require_supervisor,

            // Relations
            'createdBy' => $this->formatRelation($this->whenLoaded('createdBy')),
            'questionBank' => $this->formatRelation($this->whenLoaded('questionBank')),
            'subject' => $this->formatRelation($this->whenLoaded('subject')),
            'updatedBy' => $this->formatRelation($this->whenLoaded('updatedBy')),
            'classes' => $this->formatRelation($this->whenLoaded('classes')),
            'supervisors' => $this->formatRelation($this->whenLoaded('supervisors')),
            'examiners' => $this->formatRelation($this->whenLoaded('examiners')),
            'supervisorAssignments' => ExamSupervisorResource::collection($this->whenLoaded('supervisorAssignments')),
            'participants' => $this->getParticipants(),

            // Flattened Fields
            'createdBy_name' => $this->resource['createdBy_name'] ?? $this->createdBy['username'] ?? null,
            'questionBank_name' => $this->resource['questionBank_name'] ?? $this->questionBank['name'] ?? null,
            'subject_name' => $this->resource['subject_name'] ?? $this->subject['name'] ?? null,
            'updatedBy_name' => $this->resource['updatedBy_name'] ?? $this->updatedBy['username'] ?? null,
            'working_student_count' => (int)($this->working_student_count ?? $this->getWorkingCount()),
            'exam_results' => $this->whenLoaded('examresults'),
        ];
    }

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

    private function getWorkingCount(): int
    {
        // Try direct attribute access if set in controller via setAttribute or array access
        $count = $this->resource->working_student_count ?? $this->resource['working_student_count'] ?? null;
        if (!is_null($count)) return (int)$count;

        $results = $this->whenLoaded('examresults');
        if (is_null($results) || !is_iterable($results)) return 0;

        $count = 0;
        foreach ($results as $res) {
            $status = $res->status ?? $res['status'] ?? 1;
            if ((int)$status >= 2) $count++;
        }
        return $count;
    }

    private function getParticipants()
    {
        $results = $this->whenLoaded('examresults');
        if (is_null($results) || !is_iterable($results)) return [];

        $participants = [];
        foreach ($results as $res) {
            $student = $res->student ?? $res['student'] ?? null;
            if ($student) {
                $participants[] = [
                    'id' => $student->id ?? $student['id'] ?? null,
                    'name' => $student->name ?? $student['name'] ?? null,
                    'nisn' => $student->nisn ?? $student['nisn'] ?? null,
                ];
            }
        }
        return $participants;
    }
}
