<?php
namespace Modules\Groovesell\Transformers;
use Illuminate\Http\Resources\Json\Resource;
use Modules\Groovesell\Entities\Product;
use Modules\Groovesell\Transformers\ProductResource;
use Modules\Groovesell\Transformers\MinimalProductResource;
use Modules\Groovesell\Entities\Domain;
use Carbon\Carbon;
class FunnelResource extends Resource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
$lastUpdated = $this->getLastUpdated();
$mainProduct = $this->getMainProduct();
$currencySymbol = $this->getCurrencySymbol();
$funnelDomain = Domain::where('funnel_assigned_to', $this->id)->first();
$domainInfo = $this->getDomainInfo($funnelDomain);
$resourceArray = [
'id' => $this->id,
'user_id' => $this->user_id,
'internal_name' => $this->internal_name,
'name' => $this->name,
'category' => $this->category,
'description' => $this->description,
'slug' => $this->slug,
'primary_color' => $this->primary_color,
'main_product_id' => $this->main_product_id,
'is_live' => $this->is_live,
'sender_id' => $this->sender_id,
'show_in_marketplace' => $this->show_in_marketplace,
'currency_code' => $this->currency_code,
'currency_symbol' => $currencySymbol,
'language' => $this->language,
'sales' => $this->sales,
'refunds' => $this->refunds,
'revenue' => $this->revenue,
'optins' => $this->optins,
'commissions' => $this->commissions,
'funnel_products_count' => $this->getFunnelProductsCount(),
'domain' => $domainInfo['id'],
'domain_name' => $domainInfo['name'],
'main_product' => new ProductResource($mainProduct),
];
if ($request->user()) {
$resourceArray = array_merge($resourceArray, [
'all_products' => MinimalProductResource::collection($this->getAllFunnelProducts()),
'last_updated_on' => $lastUpdated,
]);
}
return $resourceArray;
}
private function getLastUpdated()
{
$timezone = 'US/Eastern';
$now = Carbon::now();
$diffInDays = $now->diffInDays($this->updated_at);
return $diffInDays > 7 ? $this->updated_at->setTimezone($timezone)->format('m/d/Y') : $this->updated_at->diffForHumans();
}
private function getMainProduct()
{
return Product::where([
['funnel_id', $this->id],
['is_main', 1],
])->first();
}
private function getCurrencySymbol()
{
$locale = 'en-US'; // Replace with the user's locale
$currency = strtoupper($this->currency_code);
$fmt = new \NumberFormatter($locale . "@currency=$currency", \NumberFormatter::CURRENCY);
return $fmt->getSymbol(\NumberFormatter::CURRENCY_SYMBOL);
}
private function getDomainInfo($funnelDomain)
{
if ($funnelDomain != null) {
return [
'id' => $funnelDomain->id,
'name' => $funnelDomain->name,
];
} else {
return [
'id' => 0,
'name' => null,
];
}
}
private function getFunnelProductsCount()
{
$allFunnelProducts = Product::where('funnel_id', $this->id)->get();
return $allFunnelProducts ? count($allFunnelProducts) : 0;
}
private function getAllFunnelProducts()
{
return Product::where('funnel_id', $this->id)->get();
}
}