<?php

namespace App\Http\Controllers\Api\EMails;

use App\Http\Controllers\Controller;
use App\Danoral\U;
use Webklex\IMAP\Client;
use App\Mail\SendMail;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

use App\Mail\Recibo as ReciboEMail;
use App\Danoral\Entidades\Entidad;
use App\Danoral\Entidades\EDatoType;
use App\Danoral\Entidades\SyncEntidades;
use App\Danoral\Bancos\sysOLD\Banco As BancoJSys;

class EMailController extends Controller
{

    public function sendCond(Request $request)
    {
        // $idE_edif = 100100020000000783; // 3061 CAMURIMAR
        // $idE_edif = 100100020000000480; // 8624 AGUA DE COCO
        // $idE_edif = 100100020000001072; // 3337 SOBRE LAS OLAS
        // $idE_edif = 100100020000001123; // 4288 YAMANDU
        // $idE_edif = 100100020000001125; // 3345 MACAIRA
        // $idE_edif = 100100020000001122; // 3344 ALTOSOL
        //$idE_edif = 100100020000001156; // 3354 EDIFICIO RESIDENCIAS TAORMINA
        $idE_edif = 100100020000001158; // 3355 RESIDENCIAS VISTA AL SOL

        $mesR       = 9;
        $anoR       = 2023;
        //$syb_moneda = 'U$D';
        $syb_moneda = 'Bs.';

        $tMes       = U::$MES[$mesR];
        $sMes       = U::getMesTxt($mesR);
        $sAno       = strval($anoR);

        $i_apto = 0;
        $i_email = 0;

        $eE = Entidad::find($idE_edif);
        $eE->loadDatos();
        echo $eE->edatos[EDatoType::$DATO_TYPE_EDIF_COD]->valueED . PHP_EOL;

        $idE_edif_old = SyncEntidades::cambioID_edif_R($idE_edif);
        $lBEF = BancoJSys::getListaBancos_Entidad($idE_edif_old);
        $forma_pago = [];

        foreach($lBEF as $bef){
            if($bef->visiblePago_banco){
                $fp = $bef->nombre_Banco . ' - ' .
                    $bef->numCTA_banco . ' - ' .
                    $bef->nombreTitular_banco . ' - ' .
                    $bef->RIFTitular_banco;
            
                array_push($forma_pago, $fp);
            }
        }


        foreach($eE->ESuper as $eA)
        {
            $eA->loadDatos();
            echo $i_apto++ . ' - ' . $eA->edatos[EDatoType::$DATO_TYPE_APTO_COD]->valueED . PHP_EOL;

            $cuota = $eA->CuotasView()->where([
                    ['anoDT', $anoR],
                    ['mesDT', $mesR],
                ])
                ->first();
            $monto = number_format($cuota->montoDT, 2, ',', '.') . ' ' . $syb_moneda;
            $hrefRecibo = 'http://apix.danoral.com/v1/recibo/' . $eA->idE.'/'.$anoR.'/'.$mesR;


            $rec = [
                'codEdif'       => $eE->edatos[EDatoType::$DATO_TYPE_EDIF_COD]->valueED,
                'nameEdif'      => $eE->edatos[EDatoType::$DATO_TYPE_NAME]->valueED,
                'RIFEdif'       => $eE->edatos[EDatoType::$DATO_TYPE_RIF_NRO]->valueED,
                'nameCliente'   => $eA->edatos[EDatoType::$DATO_TYPE_NAME]->valueED,
                'codCliente'    => $eA->edatos[EDatoType::$DATO_TYPE_APTO_COD_CLIENTE]->valueED,
                'codApto'       => $eA->edatos[EDatoType::$DATO_TYPE_APTO_COD]->valueED,
                'tMes'          => $tMes,
                'sMes'          => $sMes,
                'sAno'          => $sAno,
                'monto'         => $monto,
                'hrefRecibo'    => $hrefRecibo,

                'formaPago'     => $forma_pago,

                // 401
                //'formaPago' => [
                //    'BANCO MERCANTIL  - 01050638701638012601 - ADMINISTRADORA DANORAL C.A. - RIF J-300857565',
                //    'BANCO PROVINCIAL - 01080041230100002632 - ADMINISTRADORA DANORAL C.A. - RIF J-300857565',
                //]

                // 3345 MACAIRA
                //'formaPago' => [
                //    'BANCO VENEZOLANO DE CREDITO - 01040107110107165118 - RESIDENCIAS MACAIRA - RIF J-314542834',
                //]

                //3345 TAORMINA
                //'formaPago' => [
                //    'BANCO DE VENEZUELA - 01020235340000165686 - CONDOMINIO EDIFICIO RESIDENCIAS TAORMINA - RIF J-315387344',
                //]

            ];

            //print_r($rec);

            if(empty($eA->edatos[EDatoType::$DATO_TYPE_EMAIL]->valueED)) {
                echo 'coreo empty' .PHP_EOL ;
                echo ' --- empty' . PHP_EOL;
                continue;
            }

            $emails_res = explode("/", $eA->edatos[EDatoType::$DATO_TYPE_EMAIL]->valueED);

            $emails = [];
            foreach($emails_res as $email){
                $email = trim($email);

                echo $i_email++ . " $email" . PHP_EOL;

                if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
                    $emails[] = $email;
                }else{
                    echo "Esta dirección de correo ($email) NO es válida. ----------------------------########" . PHP_EOL;
                }

            }

            //$emails = ["versionunoti@gmail.com", "antonio.nieves@danoral.com", "nieves.antonio@gmail.com"];

            
            print_r($emails);

            //return; //se coloca por seguridad para evitar envios por error
            
            if(!empty($emails)){
                Mail::to($emails)
                    ->send(new ReciboEMail($rec));
                echo('   --> SEND : ' . implode(", ", $emails) . PHP_EOL);
            }else{
                echo('   --> NO SEND : email empty : (' . implode(", ", $emails) . ')' . PHP_EOL);
            }
            
            //return;            


            echo ' --- ' . PHP_EOL;

        }

