<?php
namespace App\Command\Money;

use App\Alias\Connection;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

#[AsCommand(
    name: 'money:lookup',
    hidden: false
)]
class Lookup extends Command
{
    public function __construct(protected Connection $connection, string $name = null)
    {
        parent::__construct($name);
    }

    public function execute(InputInterface $input, OutputInterface $output)
    {
        $io = new SymfonyStyle($input, $output);
        $io->title('Lookup Money');

        while (true) {
            $io->info('Checking pending');
            if ($this->hasPendingMoney()) {
                $io->success('Running money get UF');
                $io->note($this->runGetUF());
            }
        }
        return Command::SUCCESS;
    }

    protected function hasPendingMoney(): bool
    {
        $query = "SELECT 1 FROM pago WHERE uf IS NULL AND fecha BETWEEN 0 AND DATE_ADD(CURDATE(), INTERVAL 9 DAY)";
        $statement = $this->connection->connect()->query($query);
        return $statement->rowCount() > 0;
    }
    protected function runGetUF(): string
    {
        $command = "/code/bin/console money:uf:get";
        $result = shell_exec($command);
        if (!$result or $result === null) {
            throw new \Exception();
        }
        return $result;
    }
}
