<?php
// includes/class-vmo-feature-gate.php
if (!defined('ABSPATH')) exit;

/**
 * VMO Feature Gate — Granular per-feature plan gating with upgrade recommendations.
 *
 * Plan hierarchy (lowest → highest):
 *   free < tester < starter < pro < elite < enterprise
 */
class VMO_Feature_Gate {

    /** Plan hierarchy indices (higher number = higher tier). */
    private static $tiers = [
        'free'       => 0,
        'tester'     => 1,
        'starter'    => 2,
        'pro'        => 3,
        'elite'      => 4,
        'enterprise' => 5,
    ];

    /**
     * Feature → minimum plan required.
     * Key = feature slug, Value = minimum plan key.
     * Features not listed here are available to ALL plans (including free).
     */
    private static $feature_map = [
        // ── Builder & AI ─────────────────────────────
        'ai_consultation'       => 'tester',   // Full AI business consultation
        'ai_website_generation' => 'tester',   // AI website builder
        'ai_website_refinement' => 'tester',   // AI refinement agents
        'seo_tools'             => 'starter',  // SEO analyzer & optimizer
        'competitive_intel'     => 'pro',      // Competitive intelligence

        // ── Communications ───────────────────────────
        'email_marketing'       => 'starter',  // Email campaigns & templates
        'email_scheduling'      => 'starter',  // Scheduled email sends
        'email_tracking'        => 'starter',  // Open/click tracking pixels
        'sms_marketing'         => 'pro',      // Bulk SMS campaigns
        'power_dialer'          => 'pro',      // AI power dialer

        // ── CRM ──────────────────────────────────────
        'crm_basic'             => 'starter',  // Contact management
        'crm_interactions'      => 'starter',  // Interaction history
        'crm_ai_summary'        => 'pro',      // AI relationship summaries
        'crm_retention'         => 'pro',      // Retention action log

        // ── Payments & Commerce ──────────────────────
        'stripe_connect'        => 'starter',  // Stripe Connect store
        'invoices'              => 'pro',      // Invoice creation & sending
        'payment_links'         => 'starter',  // Payment link generation
        'customer_ltv'          => 'pro',      // Customer lifetime value analytics

        // ── Shipping ─────────────────────────────────
        'shipping_management'   => 'starter',  // Order fulfillment
        'carrier_discovery'     => 'pro',      // Auto carrier discovery
        'public_tracking'       => 'starter',  // Customer tracking page

        // ── Reports & Analytics ──────────────────────
        'basic_reports'         => 'starter',  // Standard business reports
        'advanced_analytics'    => 'pro',      // Deep analytics & trends
        'cfo_dashboard'         => 'starter',  // Financial KPIs
        'financial_insights'    => 'pro',      // AI financial interpretation

        // ── Media & Video ────────────────────────────
        'media_generation'      => 'tester',   // Image generation
        'video_generation'      => 'pro',      // Premium video (Sora)
        'tts_hd'                => 'pro',      // HD text-to-speech

        // ── Background Ops ───────────────────────────
        'background_ops'        => 'starter',  // Automated background operations

        // ── Documents ────────────────────────────────
        'document_generation'   => 'starter',  // Business document generation

        // ── Elite+ Features ──────────────────────────
        'priority_compute'      => 'enterprise', // Priority AI processing
        'white_label'           => 'enterprise', // White-label capabilities
    ];

    /**
     * Upgrade recommendation copy per feature.
     * Key = feature slug, Value = human-readable benefit description.
     */
    private static $upgrade_copy = [
        'ai_consultation'       => 'Get a full AI-powered business consultation that builds your entire brand, website, and marketing strategy.',
        'ai_website_generation' => 'Let AI generate complete, professional websites tailored to your business in minutes.',
        'seo_tools'             => 'Analyze and optimize your website for search engines with AI-powered SEO tools.',
        'competitive_intel'     => 'Get AI-driven competitive analysis and market positioning insights.',
        'email_marketing'       => 'Create and send professional email campaigns with templates, tracking, and automation.',
        'email_scheduling'      => 'Schedule emails to send at the perfect time for maximum engagement.',
        'email_tracking'        => 'Track email opens and clicks to measure campaign performance.',
        'sms_marketing'         => 'Launch bulk SMS marketing campaigns with audience targeting and AI-composed messages.',
        'power_dialer'          => 'Call leads automatically with AI-generated scripts and CRM integration.',
        'crm_basic'             => 'Manage all your contacts, leads, and customers in one intelligent CRM.',
        'crm_ai_summary'        => 'Get AI-generated summaries of your relationship with each contact over time.',
        'crm_retention'         => 'Track client retention actions and outcomes to reduce churn.',
        'stripe_connect'        => 'Accept payments online with VMO Pay — products, subscriptions, and checkout.',
        'invoices'              => 'Create and send professional invoices with online payment links.',
        'payment_links'         => 'Generate shareable payment links for any product or custom amount.',
        'customer_ltv'          => 'See customer lifetime value rankings and enrich your CRM with spend data.',
        'shipping_management'   => 'Manage orders, fulfillment, and delivery tracking.',
        'carrier_discovery'     => 'Auto-discover shipping carriers available in your region.',
        'basic_reports'         => 'Generate business intelligence reports across all your operations.',
        'advanced_analytics'    => 'Deep analytics with trend detection, AI insights, and forecasting.',
        'cfo_dashboard'         => 'Full CFO Dashboard with KPIs, sales trends, balance sheet, and tax calculator.',
        'financial_insights'    => 'AI-powered financial interpretation and profit & efficiency analysis.',
        'media_generation'      => 'Generate custom images for your website with AI.',
        'video_generation'      => 'Create premium video content with AI for hero sections and marketing.',
        'tts_hd'                => 'Convert text to natural HD speech for voice content and narration.',
        'background_ops'        => 'Automated background operations — SEO scans, email follow-ups, and more.',
        'document_generation'   => 'Generate professional business documents, contracts, and proposals.',
    ];

