<?php

namespace App\Http\Resources\Manufacturing;

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

class RouteCardResource extends BaseResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'route_card_no' => $this->route_card_no,
            'sales_order' => new SalesOrderResource($this->whenLoaded('salesOrder')),
            'sales_order_id' => $this->sales_order_id,
            'start_date' => $this->formatDate($this->start_date),
            'end_date' => $this->formatDate($this->end_date),
            'part_no' => $this->part_no,
            'drawing_no' => $this->drawing_no,
            'drawing_rev' => $this->drawing_rev,
            'quantity' => (float) $this->quantity,
            'description' => $this->description,
            'priority' => $this->priority,
            'priority_badge' => $this->getPriorityBadge(),
            'status' => $this->status,
            'status_badge' => $this->getStatusBadge($this->status ?? 'pending'),
            'remarks' => $this->remarks,
            'processes' => RouteCardProcessResource::collection($this->whenLoaded('processes')),
            'process_count' => $this->whenLoaded('processes', fn() => $this->processes->count()),
            'completed_processes' => $this->whenLoaded('processes', fn() => $this->processes->where('status', 'completed')->count()),
            'progress_percentage' => $this->calculateProgress(),
            'created_at' => $this->formatDateTime($this->created_at),
            'updated_at' => $this->formatDateTime($this->updated_at),
        ];
    }

    protected function getPriorityBadge(): array
    {
        $badges = [
            'low' => ['class' => 'secondary', 'label' => 'Low'],
            'normal' => ['class' => 'info', 'label' => 'Normal'],
            'high' => ['class' => 'warning', 'label' => 'High'],
            'urgent' => ['class' => 'danger', 'label' => 'Urgent'],
        ];

        return $badges[$this->priority ?? 'normal'] ?? $badges['normal'];
    }

    protected function calculateProgress(): int
    {
        if (!$this->relationLoaded('processes') || $this->processes->isEmpty()) {
            return 0;
        }

        $total = $this->processes->count();
        $completed = $this->processes->where('status', 'completed')->count();

        return $total > 0 ? (int) round(($completed / $total) * 100) : 0;
    }
}
