<?php

declare(strict_types=1);

class AdminReturnController extends AdminReturnControllerCore
{
    public function __construct()
    {
        parent::__construct();

        // Jointure avec les groupes des clients.
        $this->_join .= ' INNER JOIN `' . _DB_PREFIX_ . 'customer_group` cg ON cg.`id_customer` = o.`id_customer`';

        /* En cas de connexion d'une clinique (profile = 5),
         * filtre pour n'avoir que les données concernant la clinique en question.
         */
        $context = \Context::getContext();
        if ($context) {
            $cookieContent = $context->cookie->getAll();
            if (isset($cookieContent['profile']) && 5 == $cookieContent['profile']) {
                $idGroup = Db::getInstance()->getRow(
                    'SELECT id_group FROM `' . _DB_PREFIX_ . Clinique::TABLE . '`'
                    . ' WHERE id_employee = ' . (int) $cookieContent['id_employee']
                );
                $idGroup = is_array($idGroup) && isset($idGroup['id_group']) ? (int) $idGroup['id_group'] : 0;
                $this->_join .= ' AND cg.`id_group` = ' . $idGroup;
            }
        }

        // Jointure avec les cliniques.
        $this->_join .= ' INNER JOIN `' . _DB_PREFIX_ . 'myvetshop_clinique` mvc'
            . ' ON cg.`id_group` = mvc.`id_group` OR cg.`id_group` = mvc.`id_group_rural`';

        // Récupération du code_client de clinique et du nom de centrale.
        $this->_select .= ', mvc.`code_client`, mvc.`centrale`';

        // Jointure avec les avoirs.
        $this->_join .= ' LEFT JOIN `' . _DB_PREFIX_ . 'order_slip` os ON os.`id_order` = o.`id_order`';

        // Récupération des infos d'avoir.
        $this->_select .= ', REPLACE(CONCAT(ROUND(os.`amount`, 2), " €"), ".", ",") as slip_amount';

        // Récupération de l'info de la présence de commentaire
        $this->_select .= ', IF(comment <> "", "Oui", "") as has_comment';

        // Ajout des infos dans la liste.
        $this->fields_list += [
            'centrale' => ['title' => 'Centrale', 'align' => 'center'],
            'code_client' => ['title' => 'Code clinique', 'align' => 'center'],
            'slip_amount' => ['title' => 'Avoir', 'align' => 'center'],
            'has_comment' => ['title' => 'Commentaire', 'align' => 'center'],
        ];
    }

