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

declare(strict_types=1);

namespace Bwlab\Withdrawal\Service;

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

use Bwlab\Withdrawal\Entity\WithdrawalRequest;

class WithdrawalMailService
{
    public function sendConfirmation(WithdrawalRequest $request, string $languageIsoCode = 'it'): bool
    {
        return (bool) \Mail::Send(
            (int) \Language::getIdByIso($languageIsoCode),
            'withdrawal_confirm',
            \Mail::l('Conferma richiesta di recesso'),
            $this->buildTemplateVars($request),
            $request->getCustomerEmail(),
            $request->getCustomerName(),
            null,
            null,
            null,
            null,
            _PS_MODULE_DIR_ . 'bwwithdrawal/mails/'
        );
    }

    public function sendMerchantNotification(WithdrawalRequest $request, string $languageIsoCode = 'it'): bool
    {
        $merchantEmail = $this->getMerchantEmail();
        if ($merchantEmail === '' || !\Validate::isEmail($merchantEmail)) {
            // ponytail: no valid merchant address configured → skip instead of crashing Mail::Send
            return false;
        }

        $templateVars = array_merge(
            $this->buildTemplateVars($request),
            ['{bo_url}' => $this->getBoUrl()]
        );

        return (bool) \Mail::Send(
            (int) \Language::getIdByIso($languageIsoCode),
            'withdrawal_merchant',
            \Mail::l('Nuova richiesta di recesso #{withdrawal_id}', ['withdrawal_id' => $request->getId()]),
            $templateVars,
            $merchantEmail,
            null,
            null,
            null,
            null,
            null,
            _PS_MODULE_DIR_ . 'bwwithdrawal/mails/'
        );
    }

    public function sendStatusUpdate(WithdrawalRequest $request, ?string $customerNote = null, string $languageIsoCode = 'it'): bool
    {
        // ponytail: pending has no notification; only the three actionable statuses email the customer
        if (!in_array($request->getStatus(), [
            WithdrawalRequest::STATUS_PROCESSING,
            WithdrawalRequest::STATUS_COMPLETED,
            WithdrawalRequest::STATUS_REJECTED,
        ], true)) {
            return false;
        }

        $vars = array_merge(
            $this->buildTemplateVars($request),
            ['{customer_note}' => $customerNote !== null ? trim($customerNote) : '']
        );

        return (bool) \Mail::Send(
            (int) \Language::getIdByIso($languageIsoCode),
            'withdrawal_status_update',
            \Mail::l('Aggiornamento richiesta di recesso'),
            $vars,
            $request->getCustomerEmail(),
            $request->getCustomerName(),
            null,
            null,
            null,
            null,
            _PS_MODULE_DIR_ . 'bwwithdrawal/mails/'
        );
    }

    private function getMerchantEmail(): string
    {
        $email = (string) \Configuration::get('BWWITHDRAWAL_MERCHANT_EMAIL');

        return $email !== '' ? $email : (string) \Configuration::get('PS_SHOP_EMAIL');
    }

    private function getBoUrl(): string
    {
        return $this->getShopUrl();
    }

    private function getShopUrl(): string
    {
        return (string) \Tools::getShopDomainSsl(true);
    }

    /** @return array<string, string> */
    private function buildTemplateVars(WithdrawalRequest $request): array
    {
        return [
            '{withdrawal_id}' => (string) $request->getId(),
            '{order_reference}' => $request->getOrderReference(),
            '{customer_name}' => $request->getCustomerName(),
            '{customer_email}' => $request->getCustomerEmail(),
            '{withdrawal_deadline}' => $request->getWithdrawalDeadline()->format('d/m/Y'),
            '{status}' => $request->getStatus(),
            '{shop_name}' => (string) \Configuration::get('PS_SHOP_NAME'),
            '{shop_url}' => $this->getShopUrl(),
        ];
    }
}
