<?php

namespace App\Console\Commands;

use App\Http\Models\Site;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $siteList = Site::query()->where('is_bq', 1)->get();
        $rankConnection = DB::connection('rank');

        foreach ($siteList as $key => $value) {

            if (!empty($value->old_id)) {

                $listReportList = $rankConnection->table('project_listreport')->where('project_id', $value->old_id)->get();
                foreach ($listReportList as $kk => $vv) {

                    $ym = $vv->ym . '01';
                    $date = date('Y-m-d H:i:s', strtotime('last day of this month', strtotime($ym)));

                    if ($vv->traffic >= 2000 && !$value->reach_2000_at) {
                        $value->update(['reach_2000_at' => $date]);
                    }
                    if ($vv->traffic >= 1500 && !$value->reach_1500_at) {
                        $value->update(['reach_1500_at' => $date]);
                    }
                    if ($vv->traffic >= 1000 && !$value->reach_1000_at) {
                        $value->update(['reach_1000_at' => $date]);
                    }
                    if ($vv->traffic >= 500 && !$value->reach_500_at) {
                        $value->update(['reach_500_at' => $date]);
                    }
                    if ($vv->traffic >= 300 && !$value->reach_300_at) {
                        $value->update(['reach_300_at' => $date]);
                    }
                    \App\Http\Models\MasterMeter::query()->create([
                        'site_id' => $value->id,
                        'old_id' => $value->old_id,
                        'cn_title' => $value->cn_title,
                        'domain' => $value->domain,
                        'traffic' => $vv->traffic,
                        'inquire' => $vv->inquire,
                        'ym' => date('Ym')
                    ]);
                }
            }
        }

        $this->info('success');
        return;
    }

}