<?php

namespace App\Helpers\FirstParty\DFS;

use App\Models\CandidateDomain;
use Exception;
use Http;

class DFSBacklinks
{
    public static function processAndSaveToCandidateDomains($directory)
    {
        // Get all the JSON files in the directory
        $jsonFiles = glob($directory.'/*.json');

        dd($jsonFiles);

        // Loop through each file
        foreach ($jsonFiles as $file) {
            // Check if the file name matches the pattern (1.json, 2.json, etc.)
            if (preg_match('/\/(\d+)\.json$/', $file, $matches)) {
                // Decode the JSON file
                $data = json_decode(file_get_contents($file), false);

                foreach ($data->result[0]->items as $item) {
                    $candidate_domain = CandidateDomain::where('from_domain', $item->domain_from)->first();

                    if (is_null($candidate_domain)) {
                        $candidate_domain = new CandidateDomain;
                        $candidate_domain->to_url = $item->url_to;
                        $candidate_domain->from_domain = $item->domain_from;
                        $candidate_domain->from_tld = get_tld_from_url($item->url_from);

                        if (is_array($item->domain_from_platform_type)) {
                            $candidate_domain->platform_type = implode(',', $item->domain_from_platform_type);
                        } else {
                            $candidate_domain->platform_type = $item->domain_from_platform_type;
                        }

                        $candidate_domain->from_url = $item->url_from;
                        $candidate_domain->from_title = $item->page_from_title;
                        $candidate_domain->from_image_alt = $item->alt;
                        $candidate_domain->from_image_url = $item->image_url;
                        $candidate_domain->save();

                    }
                }
            }
        }
    }

    public static function backlinksPaginationLive($target, $search_after_token, $value = 1000)
    {
        $api_url = config('dataforseo.url');

        $api_version = config('dataforseo.api_version');

        $api_timeout = config('dataforseo.timeout');

        $query = [
            'target' => $target,
            'search_after_token' => $search_after_token,
            'value' => $value,
            'mode' => 'as_is',
        ];

        try {
            $response = Http::timeout($api_timeout)->withBasicAuth(config('dataforseo.login'), config('dataforseo.password'))->withBody(
                json_encode([(object) $query])
            )->post("{$api_url}{$api_version}backlinks/backlinks/live");

            if ($response->successful()) {
                return $response->body();
            }
        } catch (Exception $e) {
            return null;
        }

        return null;

    }
}
