<?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
{
    /**
     * @var Clinique
     */
    protected $clinique;

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

        $this->bootstrap = true;
    }

    public function setMedia(): void
    {
        parent::setMedia();

        $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);

        /////////////////////////////////////////
        /// Détermine la clinique
        $clinique_id = Clinique::getCliniqueByEmployee(Context::getContext()->employee->id);
        $cliniques = [];

        if (!$clinique_id) {
            if (1 == Context::getContext()->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(Tools::getValue('clinique_id'));
        } else {
            $this->clinique = new Clinique($clinique_id);
            $cliniques[] = $this->clinique;
        }

        /////////////////////////////////////////
        /// Détermine la période (par défaut : 1 an)
        $date_min = new \DateTimeImmutable('-1 year');
        $date_max = Tools::getValue('date_max') ? new \DateTimeImmutable(Tools::getValue('date_max')) : new \DateTimeImmutable();

        /////////////////////////////////////////
        /// Isoles les commandes
        $query = 'SELECT o.* FROM `' . _DB_PREFIX_ . 'orders` o WHERE o.`date_add` >= "' . $date_min->format('Y-m-d 00:00:00')
            . '" AND `o`.`date_add` <= "' . $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 (!is_null($this->base_tpl_view)) {
            $helper->base_tpl = $this->base_tpl_view;
        }
        $view = $helper->generateView();

        return $view;
    }
}