    // Réécriture de la méthode renderForm pour ajouter des infos.
    public function renderForm(): string
    {
        // Définition du formulaire
        $this->fields_form = [
            'legend' => [
                'title' => 'Retour produit',
                'icon' => 'icon-clipboard',
            ],
            'input' => [
                [
                    'type' => 'hidden',
                    'name' => 'id_order',
                ],
                [
                    'type' => 'hidden',
                    'name' => 'id_customer',
                ],
                [
                    'type' => 'text_customer',
                    'label' => $this->trans('Customer', [], 'Admin.Global'),
                    'name' => '',
                    'size' => '',
                    'required' => false,
                ],
                [
                    'type' => 'text_order',
                    'label' => $this->trans('Order', [], 'Admin.Global'),
                    'name' => '',
                    'size' => '',
                    'required' => false,
                ],
                [
                    'type' => 'free',
                    'label' => $this->trans('Customer explanation', [], 'Admin.Orderscustomers.Feature'),
                    'name' => 'question',
                    'size' => '',
                    'required' => false,
                ],
                [
                    'type' => 'select',
                    'label' => $this->trans('Status', [], 'Admin.Global'),
                    'name' => 'state',
                    'required' => false,
                    'options' => [
                        'query' => OrderReturnState::getOrderReturnStates($this->context->language->id),
                        'id' => 'id_order_return_state',
                        'name' => 'name',
                    ],
                    'desc' => $this->trans('Merchandise return (RMA) status.', [], 'Admin.Orderscustomers.Help'),
                ],
                [
                    'type' => 'textarea',
                    'label' => 'Commentaire',
                    'name' => 'comment',
                    'rows' => 1,
                    'required' => false,
                ],
                [
                    'type' => 'list_products',
                    'label' => $this->trans('Products', [], 'Admin.Global'),
                    'name' => '',
                    'size' => '',
                    'required' => false,
                    'desc' => $this->trans('List of products in return package.', [], 'Admin.Orderscustomers.Help'),
                ],
                [
                    'type' => 'pdf_order_return',
                    'label' => $this->trans('Returns form', [], 'Admin.Orderscustomers.Feature'),
                    'name' => '',
                    'size' => '',
                    'required' => false,
                    'desc' => $this->trans('The link is only available after validation and before the parcel gets delivered.', [], 'Admin.Orderscustomers.Help'),
                ],
            ],
            'submit' => [
                'title' => $this->trans('Save', [], 'Admin.Actions'),
            ],
        ];

        // Récupération de la commande concernée par le retour.
        $order = new Order($this->object->id_order);

        // Récupération de l'avoir.
        $order_slip_array = OrderSlip::getOrdersSlip($order->id_customer, $order->id);
        $order_slip_array = is_array($order_slip_array) && count($order_slip_array) ? $order_slip_array[0] : null;

        // Récupération des produits retournés
        $products = OrderReturn::getOrdersReturnProducts($this->object->id, $order);

        // Récupération des quantités pour chaque produit retourné.
        $quantity_displayed = [];
        if ($returned_customizations = OrderReturn::getReturnedCustomizedProducts($this->object->id_order)) {
            foreach ($returned_customizations as $returned_customization) {
                $id_order_detail = (int) $returned_customization['id_order_detail'];
                $quantity_displayed[$id_order_detail] ??= 0;
                $quantity_displayed[$id_order_detail] += (int) $returned_customization['product_quantity'];
            }
        }

        // Préparation de la raison du retour.
        $this->object->question = '<span class="normal-text">' . nl2br($this->object->question) . '</span>';

        // Variables à passer au template.
        $this->tpl_form_vars = [
            'customer' => new Customer($this->object->id_customer),
            'url_customer' => $this->context->link->getAdminLink('AdminCustomers', true, [], [
                'id_customer' => $this->object->id_customer,
                'viewcustomer' => 1,
            ]),
            'text_order' => 'Commande n°' . $order->id . ' du ' . Tools::displayDate($order->date_upd)
                . '<span class="label label-success" style="margin-left: 10px;">' . Tools::displayPrice($order->total_paid) . '</span>'
                . (
                    $order_slip_array ?
                        '<br/><strong>Remboursé</strong>' .
                        '<br/>Avoir n°' . $order_slip_array['id_order_slip'] . ' du ' . $order_slip_array['date_add']
                        . '<span class="label label-danger" style="margin-left: 10px;">' . Tools::displayPrice($order_slip_array['amount']) . '</span>'
                        : ''
                ),
            'url_order' => $this->context->link->getAdminLink('AdminOrders', true, [], [
                'vieworder' => 1,
                'id_order' => (int) $order->id,
            ]),
            'picture_folder' => _THEME_PROD_PIC_DIR_,
            'returnedCustomizations' => $returned_customizations,
            'customizedDatas' => Product::getAllCustomizedDatas($order->id_cart),
            'products' => $products,
            'quantityDisplayed' => $quantity_displayed,
            'id_order_return' => $this->object->id,
            'state_order_return' => $this->object->state,
        ];

        return AdminController::renderForm();
    }

    // Réécriture de la méthode postProcess pour enregistrer les commentaires
    /**
     * @return bool|ObjectModel|void
     */
    public function postProcess()
    {
        $isSubmited = boolval(
            Tools::isSubmit('submitAddorder_return')
            || Tools::isSubmit('submitAddorder_returnAndStay')
        );
        $isAllowed = $this->access('edit');
        $id_order_return = Tools::getValue('id_order_return');
        $id_order_return = \is_string($id_order_return) ? \intval($id_order_return) : null;
        $comment = Tools::getValue('comment');
        if (!\is_string($comment)) {
            $comment = '';
        }

        if ($isSubmited && $isAllowed && $id_order_return && Validate::isUnsignedId($id_order_return)) {
            $orderReturn = new OrderReturn($id_order_return);
            \assert(property_exists($orderReturn, 'comment'));
            $orderReturn->comment = $comment;
            $orderReturn->save();
        }

        return parent::postProcess();
    }
}
