<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Webklex\PHPIMAP\ClientManager;
use App\Models\Bounce;
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
          ]);

          $this->app_id = $fbl->app_id;

          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) {
                // Get RZ_type header value
                try {
                  // To process only campaign bounces; RZ_type can be drip etc
                  $RZ_type = $oMessage->getHeaderInfo()->RZ_type_id;
                } catch(\Exception $e) {
                  $RZ_type = 'campaign';
                }

                // If campaign then needs to update schedule_campaing tables
                try {
                  $stat_id = explode('-', $RZ_type)[1];
                } catch(\Exception $e) {
                  $stat_id = 0;
                }

                $section = 'Campaign';
                $to_email = null;
                if(stripos($RZ_type, 'campaign') !== false) {
                  \App\Models\ScheduleCampaignStatLog::whereId($stat_id)->update(['status' => 'Spammed']);
                  $to_email = \App\Models\ScheduleCampaignStatLog::whereId($stat_id)->value('email');
                } elseif(stripos($RZ_type, 'trigger') !== false) {
                  \App\Models\TriggerScheduleStatLog::whereId($stat_id)->update(['status' => 'Spammed']);
                  $to_email = \App\Models\TriggerScheduleStatLog::whereId($stat_id)->value('email');
                  $section = 'Trigger';
                }

                $full_detail = !empty($oMessage->getTextBody()) ? $oMessage->getTextBody() : $oMessage->getHTMLBody(true);

                Helper::saveSpam($to_email, $stat_id, $section, $full_detail, $this->app_id);
              }

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

    }
}
