<?php

declare(strict_types=1);

require_once _PS_MODULE_DIR_ . 'myvetshopclinique' . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . 'Clinique.php';

class AdminOrdersController extends AdminOrdersControllerCore
{
    public function __construct()
    {
        parent::__construct();

        $cookieContent = Context::getContext()->cookie->getAll();
        if (isset($cookieContent['profile']) && 5 == $cookieContent['profile']) {
            $rowCarrier = Db::getInstance()->getRow(
                'SELECT `id_carrier`, `id_carrier_home`
                FROM `' . _DB_PREFIX_ . Clinique::TABLE . '`
                WHERE `id_employee` = ' . (int) $cookieContent['id_employee']
            );

            if (is_array($rowCarrier) && isset($rowCarrier['id_carrier'], $rowCarrier['id_carrier_home'])) {
                $this->_where = ' AND a.`id_carrier` IN (' . (int) $rowCarrier['id_carrier'] . ', ' . (int) $rowCarrier['id_carrier_home'] . ') ';
            }
        }

        // Remplace la colonne "paiement"
        $fieldList = [];
        foreach ($this->fields_list as $key => $value) {
            if ('payment' == $key) {
                $fieldList['centrale'] = [
                    'title' => $this->l('Centrale'),
                    'align' => 'text-center',
                    'type' => 'string',
                    'filter_key' => 'warehouse!name',
                    'orderby' => false,
                ];
            } elseif ('cname' == $key) {
                $fieldList['code_privilege'] = [
                    'title' => 'Clinique',
                    'align' => 'text-center',
                    'type' => 'string',
                    'filter_key' => 'clinique!code_privilege',
                    'orderby' => false,
                ];
                $fieldList['delivery'] = [
                    'title' => 'Liv. à domicile',
                    'align' => 'text-center',
                    'type' => 'bool',
                    'filter_key' => 'carrier!domicile',
                    'orderby' => false,
                    'callback' => 'printLivDomicile',
                ];
                $fieldList['donation'] = [
                    'title' => 'Micro Don',
                    'align' => 'text-center',
                    'type' => 'string',
                    'filter_key' => 'cart!donation_amount',
                    'orderby' => false,
                ];
            } else {
                $fieldList[$key] = $value;
            }
        }
        $this->fields_list = $fieldList;
        $this->fields_list['reference']['filter_key'] = 'a!reference';

        $this->_select .= ',
        a.`reference` AS reference,
        carrier.`domicile` AS delivery,
        clinique.`code_privilege` AS code_privilege,
        warehouse.`name` as centrale,
        warehouse.`reference` as centrale_reference,
        cart.`donation_amount` as donation';

        $this->_join .= '
        LEFT JOIN `' . _DB_PREFIX_ . 'carrier` carrier ON (carrier.`id_carrier` = a.`id_carrier`)
        LEFT JOIN `' . _DB_PREFIX_ . 'customer` customer ON (customer.`id_customer` = a.`id_customer`)
        LEFT JOIN `' . _DB_PREFIX_ . 'warehouse_carrier` wc ON (wc.`id_carrier` = a.`id_carrier`)
        LEFT JOIN `' . _DB_PREFIX_ . 'warehouse` warehouse ON (warehouse.`id_warehouse` = wc.`id_warehouse`)
        LEFT JOIN `' . _DB_PREFIX_ . 'myvetshop_clinique` clinique ON (clinique.`id_group` = customer.`id_default_group`)
        LEFT JOIN `' . _DB_PREFIX_ . 'cart` cart ON (cart.`id_cart` = a.`id_cart`)';
    }

    /**
     * @param array<string, mixed> $tr
     */
    public function printLivDomicile(string $id_order, array $tr): string
    {
        return $tr['delivery'] ? $this->l('Yes') : $this->l('No');
    }

