<?php

namespace Modules\TPConnector\Events;

use App\Transaction;
use Illuminate\Broadcasting\Channel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Queue\SerializesModels;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Support\Collection;
use Modules\TPConnector\Transformers\SellResource;

class TransactionCreatedEvent implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    var $transaction;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(Transaction $transaction)
    {
        $this->transaction = $transaction;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return Channel
     */
    public function broadcastOn()
    {
        return new Channel('location-' . $this->transaction->location_id);
    }

    /**
     * The event's broadcast name.
     *
     * @return string
     */
    public function broadcastAs()
    {
        return 'TransactionCreated';
    }

    /**
     * Get the data to broadcast.
     *
     * @return array
     */
    public function broadcastWith()
    {
        /** @var Collection $taxes */
        $taxes = $this->transaction->sell_lines->pluck('line_tax')->unique()->filter()->values();
        $taxes = $taxes->push($this->transaction->tax)->unique()->filter()->values();
        $variations = $this->transaction->sell_lines->pluck('variations')->unique()->filter()->values();
        $products = $this->transaction->sell_lines->pluck('product')->unique()->filter()->values();
        $categories = $products->pluck('category')->unique()->filter()->values();
        $subCategories = $products->pluck('sub_category')->unique()->filter()->values();
        return [
            'data' => [
                new SellResource($this->transaction)
            ],
            'tables' => collect([$this->transaction->table])->filter()->map->only(['id', 'name']),
            'taxes' => $taxes->map->only(['id', 'name', 'amount']),
            'variations' => $variations->map->only(['id', 'name', 'sub_sku']),
            'products' => $products->map->only(['id', 'name', 'product_custom_field1', 'product_custom_field2', 'type', 'category_id', 'sub_category_id']),
            'categories' => $categories->map->only(['id', 'name']),
            'sub_categories' => $subCategories->map->only(['id', 'name', 'parent_id']),
        ];
    }
}
