<?php

namespace App\Repositories\Shop;

use App\Models\Shop\PriceList;
use App\Traits\Model\Basic;

class PriceLists
{
    use Basic;

    public static function init($tariffId = false)
    {
        return [
            'sale_channels' => SaleChannels::getOptions(),
            'statuses' => Tariffs::getStatuses(),
            'taxes' => Taxes::getOptions(),
            'price_list' => [
                'tariff_id' => $tariffId,
                'price_list_values' => [],
            ],
        ];
    }

    public static function getByOfferAndSaleChannel($offer_id, $sale_channel_id)
    {
        return PriceList::bySaleChannel($sale_channel_id)->byOffer($offer_id)->get();
    }

    public static function getByOffer($offer_id)
    {
        return PriceList::byOffer($offer_id)->get();
    }

    public static function getStatus($status_id)
    {
        return self::getStatuses()[$status_id];
    }

    public static function getStatuses()
    {
        return ['Actif', 'Suspendu', 'Invisible', 'Obsolete'];
    }

    public static function getByTariff($id)
    {
        return PriceList::byTariff($id)->get();
    }

    public static function edit($id)
    {
        $price_list = self::getFull($id)->toArray();
        if (count($price_list['price_list_values']) === 0) {
            $price_list['price_list_values'][] = [];
        }

        return $price_list;
    }

    public static function getPrices($id)
    {
        return PriceList::with('price_list_values')->find($id);
    }

    public static function getFull($id)
    {
        return PriceList::with(['price_list_values'])->find($id);
    }

    public static function store($data)
    {
        $id = $data['id'] ?? false;
        $price_list_values = $data['price_list_values'] ?? [];
        $deleted_values = array_map('intval', array_filter($data['deleted_price_list_value_ids'] ?? [], function ($value) {
            return $value !== null && $value !== '';
        }));
        unset($data['price_list_values']);
        unset($data['deleted_price_list_value_ids']);
        $price_list = $id ? self::update($data) : self::create($data);
        PriceListValues::purgeRemovedValues($price_list->id, $deleted_values);
        PriceListValues::storePrices($price_list->id, $price_list_values);

        return $price_list;
    }

    public static function getModel()
    {
        return PriceList::query();
    }
}
