<?php

declare(strict_types=1);

namespace App\Http\Resources;

use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class ProjectHubResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        $total = (int) ($this->quantity ?? 0);
        $removed = $this->removed_products_count ?? 0;
        $remaining = max($total - $removed, 0);

        $start = $this->start_date ? Carbon::parse($this->start_date) : null;
        $end = $this->end_date ? Carbon::parse($this->end_date) : null;
        $totalDays = $start && $end ? max($start->diffInDays($end), 1) : 0;
        $elapsedDays = $start ? min($start->diffInDays(now()), $totalDays) : 0;
        $progressPercent = $totalDays > 0 ? (int) round(($elapsedDays / $totalDays) * 100) : 0;

        $invested = (int) ($this->budget ?? 0);

        return [
            'product' => [
                'total' => $total,
                'removed' => $removed,
                'remaining' => $remaining,
            ],
            'progress' => [
                'percent' => $progressPercent,
                'total_days' => $totalDays,
                'elapsed_days' => $elapsedDays,
            ],
            'growth' => [
                'current' => $this->latest_growth_value ?? '—',
                'target' => $this->growth_target_value ?? '—',
                'percent' => $this->growth_percent ?? 0,
            ],
            'capital' => [
                'invested' => number_format($invested) . ' تومان',
                'invested_amount' => $invested,
            ],
        ];
    }
}
