<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Http\Helper\Helper;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Set the counters';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        try {
            $this->setListsCounts();
        } catch(\Exception $e) {
            \Log::error('set:counter-setListsCounts: '.$e->getMessage());
        }

        try {
            $this->setSendingServerSendingLimitCounters();
        } catch(\Exception $e) {
            \Log::error('set:counter-setSendingServerSendingLimitCounters => '.$e->getMessage());
        }

        try {
            $this->setSendingServerStatus();
        } catch(\Exception $e) {
            \Log::error('set:counter-setSendingServerStatus => '.$e->getMessage());
        }

        // Should be after setSendingServerStatus() so sending servers already checked
        try {
            $this->setScheduledCampaignStatus();
        } catch(\Exception $e) {
            \Log::error('set:counter-setScheduledCampaignStatus => '.$e->getMessage());
        }

        // Re-Run campaign if stopped for any reason
        try {
            $this->rerunCampaign();
        } catch(\Exception $e) {
            \Log::error('relayzo:cleaner:1 => '.$e->getMessage());
        }
    }

    /**
     * Re-Run the running status campaing stopped for some reason
    */
    protected function rerunCampaign() 
    {
      $schedules = \App\Models\ScheduleCampaign::whereIn('status', ['Running'])
          ->orderBy('id', 'desc')
          ->get();
        if(count($schedules) > 0) {
          foreach($schedules as $schedule) {
            $schedle_campaign_stat_id = \App\Models\ScheduleCampaignStat::whereScheduleCampaignId($schedule->id)->value('id');
            $campaign_stat_log = \App\Models\ScheduleCampaignStatLog::whereScheduleCampaignStatId($schedle_campaign_stat_id)
              ->orderBy('id', 'desc')
              ->limit(1)
              ->get();
            // get last email send difference in minutes
            $diff = \Carbon\Carbon::parse($campaign_stat_log[0]->created_at)->diffInMinutes(\Carbon\Carbon::now());
            // if more than 15 min
            if($diff > 15) {
              // update to scheduled from running, then it will again start
              \App\Models\ScheduleCampaign::whereId($schedule->id)->update(['status' => 'Scheduled']);
            }
          }
        }
    }

    /**
    * Re-set the sending limit and set the next timestamp
    */
    protected function setListsCounts()
    {
        $lists = \App\Models\Lists::all();

        foreach($lists as $list) {
          // get all list contacts
          $total_contacts = \App\Models\Contact::whereListId($list->id)->count();

          // update total_contacts for List
          \App\Models\Lists::whereId($list->id)
          ->update([
            'total_contacts' => $total_contacts
          ]);
        }
    }

    /**
    * Re-set the sending limit and set the next timestamp
    */
    protected function setSendingServerSendingLimitCounters()
    {
        \App\Models\SendingServer::where('hourly_sent_next_timestamp', '<', \Carbon\Carbon::now())
          ->update([
            'hourly_sent' => 0,
            'hourly_sent_next_timestamp' => \Carbon\Carbon::now()->addHour(1)
          ]);
        \App\Models\SendingServer::where('daily_sent_next_timestamp', '<', \Carbon\Carbon::now())
          ->update([
            'daily_sent' => 0,
            'daily_sent_next_timestamp' => \Carbon\Carbon::now()->addDay(1)
          ]);
    }

    /**
   * Update the sending server status to active for System Inactive / System Paused
  */
  protected function setSendingServerStatus()
  {
    $sending_servers = \App\Models\SendingServer::WhereIn('status', ['System Inactive', 'System Paused'])->get();
    foreach($sending_servers as $sending_server) {
      $status = null;
      if($sending_server->status == 'System Paused') {
        $speed_attributes = json_decode($sending_server->speed_attributes);
        if($speed_attributes->speed == 'limited') {
          if($speed_attributes->duration == 'hourly') {
            if($sending_server->hourly_sent < $speed_attributes->limit) {
              $status = 'Active';
            }
          } elseif($speed_attributes->duration == 'daily') {
            if($sending_server->daily_sent < $speed_attributes->limit) {
              $status = 'Active';
            }
          }
        } else {
          $status = 'Active';
        }
      } elseif($sending_server->status == 'System Inactive') {
        $connection = Helper::configureSendingNode($sending_server->type, $sending_server->sending_attributes);
        if($connection['success']) {
          $status = 'Active';
        }
      }

      if(!empty($status)) {
        \App\Models\SendingServer::whereId($sending_server->id)
        ->update([
          'status' => $status,
          'notification' => null
        ]);
      }
    }
  }

  /**
   * Update the scheduled campaigns status to active System Paused
  */
  protected function setScheduledCampaignStatus()
  {
    $schedules = \App\Models\ScheduleCampaign::whereStatus('System Paused')
      ->select('id', 'sending_server_ids', 'sending_speed')->get();
    foreach($schedules as $schedule) {
      $sending_serves = \App\Models\SendingServer::WhereIn('id', explode(',', $schedule->sending_server_ids))
      ->where('status', 'Active')
      ->get();

      if(count($sending_serves) > 0) {
        // Scheduled and RunningLimit will be entertain again
        if(json_decode($schedule->sending_speed)->speed == 'limited') {
          \App\Models\ScheduleCampaign::whereId($schedule->id)
            ->update([
              'status' => 'RunningLimit',
              'send_datetime' => \Carbon\Carbon::now()
            ]);
        } else {
          \App\Models\ScheduleCampaign::whereId($schedule->id)
            ->update([
              'status' => 'Resume',
              'thread_no' => 1
            ]);
        };
        
      }
    }
  }

}
