<?php

namespace App\Http\Resources;

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

/**
 * Base Resource
 *
 * Provides common functionality for all API resources including
 * standardized response format and helper methods.
 */
class BaseResource extends JsonResource
{
    /**
     * Additional data to include in response
     */
    protected array $additionalData = [];

    /**
     * Transform the resource into an array.
     * Override this method in child classes.
     */
    public function toArray(Request $request): array
    {
        return parent::toArray($request);
    }

    /**
     * Add additional data to the response
     */
    public function withAdditionalData(array $data): self
    {
        $this->additionalData = array_merge($this->additionalData, $data);
        return $this;
    }

    /**
     * Get additional data
     */
    public function with(Request $request): array
    {
        return array_merge([
            'success' => true,
        ], $this->additionalData);
    }

    /**
     * Format date for response
     */
    protected function formatDate($date, string $format = 'Y-m-d'): ?string
    {
        if (!$date) {
            return null;
        }

        return $date instanceof \Carbon\Carbon
            ? $date->format($format)
            : date($format, strtotime($date));
    }

    /**
     * Format datetime for response
     */
    protected function formatDateTime($date): ?string
    {
        return $this->formatDate($date, 'Y-m-d H:i:s');
    }

    /**
     * Format currency for response
     */
    protected function formatCurrency($amount, int $decimals = 2): string
    {
        return number_format((float) ($amount ?? 0), $decimals);
    }

    /**
     * Get status badge class
     */
    protected function getStatusBadge(string $status): array
    {
        $badges = [
            'pending' => ['class' => 'warning', 'label' => 'Pending'],
            'approved' => ['class' => 'success', 'label' => 'Approved'],
            'rejected' => ['class' => 'danger', 'label' => 'Rejected'],
            'completed' => ['class' => 'success', 'label' => 'Completed'],
            'in_progress' => ['class' => 'info', 'label' => 'In Progress'],
            'cancelled' => ['class' => 'secondary', 'label' => 'Cancelled'],
            'draft' => ['class' => 'secondary', 'label' => 'Draft'],
            'active' => ['class' => 'success', 'label' => 'Active'],
            'inactive' => ['class' => 'secondary', 'label' => 'Inactive'],
        ];

        return $badges[$status] ?? ['class' => 'secondary', 'label' => ucfirst($status)];
    }
}
