<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\ScheduleCampaignStat;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Set Opens and Clicks counter';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        // get all campaign stats and set open/clicks
        $campaign_stats = ScheduleCampaignStat::orderBy('id', 'DESC')->get();
        foreach($campaign_stats as $stat) {
            $opens_all = ScheduleCampaignStat::statLogOpens($stat->id)->get()->count();
            $opens_unique = ScheduleCampaignStat::statLogOpens($stat->id, 'unique')->get()->count();
            $clicks_all = ScheduleCampaignStat::statLogClicks($stat->id)->get()->count();
            $clicks_unique = ScheduleCampaignStat::statLogClicks($stat->id, 'unique')->get()->count();
            $opens_clicks = json_encode([
                "total_opens" => $opens_all,
                "unique_opens" => $opens_unique,
                "total_clicks" => $clicks_all,
                "unique_clicks"=> $clicks_unique
            ]);

            ScheduleCampaignStat::whereId($stat->id)->update([
                "opens_clicks" => $opens_clicks
            ]);
        }
    }
}
