<?php

declare(strict_types=1);

/**
 * Created by Aurélien RICHAUD (30/11/2017 15:37).
 */
require_once __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'classes' . \DIRECTORY_SEPARATOR . 'Clinique.php';

class AdminMyVetShopCliniqueStatistiquesController extends ModuleAdminController
{
    protected ?Clinique $clinique = null;

    public function __construct()
    {
        parent::__construct();

        $this->bootstrap = true;
    }

    /**
     * @param bool $isNewTheme
     */
    public function setMedia($isNewTheme = false): void
    {
        parent::setMedia($isNewTheme);

        $this->addJS(__PS_BASE_URI__ . 'modules/myvetshopclinique/js/jquery.flot.min.js');
        $this->addJS(__PS_BASE_URI__ . 'modules/myvetshopclinique/js/jquery.flot.pie.min.js');
    }

    /**
     * @return array<string, mixed>
     *
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     */
    public function getTemplateViewVars(): array
    {
        $db = Db::getInstance(false);

        $context = Context::getContext();
        \assert(null !== $context);

        if (!$context->employee) {
            throw new \Exception();
        }

        // ///////////////////////////////////////
        // / Détermine la clinique
        $clinique = Clinique::getCliniqueByEmployeeId((int) $context->employee->id);
        $cliniques = [];

        if (!$clinique) {
            if (1 == $context->employee->id_profile) {
                $result = $db->executeS('SELECT c.* FROM `' . _DB_PREFIX_ . Clinique::TABLE . '` c ORDER BY c.code_privilege ASC');

                if (!is_array($result)) {
                    $result = [];
                }

                $cliniques = ObjectModel::hydrateCollection(Clinique::class, $result);
            }

            $this->clinique = new Clinique(\intval(Tools::getValue('clinique_id')));
        } else {
            $this->clinique = $clinique;
            $cliniques[] = $this->clinique;
        }

        // ///////////////////////////////////////
        // / Détermine la période (par défaut : 1 mois)
        $date_min = $this->clinique->id ? new \DateTimeImmutable('-1 year') : new \DateTimeImmutable('-1 week');
        $dateMaxRaw = \strval(\Tools::getValue('date_max'));

        $date_max = $dateMaxRaw ? new \DateTimeImmutable($dateMaxRaw) : new \DateTimeImmutable();

        // ///////////////////////////////////////
        // / Isoles les commandes
        $query = 'SELECT o.* FROM `' . _DB_PREFIX_ . 'orders` o WHERE o.`invoice_date` >= "' . $date_min->format('Y-m-d 00:00:00')
            . '" AND `o`.`invoice_date` <= "' . $date_max->format('Y-m-d 23:59:59') . '"';
        if ($this->clinique->id) {
            $query .= ' AND o.`id_carrier` IN (' . $this->clinique->id_carrier . ', ' . $this->clinique->id_carrier_home . ')';
        }

        $result = $db->executeS($query);

        if (!is_array($result)) {
            $result = [];
        }

        /** @var Order[] $orders */
        $orders = ObjectModel::hydrateCollection(Order::class, $result);

        // ///////////////////////////////////////
        // / Calcul des indicateurs
        $indicateurs = [];

        // / 1 - CA total
        $indicateurs['ca_ttc'] = 0;
        $indicateurs['reduction_ttc'] = 0;
        $indicateurs['produits_ttc'] = 0;
        foreach ($orders as $order) {
            $indicateurs['ca_ttc'] += $order->total_paid_tax_incl;
            $indicateurs['reduction_ttc'] += $order->total_discounts_tax_incl;
            $indicateurs['produits_ttc'] += $order->total_products_wt;
        }

        // / 2 - Répartition par pet-foodeur [id_feature = 10]
        $product_manufacturer_cache = [];
        $indicateurs['ca_petfooder'] = [];
        $indicateurs['ca_petfooder_total'] = 0;
        foreach ($orders as $order) {
            foreach ($order->getProductsDetail() as $orderDetail) {
                if (!isset($product_manufacturer_cache[$orderDetail['id_product']])) {
                    $p = new Product($orderDetail['id_product']);
                    $m = new Manufacturer($p->id_manufacturer);

                    $product_manufacturer_cache[$p->id] = $m->name;
                }

                $petfooder = $product_manufacturer_cache[$orderDetail['id_product']];

                if (!isset($indicateurs['ca_petfooder'][$petfooder])) {
                    $indicateurs['ca_petfooder'][$petfooder] = 0;
                }

                $indicateurs['ca_petfooder'][$petfooder] += $orderDetail['total_price_tax_incl'];
                $indicateurs['ca_petfooder_total'] += $orderDetail['total_price_tax_incl'];
            }
        }

        return [
            'indicateurs' => $indicateurs,
            'cliniques' => $cliniques,
            'clinique' => $this->clinique,
        ];
    }

    /**
     * @return false|string
     *
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     *
     * {@inheritDoc}
     */
    public function renderList()
    {
        $helper = new HelperView();
        $this->setHelperDisplay($helper);
        $helper->tpl_vars = $this->getTemplateViewVars();
        if (null !== $this->base_tpl_view) {
            $helper->base_tpl = $this->base_tpl_view;
        }
        $view = $helper->generateView();

        return $view;
    }
}