    /* ═══════════════════════════════════════════
     *  Core API
     * ═══════════════════════════════════════════ */

    /**
     * Check if the current user (or a given plan) can access a feature.
     *
     * @param string      $feature  Feature slug from $feature_map.
     * @param string|null $plan     Plan key (auto-detected from current user if null).
     * @return bool
     */
    public static function can_access($feature, $plan = null) {
        if ($plan === null) {
            $plan = self::get_current_plan();
        }
        $plan = self::normalize($plan);

        // Admins always have full access
        if (current_user_can('manage_options')) return true;

        $required = self::$feature_map[$feature] ?? 'free';
        $user_tier = self::$tiers[$plan] ?? 0;
        $req_tier  = self::$tiers[$required] ?? 0;

        return $user_tier >= $req_tier;
    }

    /**
     * Get the minimum plan required for a feature.
     *
     * @param string $feature
     * @return string Plan key (e.g. 'pro', 'starter').
     */
    public static function required_plan($feature) {
        return self::$feature_map[$feature] ?? 'free';
    }

    /**
     * Get an upgrade recommendation for a feature the user can't access.
     *
     * @param string      $feature
     * @param string|null $plan
     * @return array|null  Null if user has access; otherwise array with upgrade info.
     */
    public static function get_upgrade_prompt($feature, $plan = null) {
        if (self::can_access($feature, $plan)) return null;

        $required = self::$feature_map[$feature] ?? 'free';
        $plan_info = class_exists('VMO_Plan_Policy') ? VMO_Plan_Policy::get_plan($required) : null;

        return [
            'feature'       => $feature,
            'required_plan' => $required,
            'plan_name'     => $plan_info['name'] ?? ucfirst($required),
            'plan_price'    => $plan_info['price'] ?? 0,
            'benefit'       => self::$upgrade_copy[$feature] ?? 'Upgrade to unlock this feature.',
            'current_plan'  => $plan ?? self::get_current_plan(),
        ];
    }

    /**
     * Return the full feature gate map for JS (with access flags for current user).
     *
     * @return array  Keyed by feature slug → {allowed, required_plan, plan_name, benefit}
     */
    public static function get_client_map() {
        $plan = self::get_current_plan();
        $map = [];
        foreach (self::$feature_map as $feature => $required) {
            $allowed = self::can_access($feature, $plan);
            $map[$feature] = [
                'allowed'       => $allowed,
                'required_plan' => $required,
                'plan_name'     => ucfirst($required),
                'benefit'       => self::$upgrade_copy[$feature] ?? '',
            ];
            if (!$allowed) {
                $plan_info = class_exists('VMO_Plan_Policy') ? VMO_Plan_Policy::get_plan($required) : null;
                if ($plan_info) {
                    $map[$feature]['plan_name']  = $plan_info['name'];
                    $map[$feature]['plan_price'] = $plan_info['price'];
                }
            }
        }
        return $map;
    }

    /**
     * Return the ordered list of plan tier names (for UI rendering).
     *
     * @return array  e.g. ['free','tester','starter','pro','elite','enterprise']
     */
    public static function get_tier_order() {
        return array_keys(self::$tiers);
    }

    /* ═══════════════════════════════════════════
     *  AJAX Handler
     * ═══════════════════════════════════════════ */

    public static function register_ajax() {
        add_action('wp_ajax_vmo_check_feature_access', [__CLASS__, 'ajax_check_access']);
    }

    public static function ajax_check_access() {
        check_ajax_referer('vmo_nonce', 'nonce');
        $feature = sanitize_text_field(wp_unslash($_POST['feature'] ?? ''));
        if (!$feature) wp_send_json_error('Missing feature');

        if (self::can_access($feature)) {
            wp_send_json_success(['allowed' => true, 'feature' => $feature]);
        } else {
            $prompt = self::get_upgrade_prompt($feature);
            wp_send_json_success(['allowed' => false, 'upgrade' => $prompt]);
        }
    }

    /* ═══════════════════════════════════════════
     *  Internals
     * ═══════════════════════════════════════════ */

    private static function get_current_plan() {
        $uid = get_current_user_id();
        if ($uid <= 0) return 'free';
        $raw = get_user_meta($uid, 'vmo_subscription_status', true);
        return self::normalize($raw ?: 'free');
    }

    private static function normalize($plan) {
        if (function_exists('vmo_normalize_plan_key')) {
            return vmo_normalize_plan_key($plan);
        }
        return strtolower(trim((string) $plan)) ?: 'free';
    }
}

/* ── Global helper function ─── */
if (!function_exists('vmo_can_access')) {
    /**
     * Check if the current user's plan allows access to a feature.
     *
     * @param string $feature Feature slug.
     * @return bool
     */
    function vmo_can_access($feature) {
        return VMO_Feature_Gate::can_access($feature);
    }
}

if (!function_exists('vmo_require_plan')) {
    /**
     * Return the minimum plan name required for a feature.
     *
     * @param string $feature Feature slug.
     * @return string
     */
    function vmo_require_plan($feature) {
        return VMO_Feature_Gate::required_plan($feature);
    }
}
