<?php
namespace App\Http\Resources\Api\Customer;

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

class PromoResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        $isValid = $this->is_active && 
                   $this->start_date <= now() && 
                   $this->end_date >= now();

        return [
            'id' => $this->id,
            'name' => $this->name,
            'description' => $this->description,
            'type' => $this->type,
            'discount_value' => (float) $this->discount_value,
            'formatted_discount' => $this->getFormattedDiscount(),
            'min_purchase' => $this->min_purchase ? (float) $this->min_purchase : null,
            'max_discount' => $this->max_discount ? (float) $this->max_discount : null,
            'code' => $this->code,
            'start_date' => $this->start_date->format('Y-m-d H:i:s'),
            'end_date' => $this->end_date->format('Y-m-d H:i:s'),
            'is_active' => $this->is_active,
            'is_valid' => $isValid,
            'days_left' => now()->diffInDays($this->end_date, false),
            'validation_message' => $isValid ? 'Promo berlaku' : 'Promo tidak berlaku',
            'terms_and_conditions' => $this->getTermsAndConditions(),
            'created_at' => $this->created_at->format('Y-m-d H:i:s'),
            'updated_at' => $this->updated_at->format('Y-m-d H:i:s'),
        ];
    }

    private function getFormattedDiscount(): string
    {
        return match ($this->type) {
            'percentage' => $this->discount_value . '%',
            'fixed' => 'Rp ' . number_format($this->discount_value, 0, ',', '.'),
            'bogo' => 'Buy 1 Get 1',
            default => $this->discount_value,
        };
    }

    private function getTermsAndConditions(): string
    {
        $terms = [];
        
        if ($this->min_purchase) {
            $terms[] = "Minimal pembelian Rp " . number_format($this->min_purchase, 0, ',', '.');
        }
        
        if ($this->max_discount && $this->type === 'percentage') {
            $terms[] = "Maksimal diskon Rp " . number_format($this->max_discount, 0, ',', '.');
        }
        
        if ($this->type === 'bogo') {
            $terms[] = "Hanya berlaku untuk produk yang sama";
        }
        
        if ($this->start_date && $this->end_date) {
            $terms[] = "Berlaku hingga " . $this->end_date->format('d M Y');
        }
        
        return implode('. ', $terms);
    }
}