<?php

declare(strict_types=1);

/**
 * Export des remboursements
 */
class OrderSlipExporter
{
    /**
     * @var OrderSlip
     */
    protected $orderSlip;

    /**
     * @var Order
     */
    protected $order;

    /**
     * @var Clinique
     */
    protected $clinique;

    public function __construct(
        OrderSlip $orderSlip,
        ?Order $order = null,
        ?Clinique $clinique = null
    ) {
        $this->orderSlip = $orderSlip;

        $this->order = $order ?? new Order($orderSlip->id_order);
        if (!$clinique) {
            $idClinique = Clinique::getCliniqueByCarrier($this->order->id_carrier);
            $this->clinique = new Clinique($idClinique);
        } else {
            $this->clinique = $clinique;
        }
    }

    /**
     * @return array<int, array<int,float|int|string>>
     *
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     */
    public function getLignesComptables(): array
    {
        $orderSlipDate = DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $this->orderSlip->date_add);
        $invoiceDate = DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $this->order->invoice_date);

        if (!$orderSlipDate || !$invoiceDate) {
            throw new Exception('Une erreur s\'est produite lors de l\'instanciation de la date de commande et de la date du bon de commande');
        }

        $warehouse = new Warehouse($this->clinique->id_warehouse);

        return [
            [
                $this->orderSlip->id,
                $orderSlipDate->format('d/m/Y'),
                $this->orderSlip->id_order,
                $invoiceDate->format('d/m/Y'),
                $this->clinique->code_privilege,
                $this->clinique->centrale,
                $warehouse->name,
                round($this->orderSlip->total_products_tax_excl, 2),
                round($this->orderSlip->total_shipping_tax_excl, 2),
                round($this->orderSlip->amount, 2),
            ],
        ];
    }
}
