<?php

namespace App\Http\Resources;

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

class OrderShowResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        if ($this->client_type == 'physical') {
            $client_information = [
                'full_name' => $this->full_name,
                'phone' => $this->phone,
            ];
        } else {
            $client_information = null;
        }

        if (in_array($this->payment_status, ['waiting', 'processing'])) {
            if ($this->payment_type == 'click') {
                $merchant_id = env("CLICK_MERCHANT_ID");
                $service_id = env("CLICK_SERVICE_ID");
                $pay_url = "https://my.click.uz/services/pay?service_id={$service_id}&merchant_id={$merchant_id}&amount={$this->billing->amount}&transaction_param={$this->billing->id}";

            } else {
                $amount = $this->billing->amount * 100;
                $payme_url = "https://checkout.paycom.uz/". base64_encode("m=66faa5c44f9ee150b7ff81cf;ac.key={$this->billing->id};a={$amount}");
                $pay_url = $payme_url;//'https://checkout.payme.uz';
            }
        } else {
            $pay_url = null;
        }

        return [
            'id' => $this->id,
            'pay_url' => $pay_url,
            'status' => new StatusResource($this->getStatus),
            'payment_type' => $this->payment_type,
            'payment_status' => new StatusResource($this->getPaymentStatus),
            'created_at' => $this->created_at->format('Y-m-d H:i:s'),
            'delivery_type' => $this->delivery_type,
            'client_type' => $this->client_type,
            'total_amount' => $this->price_total,
            'products' => OrderProductResource::collection($this->products),
            'address' => new AddressResource($this->address),
            'legal_information' => $this->client_type == 'legal' ? $this->legalInfo : null,
            'client_information' => $client_information,
            'branch' => new BranchResource($this->branch),
            'with_installation' => $this->with_installation,
            'with_didox' => $this->with_didox,
            'price_products' => $this->price_products,
            'price_delivery' => $this->price_delivery,
            'price_master' => $this->price_master,
            "contract" => $this->contracts()->latest()->first()?->getPath()
        ];
    }
}
