<?php
// Silence may be golden, but sometimes words paint the canvas of understanding.

namespace Plugli\Linksy\SearchAndReplace\Admin\Partials\SearchAndReplace\Events;

use Linksy\SearchAndReplace\Plugli\Standard\Helpers\Events;
use Plugli\Linksy\SearchAndReplace\Admin\Partials\SearchAndReplace\Utils;
use Linksy\SearchAndReplace\Plugli\Standard\Helpers\Database\Database;

class RunLinkAnalysisCronEvent extends Events
{
    use Utils;

    public $name = 'search_and_replace_links_analysis_cron';

    /**
     * Run the async task action
     */
    protected function handle()
    {
        $PROCESSED_LINKS_LIMIT = 40;
        $OFFSET = get_option('linksy_link_analysis_offset', 0);

        $processed_links = 0;
        $data = [];

        $linksy_links = Database::table("linksy_links")
            ->select(['post_id', 'clean_url', 'raw_url', 'anchor', 'host'])
            ->get();

        $links = array_slice($linksy_links, $OFFSET, $PROCESSED_LINKS_LIMIT);
        
        if (empty($links)) {
            return;
        }

        $db_broken_links = Database::table("linksy_broken_links");
        $existing_broken_links = $db_broken_links->select(['post_id', 'url', 'anchor'])->get();
        
        $broken_links_map = [];
        foreach ($existing_broken_links as $existing) {
            $key = $existing->post_id . '|' . $existing->url . '|' . $existing->anchor;
            $broken_links_map[$key] = true;
        }
        
        foreach ($links as $link) {
            if ($processed_links >= $PROCESSED_LINKS_LIMIT) {
                break;
            }
            
            $key = $link->post_id . '|' . $link->clean_url . '|' . $link->anchor;
            
            $result = $this->linksy_broken_link_check($link, 12, true);

            if (!empty($result) && !empty($result['url'])) {
                if (isset($broken_links_map[$key])) {
                    $this->insert_broken_link($link, $result);
                } else {
                    $data[] = $result;
                }

                $processed_links++;
            }
        }

        $OFFSET += $processed_links;
        update_option('linksy_link_analysis_offset', $OFFSET);

        if (!empty($data)) {
            $this->insert_multiple_broken_links($data);
        }

        // Stop cron job if all links have been processed
        if ($OFFSET >= count($linksy_links)) {
            update_option('linksy_link_analysis_cron_enabled', false);
            error_log("Link analysis cron job completed.");

            $event = $this->get_name();

            if (function_exists('wp_unschedule_event')) {
                $timestamp = wp_next_scheduled($event);
                wp_unschedule_event($timestamp, $event);
            }
        }
    }
}
