<?php

namespace App\Commands;

use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use Config\Clients;
use Config\Database;
use App\Models\VentasModel;
use App\Libraries\FacturacionElectronica;

class ProbarConsultaDTEs extends BaseCommand
{
    protected $group       = 'DET Manager';
    protected $name        = 'probarconsultadtes';
    protected $description = 'Genera y envía los DTE legible y json que han sido procesados correctamente';
    protected $arguments   = ['isc' => 'Identificador del sistema de cliente'];
    protected $options     = ['--cant' => 'Cantidad maxima de DTE a tomar de la cola.'];
    
    public function run(array $params)
    {
        $isc = $params[0] ?? null;
        $cantDte = CLI::getOption('cant') ?? 5;

        if ($isc) {
            $client = new Clients();
            $dbgroup = $client->getDBGroup($isc);
            if ($dbgroup) 
            {
                $database = new Database();
                $dbConf = $database->getDatabaseConfig($dbgroup);
                $db = \Config\Database::connect($dbConf);

                $systemVersion = $client->getSystem($isc);
                $feStartDate = $client->getFeStartDate($isc);

                $ventasModel = new VentasModel($systemVersion, $db);

                $pendingSales = $ventasModel->getPendingSales($feStartDate, $cantDte);

                CLI::write(date('Y-m-d H:i:s').' '.$isc.' Ventas pendiente encontradas: ' . count($pendingSales));

                if($pendingSales){
                    foreach ($pendingSales as $sale) {
                        echo "Venta: " . $sale['id'] . " documento: " . $sale['documento'] . " dteCodGeneracion: " . $sale['dteCodGeneracion'] . "\n";
                    }
                }
            }
        }
    }
}