<?php

namespace OtomaticAi\Jobs;

use OtomaticAi\Api\OtomaticAi\Client;
use OtomaticAi\Models\Netlinking;
use OtomaticAi\Models\Persona;
use OtomaticAi\Utils\Scheduler;
use OtomaticAi\Vendors\Illuminate\Support\Arr;

class FetchNetlinkingJob extends Job
{

    /**
     * Create a new job instance.
     */
    public function __construct() {}

    /**
     * Execute the job.
     */
    public function handle()
    {
        $api = new Client;
        $campaigns = $api->getNetlinkingCampaigns();

        if (!empty($campaigns)) {
            $localCampaigns = Netlinking::all()->keyBy('uuid');

            foreach ($campaigns as $campaign) {

                $uuid = Arr::get($campaign, 'uuid');
                $title = Arr::get($campaign, 'title');
                $language = Arr::get($campaign, 'language');
                $targetUrl = Arr::get($campaign, 'target_url');
                $anchorText = Arr::get($campaign, 'anchor_text');
                $modules = Arr::get($campaign, 'modules', []);
                $categoryId = Arr::get($campaign, 'category_id');
                $personaId = Arr::get($campaign, 'profile_id');

                // detect if the campaign is already in the database
                // create the campaign
                if (!$localCampaigns->has($uuid)) {

                    // Set category
                    if (!empty($categoryId)) {
                        Arr::set($modules, "wordpress.categories.automatic.enabled", false);
                        Arr::set($modules, "wordpress.categories.custom", [$categoryId]);
                    }

                    // Set persona
                    if (!empty($personaId)) {
                        $persona = Persona::find($personaId);
                        if (!empty($persona)) {
                            Arr::set($modules, "wordpress.author_id", $persona->user_id);
                        } else {
                            $personaId = null;
                        }
                    }

                    $netlinking = new Netlinking();
                    $netlinking->uuid = $uuid;
                    $netlinking->title = $title;
                    $netlinking->language = $language;
                    $netlinking->target_url = $targetUrl;
                    $netlinking->anchor_text = $anchorText;
                    $netlinking->modules = $modules;
                    $netlinking->persona_id = $personaId;

                    if ($netlinking->save()) {
                        Scheduler::single("generate_netlinking", [$netlinking->id]);

                        // update campaign status
                        $api->updateNetlinkingCampaign($uuid, [
                            "status" => "pending"
                        ]);
                    }
                }
            }
        }
    }
}
