<?php

namespace App\Console\Commands;

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

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

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

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

          $clientManager = new ClientManager();

          $client = $clientManager->make([
            'host'          => $fbl->host,
            'port'          => $fbl->port,
            'encryption'    => $fbl->encryption,
            'validate_cert' => $validate_cert,
            'username'      => $fbl->username,
            'password'      => $password,
            'protocol'      => $fbl->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);
                //$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';
                }

              
                list($app_id, $stat_log_id, $stat_id, $to_email, $section) = Helper::toEamil_Section($RZ_type, $fbl->app_id, 'Spammed');
                
                if(!empty($stat_id)) {
                  Helper::saveSpam($stat_id, $to_email, $stat_log_id, $section, $full_detail, $app_id);
                }
                
              }

              if($fbl->delete_after_processing == 'Yes') {
                // Delete the message afer process
                $fbl->delete();
              }
            }
          } catch (\Exception $e) {}
        }

    }
}
