<?php

namespace Myvetshop\Module\Clinique\Cron;

use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Query\ResultSetMapping;
use Symfony\Component\Console\Output\OutputInterface;

class OrderTableRepairCronTask implements CronTaskInterface
{
    private EntityManagerInterface $entityManager;

    public function __construct(
        EntityManagerInterface $entityManager
    ) {
        $this->entityManager = $entityManager;
    }

    public function run(OutputInterface $output): void
    {
        $rsm = new ResultSetMapping();
        $rsm
            ->addScalarResult('id_order', 'id_order')
            ->addScalarResult('number', 'number')
            ->addScalarResult('date_add', 'date_add');

        /** @var list<array{id_order: int, number: int, date_add: string}> $selectedOrders */
        $selectedOrders = $this->entityManager
            ->createNativeQuery(
                'SELECT o.id_order, oi.number, oi.date_add FROM ps_orders o'
                . ' INNER JOIN ps_order_invoice oi ON oi.id_order = o.id_order'
                . ' WHERE o.invoice_date = "0000-00-00 00:00:00"'
                . ' AND o.invoice_number = 0',
                $rsm,
            )
            ->getResult();

        foreach ($selectedOrders as $selectedOrder) {
            $this->entityManager->getConnection()
                ->executeUpdate(
                    'UPDATE ps_orders SET invoice_number = :invoice_number, invoice_date = :invoice_date WHERE id_order = :id_order',
                    [
                        'invoice_number' => $selectedOrder['number'],
                        'invoice_date' => $selectedOrder['date_add'],
                        'id_order' => $selectedOrder['id_order'],
                    ]
                );
        }
    }
}
