<?php
// app/Http/Resources/Api/Customer/ReviewResource.php
namespace App\Http\Resources\Api\Customer;

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

class ReviewResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'rating' => $this->rating,
            'stars' => str_repeat('⭐', $this->rating),
            'comment' => $this->comment,
            'is_approved' => $this->is_approved,
            'can_edit' => $this->canBeEdited(),
            'time_remaining' => $this->getTimeRemaining(),
            'menu' => $this->whenLoaded('menu', function () {
                return [
                    'id' => $this->menu->id,
                    'name' => $this->menu->name,
                    'image_url' => $this->menu->image_url,
                    'category' => $this->menu->category->name ?? null,
                ];
            }),
            'order' => $this->whenLoaded('order', function () {
                return [
                    'id' => $this->order->id,
                    'order_number' => $this->order->order_number,
                    'order_date' => $this->order->created_at->format('Y-m-d H:i:s'),
                ];
            }),
            'customer' => $this->whenLoaded('customer', function () {
                return [
                    'id' => $this->customer->id,
                    'name' => $this->customer->name,
                    'initials' => $this->getInitials($this->customer->name),
                ];
            }),
            'created_at' => $this->created_at->format('Y-m-d H:i:s'),
            'updated_at' => $this->updated_at->format('Y-m-d H:i:s'),
            'time_ago' => $this->created_at->diffForHumans(),
        ];
    }

    private function canBeEdited(): bool
    {
        return $this->created_at->addHours(24)->isFuture();
    }

    private function getTimeRemaining(): ?string
    {
        if (!$this->canBeEdited()) {
            return null;
        }
        
        $hours = $this->created_at->addHours(24)->diffInHours(now());
        return $hours . ' jam tersisa untuk edit';
    }

    private function getInitials(string $name): string
    {
        $words = explode(' ', $name);
        $initials = '';
        
        foreach ($words as $word) {
            if (!empty($word)) {
                $initials .= strtoupper($word[0]);
                if (strlen($initials) >= 2) break;
            }
        }
        
        return $initials ?: 'AN';
    }
}