<?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::getCliniqueIdByCarrier($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 [
            [
                // numero_avoir
                $this->orderSlip->id,
                // date_avoir
                $orderSlipDate->format('d/m/Y'),
                // id_commande
                $this->orderSlip->id_order,
                // date_facture
                $invoiceDate->format('d/m/Y'),
                // clinique
                $this->clinique->code_privilege,
                // centrale
                $this->clinique->centrale,
                // entrepot
                $warehouse->name,
                // produits_ht
                round($this->orderSlip->total_products_tax_excl, 2),
                // port_ht
                round($this->orderSlip->total_shipping_tax_excl, 2),
                // total_ttc
                round($this->orderSlip->amount, 2),
            ],
        ];
    }
}