    /**
     * @throws PrestaShopDatabaseException
     */
    public function renderKpis(): string
    {
        $time = time();
        $kpis = [];

        /* The data generation is located in AdminStatsControllerCore */

        $helper = new HelperKpi();
        $helper->id = 'box-conversion-rate';
        $helper->icon = 'icon-sort-by-attributes-alt';
        //$helper->chart = true;
        $helper->color = 'color1';
        $helper->title = $this->l('Conversion Rate', null, false, false);
        $helper->subtitle = $this->l('30 days', null, false, false);
        if (false !== ConfigurationKPI::get('CONVERSION_RATE')) {
            $helper->value = ConfigurationKPI::get('CONVERSION_RATE');
        }
        if (false !== ConfigurationKPI::get('CONVERSION_RATE_CHART')) {
            $helper->data = ConfigurationKPI::get('CONVERSION_RATE_CHART');
        }
        $helper->source = $this->context->link->getAdminLink('AdminStats') . '&ajax=1&action=getKpi&kpi=conversion_rate';
        $helper->refresh = (bool) (ConfigurationKPI::get('CONVERSION_RATE_EXPIRE') < $time);
        $kpis[] = $helper->generate();

        $helper = new HelperKpi();
        $helper->id = 'box-carts';
        $helper->icon = 'icon-shopping-cart';
        $helper->color = 'color2';
        $helper->title = $this->l('Abandoned Carts', null, false, false);
        $helper->subtitle = $this->l('Today', null, false, false);
        $helper->href = $this->context->link->getAdminLink('AdminCarts') . '&action=filterOnlyAbandonedCarts';
        if (false !== ConfigurationKPI::get('ABANDONED_CARTS')) {
            $helper->value = ConfigurationKPI::get('ABANDONED_CARTS');
        }
        $helper->source = $this->context->link->getAdminLink('AdminStats') . '&ajax=1&action=getKpi&kpi=abandoned_cart';
        $helper->refresh = (bool) (ConfigurationKPI::get('ABANDONED_CARTS_EXPIRE') < $time);
        $kpis[] = $helper->generate();

        $helper = new HelperKpi();
        $helper->id = 'box-average-order';
        $helper->icon = 'icon-money';
        $helper->color = 'color3';
        $helper->title = $this->l('Average Order Value', null, false, false);
        $helper->subtitle = $this->l('30 days', null, false, false);
        if (false !== ConfigurationKPI::get('AVG_ORDER_VALUE')) {
            $helper->value = sprintf($this->l('%s tax excl.'), ConfigurationKPI::get('AVG_ORDER_VALUE'));
        }
        $helper->source = $this->context->link->getAdminLink('AdminStats') . '&ajax=1&action=getKpi&kpi=average_order_value';
        $helper->refresh = (bool) (ConfigurationKPI::get('AVG_ORDER_VALUE_EXPIRE') < $time);
        $kpis[] = $helper->generate();

        $helper = new HelperKpi();
        $helper->id = 'box-net-profit-visit';
        $helper->icon = 'icon-user';
        $helper->color = 'color4';
        $helper->title = $this->l('Net Profit per Visit', null, false, false);
        $helper->subtitle = $this->l('30 days', null, false, false);
        if (false !== ConfigurationKPI::get('NETPROFIT_VISIT')) {
            $helper->value = ConfigurationKPI::get('NETPROFIT_VISIT');
        }
        $helper->source = $this->context->link->getAdminLink('AdminStats') . '&ajax=1&action=getKpi&kpi=netprofit_visit';
        $helper->refresh = (bool) (ConfigurationKPI::get('NETPROFIT_VISIT_EXPIRE') < $time);
        $kpis[] = $helper->generate();

        $helper = new HelperKpi();
        $helper->id = 'box-donation';
        $helper->icon = 'icon-heart';
        $helper->color = 'color4';
        $helper->title = $this->l('Dons', null, false, false);
        $helper->subtitle = $this->l('30 days', null, false, false);

        $date = new DateTime('-1 month');

        $db = Db::getInstance();
        $result = $db->executeS(
        'SELECT SUM(c.donation_amount) AS total_amount_of_donations FROM `' . _DB_PREFIX_ . 'cart` c
            WHERE c.id_cart IN (
	            SELECT DISTINCT `' . _DB_PREFIX_ . 'orders`.id_cart FROM `' . _DB_PREFIX_ . 'orders`
	            INNER JOIN `' . _DB_PREFIX_ . 'order_history` ON `' . _DB_PREFIX_ . 'order_history`.id_order = `' . _DB_PREFIX_ . 'orders`.id_order
	            INNER JOIN `' . _DB_PREFIX_ . 'order_state` ON `' . _DB_PREFIX_ . 'order_state`.id_order_state = `' . _DB_PREFIX_ . 'order_history`.id_order_state
	            WHERE `' . _DB_PREFIX_ . 'order_state`.paid = 1
	            AND `' . _DB_PREFIX_ . 'orders`.invoice_date >= "' . $date->format('Y-m-d') . '"
            )'
        );

        $helper->value = '0 €';

        if (is_array($result) && !empty($result) && isset($result[0]['total_amount_of_donations']) && $result[0]['total_amount_of_donations']) {
            $helper->value = floatval($result[0]['total_amount_of_donations']) . ' €';
        }

        $kpis[] = $helper->generate();

        $helper = new HelperKpiRow();

        $helper->kpis = $kpis;

        return $helper->generate();
    }
}
