<?php

namespace Myvetshop\Module\Clinique\Api\Insight\Repository;

class InsightOrderRepository extends AbstractInsightRepository
{
    protected static function getTable(): string
    {
        return _DB_PREFIX_ . 'orders';
    }

    protected static function getAlias(): string
    {
        return 'o';
    }

    protected static function getDefaultSelects(): array
    {
        return [
            'id' => 'o.id_order',
            'reference' => 'o.reference',
            'invoice_date' => 'DATE_FORMAT(i.date_add, "%Y-%m-%dT%T' . (new \DateTimeImmutable())->format('P') . '")',
            'state' => 'o.current_state',
            'supplier' => 'c.centrale',
            'clinic_privileged_code' => 'c.code_privilege',
            'clinic_name' => 'c.name',
            'clinic_customer_code' => 'c.code_client',
        ];
    }

    protected static function getJoins(): string
    {
        return
            ' INNER JOIN ' . _DB_PREFIX_ . 'myvetshop_clinique c ON c.id_carrier=o.id_carrier OR c.id_carrier_home=o.id_carrier'
            . ' INNER JOIN ' . _DB_PREFIX_ . 'order_invoice i ON i.id_order=o.id_order';
    }

    /** @param int[] $ids */
    public function countPeriod(?\DateTimeInterface $from, ?\DateTimeInterface $to, ?array $ids = null): int
    {
        return $this->count(self::prepareCriteria($from, $to, $ids));
    }

    /**
     * @param int[] $ids
     *
     * @return list<array<string, string>>
     */
    public function findPeriod(?\DateTimeInterface $from, ?\DateTimeInterface $to, ?array $ids = null, ?int $limit = null, ?int $offset = null): array
    {
        return $this->findBy(self::prepareCriteria($from, $to, $ids), ['invoice_date' => 'DESC'], $limit, $offset);
    }

    /**
     * @param int[] $ids
     *
     * @return array<string, string|string[]|int|int[]|\DateTimeInterface>
     */
    private static function prepareCriteria(?\DateTimeInterface $from, ?\DateTimeInterface $to, ?array $ids = null): array
    {
        $criteria = ['state:not' => 15];
        $from === null ?: $criteria['invoice_date:supeq'] = $from;
        $to === null ?: $criteria['invoice_date:infeq'] = $to;
        $ids === null ?: $criteria['id'] = $ids;

        return $criteria;
    }
}
