<?php

namespace Tricks\CampaignMonitor\Console\Commands;

use CS_REST_Transactional_SmartEmail;
use Illuminate\Console\Command;
use Illuminate\Support\Arr;

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

    /**
     * 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 int
     */
    public function handle()
    {
        $apiKeyConfigKey = 'campaignmonitor.transactional.api_key';
        $apiKey = config($apiKeyConfigKey);


        if (!$apiKey) {
            $this->error("Campaign Monitor API key not found in config, looking for '${apiKeyConfigKey}'.");
            exit(1);
        }

        $clientIdConfigKey = 'campaignmonitor.transactional.client_id';
        $clientId = config($clientIdConfigKey);

        if (!$clientId) {
            $this->error("Campaign Monitor client ID not found in config, looking for '${clientIdConfigKey}'.");
            exit(1);
        }

        $auth = array(
            'api_key' => $apiKey
        );

        $wrap = new CS_REST_Transactional_SmartEmail(null, $auth, $clientId);

        $result = $wrap->get_list();

        $mails = collect($result->response)->map(function($mail) use($auth) {
            $wrap = new CS_REST_Transactional_SmartEmail($mail->ID, $auth);
            return $wrap->get_details()->response;
        });

        $configuredMailIds = collect(config('campaignmonitor.transactional.mails'))->pluck('id');

        $mails = $mails->filter(function($mail) use ($configuredMailIds) {
            return $configuredMailIds->contains($mail->SmartEmailID);
        });

        $this->info("Found " . count($mails) . " smart email(s)");
        $this->info('');

        dump($mails->toArray());

        exit(0);
    }
}
