<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Webklex\PHPIMAP\ClientManager;
use App\Models\ReplyServer;
use App\Http\Helper\Helper;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Process application replies';
    public $app_id = 1;

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $reply_servers = ReplyServer::active()->get();
        foreach($reply_servers as $reply_server) {
          $validate_cert = $reply_server->validate_cert == 'Yes' ? true : false;
          $password = !empty($reply_server->password) ? \Crypt::decrypt($reply_server->password) : '';

          $clientManager = new ClientManager();

          $client = $clientManager->make([
            'host'          => $reply_server->host,
            'port'          => $reply_server->port,
            'encryption'    => $reply_server->encryption,
            'validate_cert' => $validate_cert,
            'username'      => $reply_server->username,
            'password'      => $password,
            'protocol'      => $reply_server->method
          ]);

          try {
            //Connect to the IMAP Server
            $client->connect();

            //Get all Mailboxes
            $aFolder = $client->getFolders();

            //Loop through every Mailbox
            foreach($aFolder as $oFolder){
              //Get 1 day old Messages of the current Mailbox $oFolder
              $aMessage = $oFolder->query()->since(now()->subDays(1))->get();
              foreach($aMessage as $oMessage) {     

               // need html to get mail ref
               $full_detail = $oMessage->getHTMLBody(true);
               // echo $full_detail = !empty($oMessage->getTextBody()) ? $oMessage->getTextBody() : $oMessage->getHTMLBody(true);

                try {
                  // To process only campaign bounces; reply_ref can be drip etc
                  $RZ_type = Helper::getRelayzoRef($full_detail);
                } catch(\Exception $e) {
                  $RZ_type = 'campaign';
                  //echo $e->getMessage();
                }

                list($app_id, $stat_log_id, $stat_id, $to_email, $section) = Helper::toEamil_Section($RZ_type, $reply_server->app_id);

                if(!empty($stat_id)) {
                  Helper::saveReplies($stat_id, $to_email, $stat_log_id, $section, $full_detail, $app_id);
                }
                
              }

              if($reply_server->delete_after_processing == 'Yes') {
                // Delete the message afer process
                $reply_server->delete();
              }


            }
          } catch (\Exception $e) {
            // echo $e->getMessage();
          }
        }

    }
}
