<?php

namespace Myvetshop\Module\Clinique\Cron;

use Symfony\Component\Console\Output\OutputInterface;

class ConnectionPurgeCronTask implements CronTaskInterface
{
    private \Db $db;

    public function __construct(
        \Db $db
    ) {
        $this->db = $db;
    }

    public function run(OutputInterface $output): void
    {
        if (\time() < \strtotime('2025-06-01 00:00:00')) {
            return;
        }

        $this->db->execute(
            'DELETE c, cs
            FROM ps_connections c
            LEFT JOIN ps_connections_source cs ON (c.id_connections = cs.id_connections)
            WHERE c.date_add < DATE_SUB(NOW(), INTERVAL 6 MONTH)'
        );

        $this->db->execute(
            'DELETE cs
            FROM ps_connections_source cs
            LEFT JOIN ps_connections c ON (c.id_connections = cs.id_connections)
            WHERE c.id_connections IS NULL'
        );

        $this->db->execute('OPTIMIZE TABLE ps_connections, ps_connections_source');

        $this->db->execute(
            'DELETE c
            FROM `ps_cart` c
            LEFT JOIN `ps_orders` o ON (o.id_cart = c.id_cart)
            WHERE o.id_cart IS NULL
		        AND c.date_add < DATE_SUB(NOW(), INTERVAL 6 MONTH)'
        );

        $this->db->execute(
            'DELETE g
            FROM ps_guest g
            LEFT JOIN ps_customer c ON (g.id_customer = c.id_customer)
            WHERE c.id_customer IS NULL'
        );

        $this->db->execute(
            'DELETE g
            FROM ps_guest as g
            LEFT JOIN ps_cart as c ON g.id_guest = c.id_guest
            WHERE id_cart IS NULL'
        );

        $this->db->execute('OPTIMIZE TABLE ps_cart, ps_guest');
    }
}
