<?php

namespace App\Repositories\Shop;

use App\Models\Shop\SaleChannel;
use App\Repositories\Shop\Customers;
use App\Traits\Model\Basic;

class SaleChannels
{
    use Basic;

    public static function getDefaultID($customerId = false)
    {
        $default = self::getDefault($customerId);

        return $default ? $default->id : false;
    }

    public static function getDefault($customerId = false)
    {
        $sessionChannelId = session('shop.default_sale_channel_id');
        if ($sessionChannelId) {
            $sessionChannel = SaleChannel::find($sessionChannelId);
            if ($sessionChannel) {
                return $sessionChannel;
            }
        }

        $customer = $customerId ? Customers::get($customerId) : Customers::getAuth();

        if ($customer) {
            $customer->loadMissing('sale_channels');

            if ($customer->default_sale_channel_id) {
                $preferred = $customer->sale_channels->firstWhere('id', $customer->default_sale_channel_id);
                if (! $preferred) {
                    $preferred = SaleChannel::find($customer->default_sale_channel_id);
                }
                if ($preferred) {
                    session(['shop.default_sale_channel_id' => $preferred->id]);
                    return $preferred;
                }
            }

            if ($customer->sale_channels->isNotEmpty()) {
                session(['shop.default_sale_channel_id' => $customer->sale_channels->first()->id]);
                return $customer->sale_channels->first();
            }
        }

        return self::getByCode('POSTE');
    }

    public static function getByCode($code)
    {
        return SaleChannel::byCode($code)->first();
    }

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