<?php

namespace common\logic\PointSale\PointSale\Repository;

use common\helpers\GlobalParam;
use common\logic\AbstractRepository;
use common\logic\Distribution\Distribution\Model\Distribution;
use common\logic\PointSale\PointSale\Model\PointSale;
use common\logic\Producer\Producer\Model\Producer;

class PointSaleRepository extends AbstractRepository
{
    protected PointSaleRepositoryQuery $query;

    public function loadDependencies(): void
    {
        $this->query = $this->loadService(PointSaleRepositoryQuery::class);
    }

    public function getDefaultOptionsSearch(): array
    {
        return [
            'with' => [],
            'join_with' => [],
            'orderby' => 'is_bread_box ASC, name ASC',
            'attribute_id_producer' => 'point_sale.id_producer'
        ];
    }

    public function findOnePointSaleById(int $id): ?PointSale
    {
        return PointSale::searchOne(['id' => $id]);
    }

    public function findOnePointSaleByIdUser(int $idUser): ?PointSale
    {
        return PointSale::searchOne([
            'id_user' => $idUser
        ]);
    }

    public function findOnePointSaleByName(string $name): ?PointSale
    {
        return PointSale::searchOne([
            'name' => $name
        ]);
    }

    public function findPointSalesByDistribution(Distribution $distribution)
    {
        return PointSale::find()
            ->with(['pointSaleDistribution' => function ($q) use ($distribution) {
                $q->where(['id_distribution' => $distribution->id]);
            }])
            ->where([
                'id_producer' => $distribution->producer->id,
            ])
            ->all();
    }

    /**
     * Retourne le nombre de points de vente pour le producteur courant.
     */
    public static function countPointSales(): int
    {
        return PointSale::searchCount(['id_producer' => GlobalParam::getCurrentProducerId()]);
    }

    public function findPointSales()
    {
        return PointSale::find()
            ->where('id_producer = ' . GlobalParam::getCurrentProducerId())
            ->all();;
    }

    public function queryPointSalesPublic(Producer $producer)
    {
        return PointSale::find()
            ->where([
                'id_producer' => $producer->id,
                'restricted_access' => 0,
                'status' => 1
            ])->orderBy(
                'code ASC, restricted_access ASC, is_bread_box ASC, `default` DESC, name ASC'
            );
    }

    public function populatePointSaleDropdownList(): array
    {
        $pointSalesArrayDropdown = ['' => '--'];
        $pointSalesArray = $this->findPointSales();

        foreach ($pointSalesArray as $pointSale) {
            $pointSalesArrayDropdown[$pointSale['id']] = $pointSale['name'];
        }

        return $pointSalesArrayDropdown;
    }
}