<?php

namespace App\Http\Resources\MasterData;

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

class CustomerVendorResource extends BaseResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'company' => $this->company,
            'company_role' => $this->company_role,
            'company_type' => $this->company_type,
            'account_type' => $this->account_type,
            'address' => $this->address,
            'city' => $this->city,
            'state' => $this->state,
            'pincode' => $this->pincode,
            'country' => $this->country,
            'full_address' => $this->getFullAddress(),
            'gst' => $this->gst,
            'pan' => $this->pan,
            'phone' => $this->phone,
            'email' => $this->email,
            'website' => $this->website,
            'credit_limit' => $this->formatCurrency($this->credit_limit),
            'payment_terms' => $this->payment_terms,
            'bank_name' => $this->bank_name,
            'bank_account_no' => $this->bank_account_no,
            'ifsc_code' => $this->ifsc_code,
            'status' => $this->status,
            'status_badge' => $this->getStatusBadge($this->status ?? 'active'),
            'is_customer' => $this->company_role === 'Customer' || $this->company_role === 'Both',
            'is_vendor' => $this->company_role === 'Vendor' || $this->company_role === 'Both',
            'contacts' => ContactPersonResource::collection($this->whenLoaded('contacts')),
            'primary_contact' => new ContactPersonResource($this->whenLoaded('primaryContact')),
            'created_at' => $this->formatDateTime($this->created_at),
            'updated_at' => $this->formatDateTime($this->updated_at),
        ];
    }

    protected function getFullAddress(): ?string
    {
        $parts = array_filter([
            $this->address,
            $this->city,
            $this->state,
            $this->pincode,
            $this->country,
        ]);

        return !empty($parts) ? implode(', ', $parts) : null;
    }
}