        return;

    }

    public function SendTest()
    {
        $recipent = ['nieves.antonio@gmail.com', 'antonio.nieves.m@gmail.com', 'antonio_nieves@danoral.com', 'versionunoti@gmail.com'];

        /*
        Mail::to('sistemas@danoral.com')
            ->bcc($recipent)
            ->send(new SendMail());
        */

        echo 'OK...';
    }

    public function MailTest()
    {

        $oClient = new Client([
            'host'          => 'danoral.com',
            'port'          => 993,
            'encryption'    => 'ssl',
            'validate_cert' => false,
            'username'      => 'antonio.nieves@danoral.com',
            'password'      => 'n13v35MA',
            'protocol'      => 'imap'
        ]);
        /* Alternative by using the Facade
        $oClient = Webklex\IMAP\Facades\Client::account('default');
        */

        //Connect to the IMAP Server
        $oClient->connect();

        //Get all Mailboxes
        /** @var \Webklex\IMAP\Support\FolderCollection $aFolder */
        $aFolder = $oClient->getFolders();

        //echo count($aFolder);
        echo ' <br /><br />';

        //Loop through every Mailbox
        /** @var \Webklex\IMAP\Folder $oFolder */
        foreach($aFolder as $oFolder){

            //Get all Messages of the current Mailbox $oFolder
            /** @var \Webklex\IMAP\Support\MessageCollection $aMessage */
            //            $aMessage = $oFolder->messages()->all()->get();

            //Get all messages within the last 5 days
            /** @var \Webklex\IMAP\Support\MessageCollection $aMessage */
            $aMessage = $oFolder->query()->since(now()->subDays(2))->get();

            //            print_r($oFolder);

            echo $oFolder->full_name;
            echo '<br /> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- <br /><br />';

            /** @var \Webklex\IMAP\Message $oMessage */
            foreach($aMessage as $oMessage){
                print_r($oMessage);
            /*
                    echo '<br />.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.- <br /><br />';

                    echo $oMessage->getUid(). '<br />';
                    echo $oMessage->getMessageId().'<br />';
                    echo $oMessage->getFrom()[0]->mail.'<br />';
                    print_r($oMessage->getFrom()).'<br />';
                    echo $oMessage->getSubject().'<br /><br />';
                    echo 'Attachments: '.$oMessage->getAttachments()->count().'<br />';
                    echo $oMessage->getHTMLBody(true);

                //Move the current Message to 'INBOX.read'

                if($oMessage->moveToFolder('INBOX.read') == true){
                    echo 'Message has ben moved';
                }else{
                    echo 'Message could not be moved';
                }
            */
            }
        }
    }


}
