<?php
if (!defined('ABSPATH')) exit;

/**
 * Stores and evaluates consultation-generated automation rules.
 */
class VMO_Automation_Engine {
    private static $instance = null;

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

    public function sync_from_manifest($user_id, $session_id, $manifest) {
        $user_id = (int) $user_id;
        $session_id = sanitize_text_field((string) $session_id);
        $manifest = is_array($manifest) ? $manifest : array();
        $rules = is_array($manifest['automation_rules'] ?? null) ? $manifest['automation_rules'] : array();

        if ($user_id <= 0 || $session_id === '' || empty($rules)) {
            return false;
        }

        $state = array(
            'version' => 'vmo_automation_rules_v1',
            'source' => 'vmo_business_manifest',
            'session_id' => $session_id,
            'rules' => $rules,
            'synced_at' => current_time('mysql'),
            'active_rule_count' => count(array_filter($rules, function($rule) {
                return is_array($rule) && strpos((string) ($rule['status'] ?? ''), 'active') === 0;
            })),
        );

        update_user_meta($user_id, 'vmo_automation_rules', $rules);
        update_user_meta($user_id, 'vmo_automation_rules_' . $session_id, $rules);
        update_user_meta($user_id, 'vmo_automation_state', $state);
        update_user_meta($user_id, 'vmo_automation_state_' . $session_id, $state);

        do_action('vmo_automation_rules_synced', $user_id, $session_id, $state, $manifest);
        return $state;
    }

    public function evaluate_manifest_kpi_rules($user_id, $manifest, $current_metrics = array()) {
        $user_id = (int) $user_id;
        $manifest = is_array($manifest) ? $manifest : array();
        $current_metrics = is_array($current_metrics) ? $current_metrics : array();
        $targets = is_array($manifest['kpi_targets'] ?? null) ? $manifest['kpi_targets'] : array();
        $rules = is_array($manifest['automation_rules'] ?? null) ? $manifest['automation_rules'] : array();
        $recommendations = array();

        foreach ($rules as $rule) {
            if (!is_array($rule)) {
                continue;
            }
            $metric = sanitize_key((string) ($rule['trigger_metric'] ?? ''));
            if ($metric === '' || empty($targets[$metric])) {
                continue;
            }
            $target = is_array($targets[$metric]) ? $targets[$metric] : array();
            $current = isset($current_metrics[$metric]) ? (float) $current_metrics[$metric] : (float) ($target['current'] ?? 0);
            $goal = (float) ($target['target'] ?? 0);
            if ($goal > 0 && $current < $goal) {
                $recommendations[] = array(
                    'rule_id' => sanitize_key((string) ($rule['rule_id'] ?? $metric)),
                    'metric' => $metric,
                    'current' => $current,
                    'target' => $goal,
                    'gap' => $goal - $current,
                    'recommended_action' => sanitize_text_field((string) ($rule['action'] ?? 'review_metric')),
                    'approval_required' => !empty($rule['approval_required']),
                );
            }
        }

        if ($user_id > 0) {
            update_user_meta($user_id, 'vmo_automation_recommendations', $recommendations);
            update_user_meta($user_id, 'vmo_automation_recommendations_updated_at', current_time('mysql'));
        }

        return $recommendations;
    }
}