<?php

namespace App\Http\Resources\Manufacturing;

use App\Http\Resources\BaseResource;
use Illuminate\Http\Request;

class RouteCardProcessResource extends BaseResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'route_card_id' => $this->route_card_id,
            'process' => $this->process,
            'process_details' => $this->whenLoaded('attchedProcess'),
            'machine_id' => $this->machine,
            'machine' => $this->whenLoaded('attchedMachine'),
            'operator_id' => $this->operator,
            'operator' => $this->whenLoaded('attchedOperator'),
            'cycle_hours' => $this->cycle_hours,
            'cycle_minutes' => $this->cycle_minutes,
            'cycle_time_formatted' => $this->getFormattedCycleTime(),
            'cycle_time_minutes' => $this->getCycleTimeInMinutes(),
            'source' => $this->source,
            'description' => $this->description,
            'start_date' => $this->formatDateTime($this->start_date),
            'end_date' => $this->formatDateTime($this->end_date),
            'previous_process_id' => $this->previous_process_id,
            'status' => $this->status,
            'status_badge' => $this->getStatusBadge($this->status ?? 'pending'),
            'is_qc_stage' => in_array($this->status, ['qc_before', 'qc_during', 'qc_after']),
            'qc_approvals' => $this->whenLoaded('qcApprovals'),
            'can_start' => $this->canStart(),
            'is_overdue' => $this->isOverdue(),
            'created_at' => $this->formatDateTime($this->created_at),
            'updated_at' => $this->formatDateTime($this->updated_at),
        ];
    }

    protected function getFormattedCycleTime(): string
    {
        $hours = $this->cycle_hours ?? 0;
        $minutes = $this->cycle_minutes ?? 0;

        if ($hours > 0) {
            return "{$hours}h {$minutes}m";
        }
        return "{$minutes}m";
    }

    protected function getCycleTimeInMinutes(): int
    {
        return (($this->cycle_hours ?? 0) * 60) + ($this->cycle_minutes ?? 0);
    }

    protected function canStart(): bool
    {
        if ($this->previous_process_id && $this->relationLoaded('previousProcess')) {
            $previous = $this->previousProcess;
            if ($previous && $previous->status !== 'completed') {
                return false;
            }
        }
        return $this->status === 'pending';
    }

    protected function isOverdue(): bool
    {
        return $this->end_date
            && $this->end_date < now()
            && $this->status !== 'completed';
    }
}
