<?php
/**
 * _             _       _
 * | |____      _| | __ _| |__
 * | '_ \ \ /\ / / |/ _` | '_ \
 * | |_) \ V  V /| | (_| | |_) |
 * |_.__/ \_/\_/ |_|\__,_|_.__/.
 *
 * @author    Bwlab di Luigi Massa <info@bwlab.it>
 * @copyright since 2014 Bwlab
 * @license   proprietary
 */

declare(strict_types=1);

if (!defined('_PS_VERSION_')) {
    exit;
}

use Bwlab\Withdrawal\Service\WithdrawalRequestService;

class BwwithdrawalWithdrawalModuleFrontController extends ModuleFrontController
{
    public $ssl = true;
    public $auth = true;

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

        if (!$this->isXmlHttpRequest()) {
            Tools::redirect('index.php?controller=my-account');
        }
    }

    public function initContent(): void
    {
        if (!$this->isTokenValid()) {
            $this->ajaxDie(json_encode(['success' => false, 'message' => $this->trans('Invalid token.', [], 'Modules.Bwwithdrawal.Front')]));
        }

        $orderId = (int) Tools::getValue('id_order');
        $customerName = trim((string) Tools::getValue('customer_name'));
        $customerEmail = trim((string) Tools::getValue('customer_email'));

        if ($orderId <= 0 || $customerName === '' || !Validate::isEmail($customerEmail)) {
            $this->ajaxDie(json_encode(['success' => false, 'message' => $this->trans('Invalid data.', [], 'Modules.Bwwithdrawal.Front')]));
        }

        $order = new Order($orderId);
        if (!Validate::isLoadedObject($order) || (int) $order->id_customer !== (int) $this->context->customer->id) {
            $this->ajaxDie(json_encode(['success' => false, 'message' => $this->trans('Order not found.', [], 'Modules.Bwwithdrawal.Front')]));
        }

        try {
            /** @var WithdrawalRequestService $service */
            $service = $this->module->get('bwwithdrawal.service.withdrawal_request');

            $orderProducts = $order->getProducts();
            $referenceDate = new DateTime($order->date_add);
            $langIso = $this->context->language->iso_code ?? 'it';

            $request = $service->submit(
                $orderId,
                (int) $this->context->customer->id,
                (int) $this->context->shop->id,
                $customerName,
                $customerEmail,
                $order->reference,
                $orderProducts,
                $referenceDate,
                (string) ($_SERVER['HTTP_USER_AGENT'] ?? ''),
                $langIso,
            );

            $this->ajaxDie(json_encode([
                'success' => true,
                'withdrawal_id' => $request->getId(),
                'message' => $this->trans(
                    'Your withdrawal request #%id% has been submitted successfully.',
                    ['%id%' => $request->getId()],
                    'Modules.Bwwithdrawal.Front'
                ),
            ]));
        } catch (RuntimeException $e) {
            $this->ajaxDie(json_encode(['success' => false, 'message' => $e->getMessage()]));
        }
    }

    public function isXmlHttpRequest(): bool
    {
        return isset($_SERVER['HTTP_X_REQUESTED_WITH'])
            && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
    }

    public function isTokenValid(): bool
    {
        $token = (string) Tools::getValue('token');

        return $token !== '' && $token === Tools::getToken(false);
    }
}
