<?php

namespace App\Console\Commands;

use App\Http\Controllers\SIS\ProcessingEmailCrae;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class CFDINominaEmails extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cfdinominaemails:cron';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Comando para los recordatorios importes netos email';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        date_default_timezone_set('America/Mexico_City');

        $registro = DB::table('nomina')
            ->select('nomina.*')
            ->where('nomina.correoenviado', '=', 0)
            ->whereNotNull('nomina.xml')
            ->whereNotNull('nomina.pdf')
            ->take(20)->get();

        if (count($registro) > 0) {
            foreach ($registro as $key => $row) {
                $to_name = 'Facturación';
                $subject = 'CFDI Nómina - ' . $row->nombreemisor;
                $to = $row->correo;
                $path = "/home/api-test.acrescotec.com/public_html/public/" . $row->xml;
                $path2 = "/home/api-test.acrescotec.com/public_html/public/" . $row->pdf;
                $cc = [];
                $bcc = ["timbrado.crae@gmail.com"];

                $contenido = ['receptor' => $row->nombre, 'rfc_receptor' => $row->rfc, 'emisor' => $row->nombreemisor, 'correo_emisor' => 'nomina.crae@gmail.com', 'periodo' => $row->periodo];

                dispatch(new ProcessingEmailCrae($contenido, $to, $cc, $bcc, $to_name, $subject, $path, $path2));

                DB::table('nomina')
                    ->where('nomina.id_nomina', '=', $row->id_nomina)
                    ->update([
                        "correoenviado" => 1,
                        "updated_at" => date('Y-m-d H:i:s')
                    ]);
            }
        }
    }
}
