<?php
/**
 * TamRank Score Service
 *
 * Centrale orchestrator voor SEO scores.
 * Beheert caching en aanroepen van calculators.
 *
 * @package TamRank
 * @since 8.2.0
 *
 * ARCHITECTURE GUARANTEE:
 * - This class is the ONLY class allowed to calculate scores and persist score meta.
 * - No other class may write to _tam_rank_meta_score, _tam_rank_content_score, or _tam_rank_audit_score.
 * - UI layers must be read-only consumers via this service.
 */

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

class TamRank_Score_Service
{

    /**
     * Get singleton instance
     * @var TamRank_Score_Service|null
     */
    private static $instance = null;

    private function __construct()
    {
        // Hook into save_post to automatically recalculate scores
        add_action('save_post', array($this, 'update_meta_score'));
    }

    public static function get_instance()
    {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Haal Meta Score op (Realtime of Cache)
     * 
     * @param int $post_id
     * @return int Score 0-100
     */
    public function get_meta_score(int $post_id): int
    {
        // Probeer cache
        $cached = get_post_meta($post_id, '_tam_rank_meta_score', true);
        if ($cached !== '' && is_numeric($cached)) {
            return (int) $cached;
        }

        // Bereken live als cache ontbreekt
        return $this->update_meta_score($post_id);
    }

    /**
     * Herbereken en cache Meta Score
     *
     * @param int $post_id
     * @return int Nieuwe score
     */
    public function update_meta_score(int $post_id): int
    {
        // Guard: Autosaves en revisies negeren
        if (wp_is_post_autosave($post_id) || wp_is_post_revision($post_id)) {
            return 0;
        }

        if (!class_exists('TamRank_Meta_Calculator')) {
            require_once dirname(__FILE__) . '/class-tamrank-meta-calculator.php';
        }

        $post = get_post($post_id);
        if (!$post)
            return 0;

        // Verzamel data
        $focus_keyword = get_post_meta($post_id, '_tam_rank_focus_keyword', true);
        $meta_title = get_post_meta($post_id, '_tam_rank_meta_title', true) ?: $post->post_title;
        $meta_description = get_post_meta($post_id, '_tam_rank_meta_description', true);
        $custom_slug = get_post_meta($post_id, '_tam_rank_custom_slug', true);
        $slug = $custom_slug ?: $post->post_name;

        $data = [
            'title' => $meta_title,
            'description' => $meta_description,
            'focus_keyword' => $focus_keyword,
            'slug' => $slug
        ];

        // Bereken score
        $score = TamRank_Meta_Calculator::calculate($data);

        // Update cache
        update_post_meta($post_id, '_tam_rank_meta_score', $score);

        // Update ook de 'total' audit score (voorlopig gelijk aan meta score + content score later)
        $this->update_total_score($post_id);

        return $score;
    }

    /**
     * Haal Content Score op (Lazy - rekent NIET zelf)
     *
     * @param int $post_id
     * @return int|null Score of null als nog niet berekend
     */
    public function get_content_score(int $post_id)
    {
        $score = get_post_meta($post_id, '_tam_rank_content_score', true);
        return is_numeric($score) ? (int) $score : null;
    }


    /**
     * Update Totaal Score (Meta + Content)
     * Wordt gebruikt door Dashboard en Lijstoverzichten
     */
    public function update_total_score(int $post_id): int
    {
        $meta_score = (int) get_post_meta($post_id, '_tam_rank_meta_score', true);
        $content_score = get_post_meta($post_id, '_tam_rank_content_score', true);

        // Als content score bestaat, gebruik weging: 30% Meta, 70% Content
        if (is_numeric($content_score) && $content_score !== '') {
            $total = round($meta_score * 0.30 + (int) $content_score * 0.70);
        } else {
            // Anders alleen meta score (100%)
            $total = $meta_score;
        }

        update_post_meta($post_id, '_tam_rank_audit_score', $total);
        return (int) $total;
    }

    /**
     * Update Content Score via Analyzer
     */
    public function update_content_score(int $post_id): int
    {
        if (!class_exists('TamRank_Content_Analyzer')) {
            // Check likely paths
            $paths = [
                dirname(dirname(__FILE__)) . '/admin/content/class-tamrank-content-analyzer.php',
                dirname(__FILE__) . '/class-tamrank-content-analyzer.php'
            ];
            foreach ($paths as $path) {
                if (file_exists($path)) {
                    require_once $path;
                    break;
                }
            }
        }

        if (class_exists('TamRank_Content_Analyzer')) {
            $analyzer = new TamRank_Content_Analyzer();
            $post = get_post($post_id);

            if (!$post)
                return 0;

            $focus_keyword = get_post_meta($post_id, '_tam_rank_focus_keyword', true);
            $content = $post->post_content;

            $result = $analyzer->analyze($content, $focus_keyword, $post_id);
            $score = isset($result['score']) ? (int) $result['score'] : 0;

            update_post_meta($post_id, '_tam_rank_content_score', $score);
            return $score;
        }

        return 0;
    }

    /**
     * Refresh ALL scores for a post (Meta + Content + Total)
     * Dit is de methode die de Bulk Audit moet gebruiken.
     */
    public function refresh_post_score(int $post_id): array
    {
        // 1. Update Meta Score
        $meta_score = $this->update_meta_score($post_id);

        // 2. Update Content Score
        $content_score = $this->update_content_score($post_id);

        // 3. Update Total Score (uses cached meta/content we just saved)
        $total_score = $this->update_total_score($post_id);

        return [
            'meta' => $meta_score,
            'content' => $content_score,
            'total' => $total_score
        ];
    }
}
