<?php 
/**
 * FluentC ScanService
 *
 * This file contains the adjustments for the Yoast Plugin
 *
 * @package FluentCPlugin
 * @author  FluentC <wp@fluentc.io>
 */


namespace FluentC\Services;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Scan {
    //
    private $site_url;
    private $urls;

    public function __construct(){
        $this->site_url = home_url();
       $this->urls = array();
    }
    public function scanSite() {
        $urls = $this->getAllPublishedContentUrls();
        $existingData = get_option('fluentc_site_scan', []);

        foreach ($urls as $url) {
            if (!isset($existingData[$url])) {
                $existingData[$url] = ['status' => 'active'];
            }
        }

        update_option('fluentc_site_scan', $existingData);
        set_transient('fluentc_last_scan_time', current_time('timestamp'), 7 * DAY_IN_SECONDS);

        return true;
    }

   

    public function getTotalUrls() {
        $all_urls = get_option('fluentc_site_scan', []);
        return count($all_urls);
    }

    public function toggleUrlStatus($url) {
        $data = get_option('fluentc_site_scan', []);

        if (isset($data[$url])) {
            $data[$url]['status'] = ($data[$url]['status'] === 'active') ? 'inactive' : 'active';
            update_option('fluentc_site_scan', $data);
            return true;
        }

        return false;
    }
    public function getUrls($page = 1, $per_page = 50) {
        $all_urls = get_option('fluentc_site_scan', []);
        
        // Add homepage if it's not already in the list
        $homepage_url = home_url('/');
        if (!isset($all_urls[$homepage_url])) {
            $all_urls = array_merge([$homepage_url => ['status' => 'active']], $all_urls);
            update_option('fluentc_site_scan', $all_urls);
        }

        $offset = ($page - 1) * $per_page;
        return array_slice($all_urls, $offset, $per_page, true);
    }
    
    private function getAllPublishedContentUrls() {
        $urls = [];
        $post_types = get_post_types(['public' => true]);

        foreach ($post_types as $post_type) {
            $posts = get_posts([
                'post_type' => $post_type,
                'post_status' => 'publish',
                'posts_per_page' => -1,
            ]);

            foreach ($posts as $post) {
                $urls[] = get_permalink($post);
            }
        }

        return $urls;
    }
    public function discover() {
        // First try sitemap discovery
        if ($this->discover_from_sitemaps()) {
            return $this->urls;
        }

        // Fallback to basic WordPress URLs if no sitemap
        return $this->discover_basic_wordpress_urls();
    }

    private function discover_from_sitemaps() {
        
        $sitemap_urls = array(
            $this->site_url . '/wp-sitemap.xml',              // WordPress core
            $this->site_url . '/sitemap_index.xml',           // Yoast/RankMath
            $this->site_url . '/sitemap.xml',                 // AIOSEO
        );

        foreach ($sitemap_urls as $sitemap_url) {
            $response = wp_remote_get($sitemap_url, array(
                'timeout' => 30,
                'sslverify' => false
            ));
            
            if (is_wp_error($response)) {
                continue;
            }

            $body = wp_remote_retrieve_body($response);
            if (empty($body)) {
                continue;
            }

            // Check if this is an index sitemap or regular sitemap
            if (strpos($body, '<sitemapindex') !== false) {
                $this->parse_sitemap_index($body);
            } else {
                $this->parse_sitemap($body);
            }

            // If we found URLs, we can stop looking for sitemaps
            if (!empty($this->urls)) {
                return true;
            }
        }

        return false;
    }

    private function parse_sitemap_index($content) {
        libxml_use_internal_errors(true);
        $xml = \simplexml_load_string($content);
        
        if (!$xml) {
            return;
        }

        // Handle different sitemap index formats
        $namespaces = $xml->getNamespaces(true);
        
        foreach ($xml->sitemap as $sitemap) {
            $loc = (string)$sitemap->loc;
            
            // Fetch and parse each individual sitemap
            $response = wp_remote_get($loc, array(
                'timeout' => 30,
                'sslverify' => false
            ));
            
            if (!is_wp_error($response)) {
                $body = wp_remote_retrieve_body($response);
                if (!empty($body)) {
                    $this->parse_sitemap($body);
                }
            }
        }
    }

    private function parse_sitemap($content) {
        libxml_use_internal_errors(true);
        $xml = simplexml_load_string($content);
        
        if (!$xml) {
            return;
        }

        // Handle different sitemap formats
        $namespaces = $xml->getNamespaces(true);
        
        // Standard sitemap format
        if ($xml->url) {
            foreach ($xml->url as $url) {
                $loc = (string)$url->loc;
                if ($this->is_valid_url($loc)) {
                    $this->urls[] = $loc;
                }
            }
        }
        
        // Some sitemaps use different formats
        elseif ($xml->link) {
            foreach ($xml->link as $url) {
                $loc = (string)$url->href;
                if ($this->is_valid_url($loc)) {
                    $this->urls[] = $loc;
                }
            }
        }
    }

    private function is_valid_url($url) {
        // Must be from same domain
        if (strpos($url, $this->site_url) !== 0) {
            return false;
        }

        // Skip admin, API, and feed URLs
        $skip_patterns = array(
            '/wp-admin',
            '/wp-json',
            '/feed',
            '/robots.txt',
            '/wp-login',
            '/xmlrpc.php',
        );

        foreach ($skip_patterns as $pattern) {
            if (strpos($url, $pattern) !== false) {
                return false;
            }
        }

        return true;
    }

    private function discover_basic_wordpress_urls() {
        $urls = array($this->site_url);  // Homepage
        
        // Get basic post/page URLs
        $post_types = get_post_types(array('public' => true));
        
        foreach ($post_types as $post_type) {
            $posts = get_posts(array(
                'post_type' => $post_type,
                'post_status' => 'publish',
                'posts_per_page' => -1,
                'fields' => 'ids',
            ));
            
            foreach ($posts as $post_id) {
                $urls[] = get_permalink($post_id);
            }
        }

        return array_unique(array_filter($urls));
    }

    public function scan_all_urls(){
        $urls = array($this->site_url);
        error_log(json_encode($urls));
        //Send Data to GraphQL.
        return $urls;
    }
}