<?php

namespace App\Console\Commands;

use App\Http\Logics\Admin\SocialLogic;
use App\Http\Models\Article;
use App\Http\Models\Site;
use App\Http\Models\SocialPublish;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class SocialSync extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'social:sync {type=0}';

    /**
     * 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()
    {
        $type = $this->argument('type');
        $social = new SocialLogic();

        $sitesMap = Site::query()->select(['id', 'facebook_page', 'facebook_page_token'])->get()->keyBy('id')->toArray();

        if ($type == 2) {
            $records = SocialPublish::query()->where([
                ['publish_at', '<', date('Y-m-d H:i:s')],
                ['social_sync_at', '=', null]
            ])->get();
            foreach ($records as $record) {
                list($err, $resultStatus) = $social->publish($record, $sitesMap);
//                $article->social_result = $result;
                $record->err = $err;
                $record->result_status = $resultStatus;
                $record->social_sync_at = date('Y-m-d H:i:s');
                $record->save();
            }
        }
        $this->info('success');
        return;
    }
}