<?php

namespace App\Console\Commands;

use App\Modules\Channel\Services\ChannelService;
use App\Modules\Channel\Services\CompanyService;
use Illuminate\Console\Command;
use Redis;
use DB;

class channelCpcCode extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'channel:cpccode {--get}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'reset cpc code';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $options = $this->option('get');
        if($options){
            $this->fetchtoDB();
        }else{
            $this->start();
        }
    }

    private function start()
    {
        $result = CompanyService::getAllCompanyCpcCode();
        //$result = DB::table('')
        foreach ($result as $item){
            $channel_user = DB::table('channel_users')->where('company_id',$item->id)->select('id')->get();
            if($channel_user->isNotEmpty()){
                foreach ($channel_user as $channel_user_id_info) {
                    $channels = ChannelService::getByChannelUserId($channel_user_id_info->id);
                    $code = empty($item->channel)?'zw005':$item->channel;
                    if($channels->isNotEmpty()){
                        foreach ($channels as $channel) {
                            Redis::hset('channel:setting:'.$channel->id,'cpc_channel',$code);
                        }
                    }
                }
            }
        }
    }


    private function fetchtoDB()
    {
        DB::select( 'truncate table cpc_channel_temp');
        for ($i = 1;$i<7000;$i++){
            //Redis::hset('channel:setting:'.$channel->id,'cpc_channel',$code);
            $c = \Redis::hget('channel:setting:'.$i,'cpc_channel');
            if ($c) {
                \DB::table('cpc_channel_temp')->insert([
                    'distribution_channel_id'=>$i,
                    'channel'=>$c,
                    'created_at'=>date('Y-m-d H:i:s')
                ]);
            }
        }
    }
}
