<?php

declare(strict_types=1);

class ExportSender
{
    /**
     * @throws \Exception
     */
    public function sendExport(ExportProduct $exportProduct, string $exportContent, string $emailTo): bool
    {
        $file_attachment = [];

        $file_attachment['content'] = $exportContent;
        $file_attachment['name'] = $exportProduct->name . '.csv';
        $file_attachment['mime'] = 'text/csv';

        $startDate = new \DateTime($exportProduct->date_start);
        $endDate = new \DateTime($exportProduct->date_end);
        $productsId = \json_decode($exportProduct->products, true);

        if (!is_array($productsId)) {
            throw new \Exception('Invalid exportProduct JSON');
        }

        $result = \Mail::Send(
            (int) \Configuration::get('PS_LANG_DEFAULT'),
            'export',
            'Export ' . $exportProduct->name,
            [
                '{exportName}' => $exportProduct->name,
                '{from}' => $startDate->format('d/m/Y'),
                '{to}' => $endDate->format('d/m/Y'),
                '{numberOfProduct}' => \count($productsId),
            ],
            $emailTo,
            null, // Receiver name
            \Configuration::get('PS_SHOP_EMAIL') ?: '', // Sender email
            \Configuration::get('PS_SHOP_NAME') ?: '', // Sender name
            $file_attachment,
            null,
            _PS_MAIL_DIR_,
            true // Die after error?
        );

        if ($result > 0) {
            return true;
        }

        throw new \Exception('Erreur lors de l\'envoi de l\'email');
    }
}
