<?php namespace Eae\Command;

use Log;
use Sendinblue\Mailin;
use Config;
use DB;
use User;

class UpdateHardbouncesCommand extends BaseCommand
{
  protected $name = 'serami:update-hard-bounces';
  protected $description = 'Update Hard Bounces';

  public function fire()
  {
    Log::info('=== START :: UPDATE HARD BOUNCES ===');
    $mailin = new Mailin('https://api.sendinblue.com/v2.0', Config::get('project/mailin.apiKey'), 5000);

    $data = [
      "event"      => "hard_bounce",
      "start_date" => "2017-11-01"
    ];

    $report = $mailin->get_report($data);

    if ($report['code'] != 'success') { // If failed to get report
      RETURN;
    }

    if (!isset($report['data']) || count($report['data']) < 1) { // if no reports to be managed
      RETURN;
    }

    $reportData = $report['data'];

    foreach ($reportData as $reportItem) {
      if ($reportItem['from'] !== 'newsletter@amnesty.ch') {
        continue;
      }
      DB::beginTransaction();
      try {
        $user = User::full()
          ->where('email', $reportItem['email'])
          ->where('hard_bounced', 0)
          ->first();

        if ($user) {
          $user->hard_bounced = 1;
          $user->hard_bounced_reason = $reportItem['reason'];
          $user->save();
          DB::commit();
        }
        continue;
      } catch (Exception $e) {
        DB::rollback();
        Log::error($e);

      }
    }
    Log::info('=== END :: UPDATE HARD BOUNCES ===');
  }
}
