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

class VMO_Stripe_Connect {
    public function __construct() {
        if (did_action('rest_api_init')) {
            $this->register_routes();
            return;
        }

        add_action('rest_api_init', [$this, 'register_routes']);
    }

    public function register_routes() {
        register_rest_route('vmo-builder/v1', '/stripe/connect/onboard', [
            'methods' => 'POST',
            'callback' => [$this, 'create_onboarding_link'],
            'permission_callback' => function() { return is_user_logged_in(); }
        ]);

        register_rest_route('vmo-builder/v1', '/stripe/connect/checkout', [
            'methods' => 'POST',
            'callback' => [$this, 'create_checkout_for_product'],
            'permission_callback' => '__return_true' // Public checkout endpoint — customers purchase from storefront without WP login; product validated in callback
        ]);

        // Automatic account provisioning with KYC payload collected by AI consultant
        register_rest_route('vmo-builder/v1', '/stripe/connect/provision', [
            'methods' => 'POST',
            'callback' => [$this, 'provision_connected_account'],
            'permission_callback' => function(){ return is_user_logged_in(); }
        ]);

        // Check Stripe account onboarding status
        register_rest_route('vmo-builder/v1', '/stripe/check-status', [
            'methods' => 'GET',
            'callback' => [$this, 'check_account_status'],
            'permission_callback' => function(){ return is_user_logged_in(); }
        ]);

        // Catalog endpoints (AI will upsert products after consultation)
        register_rest_route('vmo-builder/v1', '/store/products', [
            'methods' => 'POST',
            'callback' => [$this, 'upsert_products'],
            'permission_callback' => function(){ return is_user_logged_in(); }
        ]);
        register_rest_route('vmo-builder/v1', '/store/products', [
            'methods' => 'GET',
            'callback' => [$this, 'list_products'],
            'permission_callback' => function(){ return is_user_logged_in(); }
        ]);

        register_rest_route('vmo-builder/v1', '/stripe/connect/orders', [
            'methods' => 'GET',
            'callback' => [$this, 'list_orders'],
            'permission_callback' => function() {
                // Allow admins or the merchant themselves
                if (current_user_can('manage_options')) return true;
                $uid = get_current_user_id();
                return $uid > 0; // Will filter in callback to only their orders
            }
        ]);

        // Subscriptions list
        register_rest_route('vmo-builder/v1', '/store/subscriptions', [
            'methods' => 'GET',
            'callback' => [$this, 'list_subscriptions'],
            'permission_callback' => function() { return is_user_logged_in(); }
        ]);

        // Payments report for dashboard
        register_rest_route('vmo-builder/v1', '/payments/report', [
            'methods' => 'GET',
            'callback' => [$this, 'payments_report'],
            'permission_callback' => function(){ return is_user_logged_in(); }
        ]);

        // Payments advisory config (tax rules, fee model) and estimator
        register_rest_route('vmo-builder/v1', '/payments/config', [
            'methods' => 'GET',
            'callback' => [$this, 'get_payments_config'],
            'permission_callback' => function(){ return is_user_logged_in(); }
        ]);
        register_rest_route('vmo-builder/v1', '/payments/config', [
            'methods' => 'POST',
            'callback' => [$this, 'set_payments_config'],
            'permission_callback' => function(){ return is_user_logged_in(); }
        ]);
        register_rest_route('vmo-builder/v1', '/payments/estimate', [
            'methods' => 'POST',
            'callback' => [$this, 'estimate_pricing'],
            'permission_callback' => function(){ return is_user_logged_in(); }
        ]);

        // 🔔 STRIPE WEBHOOK: Automated transaction handling
        // Handles: receipts, invoices, customer auto-creation, subscriptions
        register_rest_route('vmo-builder/v1', '/stripe/webhook', [
            'methods' => 'POST',
            'callback' => [$this, 'handle_stripe_webhook'],
            'permission_callback' => '__return_true' // Public Stripe webhook — validated via \Stripe\Webhook::constructEvent() signature check in callback
        ]);
    }

    private function payments_enabled() {
        return defined('VMO_PAYMENTS_ENABLED') ? (bool) VMO_PAYMENTS_ENABLED : true;
    }

    private function init_stripe() {
        require_once VMO_AI_BUILDER_DIR . 'stripe-sdk/init.php';
        $sk = get_option('vmo_stripe_secret_key');
        if (!$sk) {
            return new WP_Error('stripe_config', 'Stripe secret key missing');
        }
        \Stripe\Stripe::setApiKey($sk);
        return true;
    }

    private function ensure_connected_account_cfo_columns() {
        global $wpdb;
        $table = $wpdb->prefix . 'vmo_connected_accounts';
        if ($wpdb->get_var("SHOW TABLES LIKE '{$table}'") !== $table) {
            return;
        }
        $columns = $wpdb->get_col("SHOW COLUMNS FROM {$table}", 0);
        if (is_array($columns) && !in_array('requirements_due', $columns, true)) {
            $wpdb->query("ALTER TABLE {$table} ADD COLUMN requirements_due LONGTEXT NULL AFTER capabilities");
        }
        if (is_array($columns) && !in_array('last_synced', $columns, true)) {
            $wpdb->query("ALTER TABLE {$table} ADD COLUMN last_synced DATETIME DEFAULT NULL AFTER requirements_due");
        }
    }

    public function create_onboarding_link(WP_REST_Request $req) {
        if (!$this->payments_enabled()) return new WP_Error('payments_disabled', 'Payments disabled');
        $ok = $this->init_stripe();
        if (is_wp_error($ok)) return $ok;

        $user_id = get_current_user_id();
        $account_id = $this->get_or_create_connected_account($user_id);
        if (is_wp_error($account_id)) return $account_id;

        try {
            $link = \Stripe\AccountLink::create([
                'account' => $account_id,
                'refresh_url' => esc_url_raw(add_query_arg('stripe_onboard', 'refresh', admin_url('admin.php?page=vmo-ai-dashboard'))),
                'return_url'  => esc_url_raw(add_query_arg('stripe_onboard', 'return', admin_url('admin.php?page=vmo-ai-dashboard'))),
                'type' => 'account_onboarding',
            ]);
            return new WP_REST_Response(['url' => $link->url], 200);
        } catch (Exception $e) {
            return new WP_Error('stripe_error', $e->getMessage());
        }
    }

    private function get_or_create_connected_account($user_id) {
        global $wpdb; $table = $wpdb->prefix . 'vmo_connected_accounts';
        $this->ensure_connected_account_cfo_columns();
        $existing = $wpdb->get_var($wpdb->prepare("SELECT stripe_account_id FROM $table WHERE user_id = %d", $user_id));
        if ($existing) return $existing;

        try {
            $acct = \Stripe\Account::create([
                'type' => 'express', // Changed to Express for guided onboarding
                'capabilities' => [
                    'card_payments' => ['requested' => true],
                    'transfers' => ['requested' => true]
                ],
                'business_type' => 'individual'
            ]);
        } catch (Exception $e) {
            return new WP_Error('stripe_error', $e->getMessage());
        }

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->insert($table, [
            'user_id' => $user_id,
            'stripe_account_id' => $acct->id,
            'account_type' => 'express',
            'details_submitted' => intval($acct->details_submitted),
            'payouts_enabled' => intval($acct->payouts_enabled),
            'charges_enabled' => intval($acct->charges_enabled),
            'capabilities' => wp_json_encode($acct->capabilities),
            'requirements_due' => wp_json_encode($acct->requirements->currently_due ?? []),
            'last_synced' => current_time('mysql')
        ]);
        return $acct->id;
    }

    public function provision_connected_account(WP_REST_Request $req) {
        if (!$this->payments_enabled()) return new WP_Error('payments_disabled', 'Payments disabled');
        $ok = $this->init_stripe(); if (is_wp_error($ok)) return $ok;

        $uid = get_current_user_id();
        $existing = $this->get_account_id_for_user($uid);
        if ($existing) {
            // Check if onboarding is complete
            $account = \Stripe\Account::retrieve($existing);
            if ($account->details_submitted) {
                return new WP_REST_Response(['account_id' => $existing, 'status' => 'complete'], 200);
            } else {
                // Generate new onboarding link (for Express accounts)
                if ($account->type === 'express') {
                    $link = \Stripe\AccountLink::create([
                        'account' => $existing,
                        'refresh_url' => home_url('/?vmo_stripe_refresh=1&account_id=' . $existing),
                        'return_url' => home_url('/?vmo_stripe_return=1&account_id=' . $existing),
                        'type' => 'account_onboarding'
                    ]);
                    return new WP_REST_Response([
                        'account_id' => $existing, 
                        'status' => 'pending',
                        'account_type' => 'express',
                        'onboarding_url' => $link->url
                    ], 200);
                } else {
                    // Custom account - already created, just return
                    return new WP_REST_Response([
                        'account_id' => $existing, 
                        'status' => 'pending',
                        'account_type' => 'custom'
                    ], 200);
                }
            }
        }

        $p = $req->get_json_params() ?: [];
        // Minimal fields; add more as required by Stripe onboarding
        $business_type = in_array(($p['business_type'] ?? 'individual'), ['individual','company']) ? $p['business_type'] : 'individual';
        $email = sanitize_email($p['email'] ?? (wp_get_current_user()->user_email ?? ''));
        $country = strtoupper(sanitize_text_field($p['country'] ?? 'US'));
        $business_name = sanitize_text_field($p['business_name'] ?? '');

        // Check account strategy setting
        $strategy = get_option('vmo_stripe_account_strategy', 'express_only');
        $account_type = 'express'; // Default to Express
        
        // TODO: If hybrid mode enabled, implement risk assessment here
        // For now, always use Express (safe mode)
        if ($strategy === 'hybrid') {
            // Future: Add risk assessment logic
            // $risk_score = $this->calculate_risk_score($p);
            // $threshold = get_option('vmo_custom_account_threshold', 90);
            // $account_type = ($risk_score >= $threshold) ? 'custom' : 'express';
            
            // For now, log that hybrid is enabled but not implemented
            error_log('VMO: Hybrid mode enabled but risk assessment not implemented yet. Using Express.');
        }

        try {
            // Create Express account with pre-filled data
            $acct = \Stripe\Account::create([
                'type' => $account_type, // Express (current) or Custom (future)
                'country' => $country,
                'email' => $email,
                'business_type' => $business_type,
                'capabilities' => [
                    'card_payments' => ['requested' => true],
                    'transfers' => ['requested' => true]
                ],
                'business_profile' => [
                    'name' => $business_name,
                    'product_description' => sanitize_text_field($p['product_description'] ?? 'Online store via VMO')
                ],
                'company' => ($business_type === 'company') ? [
                    'name' => sanitize_text_field($p['company_name'] ?? ''),
                    'tax_id' => sanitize_text_field($p['tax_id'] ?? '')
                ] : null,
                'individual' => ($business_type === 'individual') ? [
                    'first_name' => sanitize_text_field($p['first_name'] ?? ''),
                    'last_name'  => sanitize_text_field($p['last_name'] ?? ''),
                    'email'      => $email
                ] : null
            ]);
        } catch (Exception $e) {
            return new WP_Error('stripe_error', $e->getMessage());
        }

        global $wpdb; $table = $wpdb->prefix . 'vmo_connected_accounts';
        $this->ensure_connected_account_cfo_columns();
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->insert($table, [
            'user_id' => $uid,
            'stripe_account_id' => $acct->id,
            'account_type' => $account_type,
            'details_submitted' => intval($acct->details_submitted),
            'payouts_enabled' => intval($acct->payouts_enabled),
            'charges_enabled' => intval($acct->charges_enabled),
            'capabilities' => wp_json_encode($acct->capabilities),
            'requirements_due' => wp_json_encode($acct->requirements->currently_due ?? []),
            'last_synced' => current_time('mysql')
        ]);

        // Create guided onboarding link (for Express accounts only)
        if ($account_type === 'express') {
            try {
                $link = \Stripe\AccountLink::create([
                    'account' => $acct->id,
                    'refresh_url' => home_url('/?vmo_stripe_refresh=1&account_id=' . $acct->id),
                    'return_url' => home_url('/?vmo_stripe_return=1&account_id=' . $acct->id),
                    'type' => 'account_onboarding'
                ]);
                
                return new WP_REST_Response([
                    'account_id' => $acct->id, 
                    'account_type' => 'express',
                    'status' => 'created',
                    'onboarding_url' => $link->url
                ], 200);
            } catch (Exception $e) {
                return new WP_REST_Response([
                    'account_id' => $acct->id, 
                    'account_type' => 'express',
                    'status' => 'created',
                    'error' => 'Could not create onboarding link: ' . $e->getMessage()
                ], 200);
            }
        } else {
            // Custom account - no onboarding link needed (seamless)
            return new WP_REST_Response([
                'account_id' => $acct->id, 
                'account_type' => 'custom',
                'status' => 'created',
                'message' => 'Custom account created - ready to use immediately'
            ], 200);
        }
    }

    // Check if user's Stripe account onboarding is complete
    public function check_account_status(WP_REST_Request $req) {
        if (!$this->payments_enabled()) return new WP_Error('payments_disabled', 'Payments disabled');
        $ok = $this->init_stripe();
        if (is_wp_error($ok)) return $ok;

        $uid = get_current_user_id();
        $account_id = $this->get_account_id_for_user($uid);
        
        if (!$account_id) {
            return new WP_REST_Response(['status' => 'not_created'], 200);
        }

        try {
            $account = \Stripe\Account::retrieve($account_id);
            
            // Update database with current status
            global $wpdb;
            $this->ensure_connected_account_cfo_columns();
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->update(
                $wpdb->prefix . 'vmo_connected_accounts',
                [
                    'details_submitted' => intval($account->details_submitted),
                    'charges_enabled' => intval($account->charges_enabled),
                    'payouts_enabled' => intval($account->payouts_enabled),
                    'requirements_due' => wp_json_encode($account->requirements->currently_due ?? []),
                    'last_synced' => current_time('mysql')
                ],
                ['stripe_account_id' => $account_id]
            );
            
            return new WP_REST_Response([
                'status' => 'found',
                'account_id' => $account_id,
                'details_submitted' => $account->details_submitted,
                'charges_enabled' => $account->charges_enabled,
                'payouts_enabled' => $account->payouts_enabled,
                'completed' => $account->details_submitted && $account->charges_enabled
            ], 200);
        } catch (Exception $e) {
            return new WP_Error('stripe_error', $e->getMessage());
        }
    }

    // Upsert product catalog for merchant (inventory, subscriptions, downloadable, shipping)
    public function upsert_products(WP_REST_Request $req) {
        if (!$this->payments_enabled()) return new WP_Error('payments_disabled', 'Payments disabled');
        $uid = get_current_user_id();
        $payload = $req->get_json_params();
        $list = is_array($payload['products'] ?? null) ? $payload['products'] : [];
        if (!$list) return new WP_Error('bad_request', 'No products provided');
        global $wpdb; $table = $wpdb->prefix . 'vmo_store_products';
        $results = [];
        foreach ($list as $p) {
            $name = sanitize_text_field($p['name'] ?? '');
            if (!$name) continue;
            $slug = sanitize_title($p['slug'] ?? $name);
            $desc = wp_kses_post($p['description'] ?? '');
            $type = in_array($p['product_type'] ?? 'item', ['item','subscription','downloadable','service']) ? $p['product_type'] : 'item';
            $price_cents = intval($p['price_cents'] ?? 0);
            $currency = strtolower(sanitize_text_field($p['currency'] ?? 'usd'));
            $sku = sanitize_text_field($p['sku'] ?? '');
            $stock_tracking = !empty($p['stock_tracking']) ? 1 : 0;
            $stock_qty = intval($p['stock_qty'] ?? 0);
            $shipping_required = !empty($p['shipping_required']) ? 1 : 0;
            $shipping_profile = isset($p['shipping_profile']) ? wp_json_encode($p['shipping_profile']) : null;
            $download_url = isset($p['download_url']) ? esc_url_raw($p['download_url']) : null;
            $download_limit = isset($p['download_limit']) ? intval($p['download_limit']) : null;
            $interval = in_array($p['recurring_interval'] ?? null, ['day','week','month','year']) ? $p['recurring_interval'] : null;
            $interval_count = isset($p['recurring_interval_count']) ? max(1, intval($p['recurring_interval_count'])) : null;
            $images = isset($p['images']) && is_array($p['images']) ? wp_json_encode(array_values(array_map('esc_url_raw', $p['images']))) : null;

            $exists = $wpdb->get_var($wpdb->prepare("SELECT id FROM $table WHERE user_id=%d AND slug=%s", $uid, $slug));
            if ($exists) {
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                $wpdb->update($table, [
                    'name'=>$name,'description'=>$desc,'product_type'=>$type,'price_cents'=>$price_cents,'currency'=>$currency,
                    'sku'=>$sku,'stock_tracking'=>$stock_tracking,'stock_qty'=>$stock_qty,'shipping_required'=>$shipping_required,
                    'shipping_profile'=>$shipping_profile,'download_url'=>$download_url,'download_limit'=>$download_limit,
                    'recurring_interval'=>$interval,'recurring_interval_count'=>$interval_count,'images'=>$images
                ], [ 'id'=>$exists ]);
                $results[] = [ 'id'=>$exists, 'slug'=>$slug, 'updated'=>true ];
            } else {
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                $wpdb->insert($table, [
                    'user_id'=>$uid,'name'=>$name,'slug'=>$slug,'description'=>$desc,'product_type'=>$type,
                    'price_cents'=>$price_cents,'currency'=>$currency,'sku'=>$sku,'stock_tracking'=>$stock_tracking,
                    'stock_qty'=>$stock_qty,'shipping_required'=>$shipping_required,'shipping_profile'=>$shipping_profile,
                    'download_url'=>$download_url,'download_limit'=>$download_limit,'recurring_interval'=>$interval,
                    'recurring_interval_count'=>$interval_count,'images'=>$images
                ]);
                $results[] = [ 'id'=>$wpdb->insert_id, 'slug'=>$slug, 'created'=>true ];
            }
        }
        return new WP_REST_Response(['success'=>true,'products'=>$results], 200);
    }

    public function list_products(WP_REST_Request $req) {
        $uid = get_current_user_id();
        global $wpdb; $table = $wpdb->prefix . 'vmo_store_products';
        $rows = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table WHERE user_id=%d ORDER BY created_at DESC", $uid), ARRAY_A);
        return new WP_REST_Response(['success'=>true,'products'=>$rows?:[]], 200);
    }

    public function create_checkout_for_product(WP_REST_Request $req) {
        if (!$this->payments_enabled()) return new WP_Error('payments_disabled', 'Payments disabled');
        $ok = $this->init_stripe();
        if (is_wp_error($ok)) return $ok;

        $params = $req->get_json_params();
        $product_id = intval($params['product_id'] ?? 0);
        $quantity = max(1, intval($params['quantity'] ?? 1));
        $success_url = esc_url_raw($params['success_url'] ?? home_url('/?checkout=success'));
        $cancel_url = esc_url_raw($params['cancel_url'] ?? home_url('/?checkout=cancel'));
        $metadata = is_array($params['metadata'] ?? null) ? $params['metadata'] : [];

        $name = '';
        $desc = '';
        $amount_cents = 0;
        $currency = 'usd';
        $merchant_user_id = 0;
        $product_slug = '';
        $product_type = 'item';
        $stock_tracking = 0;
        $stock_qty = 0;

        global $wpdb; $products_table = $wpdb->prefix . 'vmo_store_products';

        if ($product_id > 0) {
            // Strict: derive all sale parameters from server DB
            $row = $wpdb->get_row($wpdb->prepare("SELECT * FROM $products_table WHERE id = %d AND status = 'active'", $product_id), ARRAY_A);
            if (!$row) return new WP_Error('not_found', 'Product not found');

            $merchant_user_id = intval($row['user_id']);
            $name = sanitize_text_field($row['name']);
            $desc = wp_kses_post($row['description']);
            $amount_cents = intval($row['price_cents']);
            $currency = strtolower(sanitize_text_field($row['currency'] ?: 'usd'));
            $product_slug = sanitize_title($row['slug'] ?: $row['name']);
            $product_type = sanitize_text_field($row['product_type'] ?: 'item');
            $stock_tracking = intval($row['stock_tracking']);
            $stock_qty = intval($row['stock_qty']);

            if ($amount_cents <= 0) return new WP_Error('bad_product', 'Invalid product price');
            if (!preg_match('/^[a-z]{3}$/', $currency)) $currency = 'usd';

            if ($stock_tracking && $stock_qty <= 0) {
                return new WP_Error('out_of_stock', 'Product is out of stock');
            }

            // If subscription, we will switch Checkout mode later
        } else {
            // Legacy path: only allow privileged server-side usage (never public)
            if (!(is_user_logged_in() && current_user_can('manage_options'))) {
                return new WP_Error('bad_request', 'Missing product_id');
            }
            $merchant_user_id = intval($params['merchant_user_id'] ?? 0);
            $name = sanitize_text_field($params['name'] ?? 'Product');
            $desc = sanitize_textarea_field($params['description'] ?? '');
            $amount_cents = intval($params['amount_cents'] ?? 0);
            $currency = strtolower(sanitize_text_field($params['currency'] ?? 'usd'));
            if ($merchant_user_id <= 0 || $amount_cents <= 0) {
                return new WP_Error('bad_request', 'Missing merchant or amount');
            }
            if (!preg_match('/^[a-z]{3}$/', $currency)) $currency = 'usd';
        }

        // Very light rate limiting per IP (transient; 60 req/min)
        $ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
        $key = 'vmo_chk_' . md5($ip);
        $window = 60; // seconds
        $maxReq = 60; // simple ceiling
        $rec = get_transient($key);
        if (!$rec) {
            set_transient($key, ['c'=>1,'t'=>time()], $window);
        } else {
            $c = intval($rec['c'] ?? 0) + 1;
            if ($c > $maxReq) return new WP_Error('rate_limited', 'Too many requests');
            set_transient($key, ['c'=>$c,'t'=>($rec['t'] ?? time())], $window);
        }

        // Validate success/cancel URLs are same-origin
        $origin = parse_url(home_url('/'), PHP_URL_HOST);
        $sHost = parse_url($success_url, PHP_URL_HOST);
        $cHost = parse_url($cancel_url, PHP_URL_HOST);
        if (!$sHost || !$cHost || $sHost !== $origin || $cHost !== $origin) {
            $success_url = home_url('/?checkout=success');
            $cancel_url  = home_url('/?checkout=cancel');
        }

        $account_id = $this->get_account_id_for_user($merchant_user_id);
        if (!$account_id) return new WP_Error('missing_account', 'Merchant not onboarded');

        // Platform fee guardrails
        $platform_fee_bps = intval(get_option('vmo_stripe_platform_fee_bps', 50));
        if ($platform_fee_bps < 0) $platform_fee_bps = 0;
        if ($platform_fee_bps > 1000) $platform_fee_bps = 1000; // cap at 10%
    $platform_fee_amount = intval(round($amount_cents * $quantity * ($platform_fee_bps / 10000)));

    try {
            // Optional idempotency: accept client-provided key to make retries safe
            $idem_key = isset($params['idempotency_key']) ? sanitize_text_field($params['idempotency_key']) : '';
            $stripe_opts = [];
            if ($idem_key && strlen($idem_key) <= 255) {
                $stripe_opts['idempotency_key'] = 'vmo_chk_' . $idem_key;
            }
            if ($product_type === 'subscription') {
                // Convert bps to percent for application_fee_percent
                $app_fee_percent = min(100, max(0, $platform_fee_bps / 100));
                $session = \Stripe\Checkout\Session::create([
                    'mode' => 'subscription',
                    'line_items' => [[
                        'price_data' => [
                            'currency' => $currency,
                            'recurring' => [ 'interval' => $row['recurring_interval'] ?: 'month', 'interval_count' => max(1, (int)($row['recurring_interval_count'] ?: 1)) ],
                            'unit_amount' => $amount_cents,
                            'product_data' => [ 'name' => $name, 'description' => $desc ]
                        ],
                        'quantity' => $quantity
                    ]],
                    'billing_address_collection' => 'required',
                    'success_url' => $success_url . '&session_id={CHECKOUT_SESSION_ID}',
                    'cancel_url'  => $cancel_url,
                    'subscription_data' => [
                        'transfer_data' => [ 'destination' => $account_id ],
                        'application_fee_percent' => $app_fee_percent,
                        'metadata' => array_filter([
                            'merchant_user_id' => $merchant_user_id,
                            'platform_fee_bps' => $platform_fee_bps,
                            'product_id' => $product_id ?: null,
                            'product_name' => $name,
                            'recurring_interval' => $row['recurring_interval'] ?: null,
                            'recurring_interval_count' => $row['recurring_interval_count'] ?: null
                        ])
                    ],
                    'automatic_tax' => [ 'enabled' => false ],
                    'metadata' => array_merge($metadata, array_filter([
                        'merchant_user_id' => $merchant_user_id,
                        'platform_fee_bps' => $platform_fee_bps,
                        'product_name' => $name,
                        'product_slug' => $product_slug ?: null,
                        'product_id' => $product_id ?: null,
                        'product_type' => 'subscription',
                        'recurring_interval' => $row['recurring_interval'] ?: null,
                        'recurring_interval_count' => $row['recurring_interval_count'] ?: null,
                        'amount_cents' => $amount_cents,
                        'currency' => $currency,
                        'quantity' => $quantity
                    ]))
                ], $stripe_opts);
            } else {
                $session = \Stripe\Checkout\Session::create([
                    'mode' => 'payment',
                    'line_items' => [[
                        'price_data' => [
                            'currency' => $currency,
                            'unit_amount' => $amount_cents,
                            'product_data' => [ 'name' => $name, 'description' => $desc ]
                        ],
                        'quantity' => $quantity
                    ]],
                    'billing_address_collection' => 'required',
                    'success_url' => $success_url . '&session_id={CHECKOUT_SESSION_ID}',
                    'cancel_url'  => $cancel_url,
                    'payment_intent_data' => [
                        'application_fee_amount' => $platform_fee_amount,
                        'transfer_data' => [ 'destination' => $account_id ],
                        'on_behalf_of' => $account_id
                    ],
                    'automatic_tax' => [ 'enabled' => false ],
                    'metadata' => array_merge($metadata, array_filter([
                        'merchant_user_id' => $merchant_user_id,
                        'platform_fee_bps' => $platform_fee_bps,
                        'product_name' => $name,
                        'product_slug' => $product_slug ?: null,
                        'product_id' => $product_id ?: null,
                        'product_type' => $product_type,
                        'amount_cents' => $amount_cents,
                        'currency' => $currency,
                        'quantity' => $quantity
                    ]))
                ], $stripe_opts);
            }
        } catch (Exception $e) {
            return new WP_Error('stripe_error', $e->getMessage());
        }

        // Persist order locally (using derived values)
        global $wpdb; $orders = $wpdb->prefix . 'vmo_store_orders';
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $wpdb->insert($orders, [
            'user_id' => $merchant_user_id,
            'buyer_user_id' => is_user_logged_in() ? get_current_user_id() : null,
            'stripe_checkout_session_id' => $session->id,
            'amount_total' => $amount_cents * $quantity,
            'currency' => $currency,
            'platform_fee_amount' => $platform_fee_amount,
            'status' => 'created',
            'metadata' => wp_json_encode(array_filter(array_merge($metadata, [
                'product_name' => $name,
                'product_slug' => $product_slug ?: null,
        'product_id' => $product_id ?: null,
        'product_type' => $product_type,
                'quantity' => $quantity
            ])))
        ]);

        return new WP_REST_Response(['url' => $session->url, 'id' => $session->id], 200);
    }

    public function create_checkout_for_products(WP_REST_Request $req) {
        if (!$this->payments_enabled()) return new WP_Error('payments_disabled', 'Payments disabled');
        $ok = $this->init_stripe();
        if (is_wp_error($ok)) return $ok;

        $params = $req->get_json_params();
        if (!is_array($params)) $params = [];

        $product_ids = $params['product_ids'] ?? [];
        if (is_string($product_ids)) {
            $decoded = json_decode($product_ids, true);
            $product_ids = is_array($decoded) ? $decoded : preg_split('/\s*,\s*/', $product_ids);
        }
        $product_ids = array_values(array_unique(array_filter(array_map('intval', (array) $product_ids))));
        if (count($product_ids) < 2) {
            return new WP_Error('bad_request', 'Select at least two active products');
        }

        $quantities = is_array($params['quantities'] ?? null) ? $params['quantities'] : [];
        $success_url = esc_url_raw($params['success_url'] ?? home_url('/?checkout=success'));
        $cancel_url = esc_url_raw($params['cancel_url'] ?? home_url('/?checkout=cancel'));
        $metadata = is_array($params['metadata'] ?? null) ? $params['metadata'] : [];

        $origin = parse_url(home_url('/'), PHP_URL_HOST);
        $sHost = parse_url($success_url, PHP_URL_HOST);
        $cHost = parse_url($cancel_url, PHP_URL_HOST);
        if (!$sHost || !$cHost || $sHost !== $origin || $cHost !== $origin) {
            $success_url = home_url('/?checkout=success');
            $cancel_url  = home_url('/?checkout=cancel');
        }

        global $wpdb;
        $products_table = $wpdb->prefix . 'vmo_store_products';
        $placeholders = implode(',', array_fill(0, count($product_ids), '%d'));
        $rows = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$products_table} WHERE id IN ({$placeholders}) AND status = 'active' AND price_cents > 0",
            $product_ids
        ), ARRAY_A);

        if (count($rows ?: []) !== count($product_ids)) {
            return new WP_Error('not_found', 'One or more products are unavailable');
        }

        $rows_by_id = [];
        foreach ($rows as $row) {
            $rows_by_id[intval($row['id'])] = $row;
        }

        $merchant_user_id = 0;
        $currency = '';
        $line_items = [];
        $line_item_meta = [];
        $amount_total = 0;
        $current_user_id = get_current_user_id();

        foreach ($product_ids as $pid) {
            $row = $rows_by_id[$pid] ?? null;
            if (!$row) return new WP_Error('not_found', 'Product not found');

            $row_merchant_id = intval($row['user_id']);
            if (!$merchant_user_id) $merchant_user_id = $row_merchant_id;
            if ($merchant_user_id !== $row_merchant_id) {
                return new WP_Error('mixed_merchants', 'Multi-product checkout can only include products from one VMO store');
            }
            if ($current_user_id && !current_user_can('manage_options') && $current_user_id !== $row_merchant_id) {
                return new WP_Error('forbidden', 'You can only create checkout links for your own store products');
            }

            $product_type = sanitize_text_field($row['product_type'] ?: 'item');
            if ($product_type === 'subscription') {
                return new WP_Error('subscription_multi_checkout', 'Subscription products need their own checkout link');
            }

            $row_currency = strtolower(sanitize_text_field($row['currency'] ?: 'usd'));
            if (!preg_match('/^[a-z]{3}$/', $row_currency)) $row_currency = 'usd';
            if (!$currency) $currency = $row_currency;
            if ($currency !== $row_currency) {
                return new WP_Error('mixed_currencies', 'Multi-product checkout requires all products to use the same currency');
            }

            $quantity = max(1, intval($quantities[$pid] ?? $quantities[(string) $pid] ?? 1));
            $stock_tracking = intval($row['stock_tracking']);
            $stock_qty = intval($row['stock_qty']);
            if ($stock_tracking && $stock_qty < $quantity) {
                return new WP_Error('out_of_stock', sanitize_text_field($row['name']) . ' does not have enough stock');
            }

            $amount_cents = intval($row['price_cents']);
            $amount_total += $amount_cents * $quantity;
            $description = wp_strip_all_tags((string) $row['description']);

            $line_items[] = [
                'price_data' => [
                    'currency' => $currency,
                    'unit_amount' => $amount_cents,
                    'product_data' => [
                        'name' => sanitize_text_field($row['name']),
                        'description' => substr($description, 0, 900),
                    ],
                ],
                'quantity' => $quantity,
            ];
            $line_item_meta[] = [
                'product_id' => $pid,
                'name' => sanitize_text_field($row['name']),
                'slug' => sanitize_title($row['slug'] ?: $row['name']),
                'quantity' => $quantity,
                'amount_cents' => $amount_cents,
            ];
        }

        if ($amount_total <= 0) {
            return new WP_Error('bad_product', 'Invalid checkout total');
        }

        $account_id = $this->get_account_id_for_user($merchant_user_id);
        if (!$account_id) return new WP_Error('missing_account', 'Merchant not onboarded');

        $platform_fee_bps = intval(get_option('vmo_stripe_platform_fee_bps', 50));
        if ($platform_fee_bps < 0) $platform_fee_bps = 0;
        if ($platform_fee_bps > 1000) $platform_fee_bps = 1000;
        $platform_fee_amount = intval(round($amount_total * ($platform_fee_bps / 10000)));

        try {
            $session = \Stripe\Checkout\Session::create([
                'mode' => 'payment',
                'line_items' => $line_items,
                'billing_address_collection' => 'required',
                'success_url' => $success_url . '&session_id={CHECKOUT_SESSION_ID}',
                'cancel_url'  => $cancel_url,
                'payment_intent_data' => [
                    'application_fee_amount' => $platform_fee_amount,
                    'transfer_data' => [ 'destination' => $account_id ],
                    'on_behalf_of' => $account_id,
                ],
                'automatic_tax' => [ 'enabled' => false ],
                'metadata' => array_merge($metadata, [
                    'merchant_user_id' => (string) $merchant_user_id,
                    'platform_fee_bps' => (string) $platform_fee_bps,
                    'checkout_type' => 'multi_product',
                    'product_ids' => implode(',', $product_ids),
                    'amount_cents' => (string) $amount_total,
                    'currency' => $currency,
                ]),
            ]);
        } catch (Exception $e) {
            return new WP_Error('stripe_error', $e->getMessage());
        }

        $orders = $wpdb->prefix . 'vmo_store_orders';
        $wpdb->insert($orders, [
            'user_id' => $merchant_user_id,
            'buyer_user_id' => is_user_logged_in() ? get_current_user_id() : null,
            'stripe_checkout_session_id' => $session->id,
            'amount_total' => $amount_total,
            'currency' => $currency,
            'platform_fee_amount' => $platform_fee_amount,
            'status' => 'created',
            'metadata' => wp_json_encode(array_merge($metadata, [
                'checkout_type' => 'multi_product',
                'product_ids' => $product_ids,
                'line_items' => $line_item_meta,
            ])),
        ]);

        return new WP_REST_Response(['url' => $session->url, 'id' => $session->id], 200);
    }

    private function get_account_id_for_user($user_id) {
        global $wpdb; $table = $wpdb->prefix . 'vmo_connected_accounts';
        return $wpdb->get_var($wpdb->prepare("SELECT stripe_account_id FROM $table WHERE user_id = %d", $user_id));
    }

    public function list_orders(WP_REST_Request $req) {
        if (!$this->payments_enabled()) return new WP_Error('payments_disabled', 'Payments disabled');
        global $wpdb; $orders = $wpdb->prefix . 'vmo_store_orders';
        $merchant_user_id = intval($req->get_param('user_id') ?: get_current_user_id());
        // Non-admins can only view their own
        if (!current_user_can('manage_options') && $merchant_user_id !== get_current_user_id()) {
            return new WP_Error('forbidden', 'Not authorized', ['status' => 403]);
        }
        $rows = $wpdb->get_results($wpdb->prepare("SELECT * FROM $orders WHERE user_id = %d ORDER BY created_at DESC LIMIT 200", $merchant_user_id), ARRAY_A);
        return new WP_REST_Response(['orders' => $rows ?: []], 200);
    }

    public function list_subscriptions(WP_REST_Request $req) {
        if (!$this->payments_enabled()) return new WP_Error('payments_disabled', 'Payments disabled');
        global $wpdb; 
        $subs = $wpdb->prefix . 'vmo_store_subscriptions';
        $products = $wpdb->prefix . 'vmo_store_products';
        $merchant_user_id = intval($req->get_param('user_id') ?: get_current_user_id());
        if (!current_user_can('manage_options') && $merchant_user_id !== get_current_user_id()) {
            return new WP_Error('forbidden', 'Not authorized', ['status' => 403]);
        }
        $rows = $wpdb->get_results($wpdb->prepare(
            "SELECT s.*, p.name AS product_name FROM $subs s LEFT JOIN $products p ON p.id = s.product_id WHERE s.user_id = %d ORDER BY s.created_at DESC LIMIT 200",
            $merchant_user_id
        ), ARRAY_A);
        return new WP_REST_Response(['success'=>true, 'subscriptions' => $rows ?: []], 200);
    }

    public function payments_report(WP_REST_Request $req) {
        if (!$this->payments_enabled()) return new WP_Error('payments_disabled', 'Payments disabled');
        global $wpdb; $orders = $wpdb->prefix . 'vmo_store_orders';
        $uid = get_current_user_id();
    $rows = $wpdb->get_results($wpdb->prepare("SELECT * FROM $orders WHERE user_id = %d AND status = 'paid' ORDER BY created_at DESC LIMIT 500", $uid), ARRAY_A);
        $fulfillment_breakdown = function_exists('vmo_business_flow_revenue_summary')
            ? vmo_business_flow_revenue_summary($uid, 365)
            : array('paid_revenue' => 0, 'pending_fulfillment_revenue' => 0, 'completed_fulfilled_revenue' => 0, 'refunds' => 0, 'fees' => 0, 'taxes' => 0, 'net_revenue' => 0);

        // Helpers for windows
        $sumField = function($rows, $since, $field, $meta = false) {
            $total = 0;
            foreach ($rows as $r) {
                if (strtotime($r['created_at']) >= $since) {
                    if ($meta) {
                        $m = json_decode($r['metadata'] ?: '{}', true);
                        $total += (int)($m[$field] ?? 0);
                    } else {
                        $total += (int)$r[$field];
                    }
                }
            }
            return $total;
        };
        $now = time();
        $totals = [
            'day' => $sumField($rows, strtotime('today', $now), 'amount_total'),
            'week'=> $sumField($rows, strtotime('-7 days', $now), 'amount_total'),
            'month'=> $sumField($rows, strtotime('-30 days', $now), 'amount_total'),
            'year'=> $sumField($rows, strtotime('-365 days', $now), 'amount_total')
        ];
        $totals_breakdown = [
            'net' => [
                'day' => $sumField($rows, strtotime('today', $now), 'net_to_merchant_cents', true),
                'week'=> $sumField($rows, strtotime('-7 days', $now), 'net_to_merchant_cents', true),
                'month'=> $sumField($rows, strtotime('-30 days', $now), 'net_to_merchant_cents', true),
                'year'=> $sumField($rows, strtotime('-365 days', $now), 'net_to_merchant_cents', true)
            ],
            'taxes' => [
                'day' => $sumField($rows, strtotime('today', $now), 'tax_cents', true),
                'week'=> $sumField($rows, strtotime('-7 days', $now), 'tax_cents', true),
                'month'=> $sumField($rows, strtotime('-30 days', $now), 'tax_cents', true),
                'year'=> $sumField($rows, strtotime('-365 days', $now), 'tax_cents', true)
            ],
            'stripe_fees' => [
                'day' => $sumField($rows, strtotime('today', $now), 'stripe_fee_cents', true),
                'week'=> $sumField($rows, strtotime('-7 days', $now), 'stripe_fee_cents', true),
                'month'=> $sumField($rows, strtotime('-30 days', $now), 'stripe_fee_cents', true),
                'year'=> $sumField($rows, strtotime('-365 days', $now), 'stripe_fee_cents', true)
            ],
            'platform_fees' => [
                'day' => $sumField($rows, strtotime('today', $now), 'platform_fee_cents', true),
                'week'=> $sumField($rows, strtotime('-7 days', $now), 'platform_fee_cents', true),
                'month'=> $sumField($rows, strtotime('-30 days', $now), 'platform_fee_cents', true),
                'year'=> $sumField($rows, strtotime('-365 days', $now), 'platform_fee_cents', true)
            ]
        ];

        // Simple last 12 weeks series
        $labels=[]; $sales=[];
        for ($i=11;$i>=0;$i--) {
            $start = strtotime("-{$i} week", strtotime('monday this week'));
            $end = strtotime('+7 days', $start);
            $labels[] = date('M j', $start);
            $sumw=0; foreach($rows as $r){ $t=strtotime($r['created_at']); if($t>=$start && $t<$end) $sumw += (int)$r['amount_total']; }
            $sales[] = $sumw;
        }

        // Last 12 months series (for YOY trend)
        $labelsM = []; $salesM = [];
        $anchor = strtotime(date('Y-m-01')); // first day of this month
        for ($i=11; $i>=0; $i--) {
            $startM = strtotime("-{$i} months", $anchor);
            // end is first day of next month
            $endM = strtotime('+1 month', $startM);
            $labelsM[] = date('M Y', $startM);
            $summ = 0; foreach ($rows as $r){ $t=strtotime($r['created_at']); if($t>=$startM && $t<$endM) $summ += (int)$r['amount_total']; }
            $salesM[] = $summ;
        }

    // Comparative analysis: last 30 days vs prior 30 days
    $this_30d = 0; foreach ($rows as $r) { $t=strtotime($r['created_at']); if ($t>=strtotime('-30 days', $now)) $this_30d += (int)$r['amount_total']; }
        $prev_30d = 0; foreach ($rows as $r) { $t=strtotime($r['created_at']); if ($t>=strtotime('-60 days', $now) && $t<strtotime('-30 days', $now)) $prev_30d += (int)$r['amount_total']; }
        $mom_change = ($prev_30d > 0) ? (($this_30d - $prev_30d) / $prev_30d) : null; // null means no prior period

        $orders_out = array_map(function($r){
            $meta = json_decode($r['metadata'] ?: '{}', true);
            // Prefer real tax; fallback to advisory
            $tax_cents = isset($meta['tax_cents']) ? (int)$meta['tax_cents'] : (isset($meta['advisory_tax_cents']) ? (int)$meta['advisory_tax_cents'] : null);
            return [
                'created_at' => $r['created_at'],
                'amount' => (int)$r['amount_total'],
                'currency' => $r['currency'] ?: 'usd',
                'status' => $r['status'],
                'fulfillment_status' => $r['fulfillment_status'] ?? ($meta['last_business_flow_status'] ?? ''),
                'business_flow_status' => $r['business_flow_status'] ?? ($meta['last_business_flow_status'] ?? ''),
                'business_flow_type' => $r['business_flow_type'] ?? ($meta['business_flow_plan']['business_flow_type'] ?? ''),
                'receipt_url' => $r['receipt_url'],
                'product_name' => $meta['product_name'] ?? '',
                'tax_cents' => $tax_cents,
                'net_to_merchant_cents' => isset($meta['net_to_merchant_cents']) ? (int)$meta['net_to_merchant_cents'] : null,
                'stripe_fee_cents' => isset($meta['stripe_fee_cents']) ? (int)$meta['stripe_fee_cents'] : null,
                'platform_fee_cents' => isset($meta['platform_fee_cents']) ? (int)$meta['platform_fee_cents'] : null
            ];
        }, $rows ?: []);

        return new WP_REST_Response([
            'success' => true,
            'data' => [
                'totals' => $totals,
                'orders' => $orders_out,
                'chart' => [ 'labels' => $labels, 'sales' => $sales ],
                'chart_monthly' => [ 'labels' => $labelsM, 'sales' => $salesM ],
                'comparative' => [ 'last_30d' => $this_30d, 'prev_30d' => $prev_30d, 'mom_change' => $mom_change ],
                'totals_breakdown' => $totals_breakdown,
                'fulfillment_breakdown' => $fulfillment_breakdown
            ]
        ], 200);
    }

    // ===== Advisory config and estimations =====
    public function get_payments_config(WP_REST_Request $req) {
        $uid = get_current_user_id();
        $cfg = get_user_meta($uid, 'vmo_payments_config', true);
        if (!is_array($cfg)) $cfg = [];
        // Defaults: Stripe fee (advisory) 2.9% + 30c for USD, empty tax rules
        $cfg += [
            'stripe_fee' => [ 'usd' => ['percent_bps'=>290, 'fixed_cents'=>30] ],
            'tax_rules' => [],
            'currency' => 'usd'
        ];
        return new WP_REST_Response(['success'=>true,'config'=>$cfg], 200);
    }

    public function set_payments_config(WP_REST_Request $req) {
        $uid = get_current_user_id();
        $p = $req->get_json_params() ?: [];
        $cfg = [
            'stripe_fee' => is_array($p['stripe_fee'] ?? null) ? $p['stripe_fee'] : [],
            'tax_rules'  => is_array($p['tax_rules'] ?? null) ? array_values($p['tax_rules']) : [],
            'currency'   => strtolower(sanitize_text_field($p['currency'] ?? 'usd'))
        ];
        update_user_meta($uid, 'vmo_payments_config', $cfg);
        return new WP_REST_Response(['success'=>true], 200);
    }

    public function estimate_pricing(WP_REST_Request $req) {
        $uid = get_current_user_id();
        $p = $req->get_json_params() ?: [];
        $amount_cents = max(0, (int)($p['amount_cents'] ?? 0));
        $currency = strtolower(sanitize_text_field($p['currency'] ?? 'usd'));
        $address = [
            'country' => strtoupper(sanitize_text_field($p['country'] ?? '')),
            'state'   => strtoupper(sanitize_text_field($p['state'] ?? '')),
            'postal_code' => sanitize_text_field($p['postal_code'] ?? '')
        ];
        $cfg = get_user_meta($uid, 'vmo_payments_config', true);
        if (!is_array($cfg)) $cfg = [];
        $stripe_fee_cfg = $cfg['stripe_fee'][$currency] ?? [ 'percent_bps'=>290, 'fixed_cents'=>30 ];
        $platform_fee_bps = (int) get_option('vmo_stripe_platform_fee_bps', 50);
        $tax_cents = $this->compute_advisory_tax($amount_cents, $currency, $address, $cfg['tax_rules'] ?? []);
        $stripe_fee_cents = (int) round($amount_cents * (($stripe_fee_cfg['percent_bps'] ?? 290) / 10000)) + (int)($stripe_fee_cfg['fixed_cents'] ?? 30);
        $platform_fee_cents = (int) round($amount_cents * ($platform_fee_bps / 10000));
        $net_estimate_cents = max(0, $amount_cents - $tax_cents - $stripe_fee_cents - $platform_fee_cents);
        return new WP_REST_Response([
            'success'=>true,
            'data' => [
                'tax_cents' => $tax_cents,
                'stripe_fee_cents' => $stripe_fee_cents,
                'platform_fee_cents' => $platform_fee_cents,
                'net_estimate_cents' => $net_estimate_cents
            ]
        ], 200);
    }

    private function compute_advisory_tax($amount_cents, $currency, $address, $rules) {
        if ($amount_cents <= 0 || !is_array($rules)) return 0;
        $country = strtoupper($address['country'] ?? '');
        $state = strtoupper($address['state'] ?? '');
        $rate_bps_total = 0;
        foreach ($rules as $r) {
            $rc = strtoupper($r['country'] ?? '');
            if ($rc && $rc !== $country) continue;
            $rs = strtoupper($r['state'] ?? '');
            if ($rs && $rs !== $state) continue;
            $bps = (int)($r['rate_bps'] ?? 0);
            if ($bps > 0) $rate_bps_total += $bps;
        }
        return (int) round($amount_cents * ($rate_bps_total / 10000));
    }

    /**
     * 🔔 STRIPE WEBHOOK HANDLER
     * Handles automated transaction communications and customer management
     * 
     * Events handled (configured in Stripe):
     * - checkout.session.completed → Send receipt, create customer, record purchase
     * - customer.subscription.deleted → Update subscription status
     * - customer.subscription.updated → Update subscription details
     * - invoice.payment_succeeded → Send invoice/receipt for subscriptions
     */
    public function handle_stripe_webhook(WP_REST_Request $req) {
        if (function_exists('vmo_handle_stripe_webhook')) {
            return vmo_handle_stripe_webhook($req);
        }

        $init = $this->init_stripe();
        if (is_wp_error($init)) {
            error_log('VMO Stripe webhook: init failed');
            return new WP_REST_Response(['error' => 'Configuration error'], 500);
        }

        // Get webhook secret
        $webhook_secret = get_option('vmo_stripe_webhook_secret');
        
        // Get raw body and signature
        $payload = $req->get_body();
        $sig_header = $req->get_header('stripe-signature');

        // Verify webhook signature (if secret is configured)
        try {
            if ($webhook_secret && $sig_header) {
                $event = \Stripe\Webhook::constructEvent($payload, $sig_header, $webhook_secret);
            } elseif (!$webhook_secret) {
                // No webhook secret configured — reject in production
                error_log('VMO Stripe webhook: REJECTED — no webhook secret configured. Set vmo_stripe_webhook_secret in settings.');
                return new WP_REST_Response(['error' => 'Webhook secret not configured'], 500);
            } else {
                // Secret configured but signature header missing — reject
                error_log('VMO Stripe webhook: REJECTED — Stripe-Signature header missing from request.');
                return new WP_REST_Response(['error' => 'Missing signature'], 400);
            }
        } catch (\UnexpectedValueException $e) {
            error_log('VMO Stripe webhook: Invalid payload - ' . $e->getMessage());
            return new WP_REST_Response(['error' => 'Invalid payload'], 400);
        } catch (\Stripe\Exception\SignatureVerificationException $e) {
            error_log('VMO Stripe webhook: Invalid signature - ' . $e->getMessage());
            return new WP_REST_Response(['error' => 'Invalid signature'], 400);
        }

        $event_type = $event->type ?? '';
        error_log("VMO Stripe webhook received: {$event_type}");

        // Handle different event types
        switch ($event_type) {
            case 'checkout.session.completed':
                $this->handle_checkout_completed($event->data->object);
                break;
            case 'invoice.payment_succeeded':
                $this->handle_invoice_payment_succeeded($event->data->object);
                break;
            case 'customer.subscription.updated':
                $this->handle_subscription_updated($event->data->object);
                break;
            case 'customer.subscription.deleted':
                $this->handle_subscription_deleted($event->data->object);
                break;
            case 'charge.refunded':
                $this->handle_charge_refunded($event->data->object);
                break;
            default:
                error_log("VMO Stripe webhook: Unhandled event type {$event_type}");
        }

        return new WP_REST_Response(['received' => true], 200);
    }

    /**
     * Handle checkout.session.completed event
     * - Create/update customer in CRM
     * - Record purchase
     * - Send receipt email
     * - Send order confirmation
     */
    private function handle_checkout_completed($session) {
        global $wpdb;

        $session_id = $session->id ?? '';
        $customer_email = $session->customer_details->email ?? $session->customer_email ?? '';
        $customer_name = $session->customer_details->name ?? '';
        $amount_total = $session->amount_total ?? 0; // in cents
        $currency = strtoupper($session->currency ?? 'USD');
        $payment_intent_id = $session->payment_intent ?? '';
        $payment_status = $session->payment_status ?? '';
        $metadata = $session->metadata ?? new stdClass();
        $user_id = isset($metadata->user_id) ? (int)$metadata->user_id : 0;

        // ── VMO Pay Invoice payment detection ──
        if (isset($metadata->vmo_invoice_id) && $payment_status === 'paid') {
            $inv_id = (int) $metadata->vmo_invoice_id;
            $inv_table = $wpdb->prefix . 'vmo_invoices';
            $wpdb->update($inv_table, [
                'status'                    => 'paid',
                'paid_at'                   => current_time('mysql'),
                'stripe_payment_intent_id'  => $payment_intent_id,
            ], ['id' => $inv_id], ['%s','%s','%s'], ['%d']);
            error_log("VMO Pay: Invoice #{$inv_id} marked as paid via Stripe checkout");
        }

        // Connect store orders (public checkout): they won't include platform user_id.
        if (!$user_id) {
            $orders_table = $wpdb->prefix . 'vmo_store_orders';
            $now = current_time('mysql');
            $pi_id = $payment_intent_id ? (string)$payment_intent_id : null;
            $amt = is_numeric($amount_total) ? (int)$amount_total : null;

            // Atomically mark as paid if not already.
            if ($amt !== null) {
                $sql = $wpdb->prepare(
                    "UPDATE $orders_table SET status='paid', stripe_payment_intent_id=%s, amount_total=%d, updated_at=%s WHERE stripe_checkout_session_id=%s AND status != 'paid'",
                    $pi_id, $amt, $now, $session_id
                );
            } else {
                $sql = $wpdb->prepare(
                    "UPDATE $orders_table SET status='paid', stripe_payment_intent_id=%s, updated_at=%s WHERE stripe_checkout_session_id=%s AND status != 'paid'",
                    $pi_id, $now, $session_id
                );
            }
            $wpdb->query($sql);

            // Best-effort: store buyer email/name in metadata if present.
            $row = $wpdb->get_row($wpdb->prepare("SELECT id, metadata FROM $orders_table WHERE stripe_checkout_session_id=%s", $session_id), ARRAY_A);
            if ($row) {
                $m = json_decode($row['metadata'] ?: '{}', true);
                if (!is_array($m)) $m = [];
                if ($customer_email) $m['buyer_email'] = $customer_email;
                if ($customer_name) $m['buyer_name'] = $customer_name;
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                $wpdb->update($orders_table, [
                    'metadata' => wp_json_encode($m),
                    'updated_at' => $now,
                ], [ 'id' => (int)$row['id'] ]);

                // ✅ STOCK DECREMENT: Reduce inventory for tracked products
                $product_id = isset($m['product_id']) ? intval($m['product_id']) : 0;
                $qty = isset($m['quantity']) ? max(1, intval($m['quantity'])) : 1;
                $merchant_user_id = isset($m['merchant_user_id']) ? intval($m['merchant_user_id']) : 0;
                if ($product_id > 0 && $merchant_user_id > 0) {
                    $products_table = $wpdb->prefix . 'vmo_store_products';
                    $wpdb->query($wpdb->prepare(
                        "UPDATE $products_table SET stock_qty = GREATEST(stock_qty - %d, 0), updated_at = %s WHERE id = %d AND user_id = %d AND stock_tracking = 1",
                        $qty, $now, $product_id, $merchant_user_id
                    ));

                    // Check for low stock and send alert
                    $updated_product = $wpdb->get_row($wpdb->prepare(
                        "SELECT name, slug, stock_qty FROM $products_table WHERE id = %d AND user_id = %d AND stock_tracking = 1",
                        $product_id, $merchant_user_id
                    ), ARRAY_A);
                    if ($updated_product && intval($updated_product['stock_qty']) <= 5) {
                        $this->send_low_stock_alert($merchant_user_id, [
                            'name' => $updated_product['name'],
                            'slug' => $updated_product['slug'],
                            'stock_qty' => $updated_product['stock_qty'],
                            'product_id' => $product_id
                        ]);
                    }
                }
            }

            if ($row && function_exists('vmo_business_flow_sync_paid_order')) {
                vmo_business_flow_sync_paid_order((int) $row['id'], [
                    'session_id' => $session_id,
                    'buyer_email' => $customer_email,
                    'buyer_name' => $customer_name,
                    'customer_email' => $customer_email,
                    'customer_name' => $customer_name,
                    'amount_total' => $amount_total,
                    'currency' => $currency,
                    'stripe_payment_intent_id' => $payment_intent_id,
                ]);
            }

            return;
        }

        if (!$customer_email) {
            error_log("VMO Stripe webhook: Missing customer_email in session {$session_id}");
            return;
        }

        // Extract product information from line items or metadata
        $product_name = isset($metadata->product_name) ? $metadata->product_name : 'Purchase';
        $product_id = isset($metadata->product_id) ? (int)$metadata->product_id : 0;

        // 1-2. CREATE/UPDATE CUSTOMER IN CRM AND RECORD PURCHASE
        if (function_exists('vmo_crm_record_purchase')) {
            vmo_crm_record_purchase((int) $user_id, [
                'email' => $customer_email,
                'full_name' => $customer_name,
                'phone' => $session->customer_details->phone ?? '',
                'source' => 'stripe',
            ], [
                'transaction_id' => $payment_intent_id,
                'product_service' => $product_name,
                'purchase_type' => 'one_time',
                'amount' => $amount_total / 100,
                'currency' => $currency,
                'status' => $payment_status === 'paid' ? 'completed' : 'pending',
                'purchase_date' => current_time('mysql'),
                'payment_method' => 'card',
                'source' => 'vmo_pay',
                'notes' => wp_json_encode(['stripe_session_id' => $session_id, 'payment_intent' => $payment_intent_id]),
            ]);
        } else {
            $this->ensure_customer_in_crm($user_id, $customer_email, $customer_name, $session);
        }

        // 3. UPDATE STORE ORDER STATUS
        $orders_table = $wpdb->prefix . 'vmo_store_orders';
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->update(
            $orders_table,
            [
                'status' => $payment_status === 'paid' ? 'paid' : 'created',
                'stripe_payment_intent_id' => $payment_intent_id,
                'updated_at' => current_time('mysql')
            ],
            ['stripe_checkout_session_id' => $session_id],
            ['%s', '%s', '%s'],
            ['%s']
        );

        // 3b. STOCK DECREMENT on successful payment
        if ($payment_status === 'paid') {
            $order_row = $wpdb->get_row($wpdb->prepare(
                "SELECT metadata FROM $orders_table WHERE stripe_checkout_session_id = %s", $session_id
            ), ARRAY_A);
            if ($order_row) {
                $order_meta = json_decode($order_row['metadata'] ?: '{}', true);
                $prod_id = isset($order_meta['product_id']) ? intval($order_meta['product_id']) : 0;
                $qty = isset($order_meta['quantity']) ? max(1, intval($order_meta['quantity'])) : 1;
                $merchant_id = isset($order_meta['merchant_user_id']) ? intval($order_meta['merchant_user_id']) : 0;
                if ($prod_id > 0 && $merchant_id > 0) {
                    $products_table = $wpdb->prefix . 'vmo_store_products';
                    $wpdb->query($wpdb->prepare(
                        "UPDATE $products_table SET stock_qty = GREATEST(stock_qty - %d, 0), updated_at = %s WHERE id = %d AND user_id = %d AND stock_tracking = 1",
                        $qty, current_time('mysql'), $prod_id, $merchant_id
                    ));

                    // Check for low stock and send alert
                    $updated_product = $wpdb->get_row($wpdb->prepare(
                        "SELECT name, slug, stock_qty FROM $products_table WHERE id = %d AND user_id = %d AND stock_tracking = 1",
                        $prod_id, $merchant_id
                    ), ARRAY_A);
                    if ($updated_product && intval($updated_product['stock_qty']) <= 5) {
                        $this->send_low_stock_alert($merchant_id, [
                            'name' => $updated_product['name'],
                            'slug' => $updated_product['slug'],
                            'stock_qty' => $updated_product['stock_qty'],
                            'product_id' => $prod_id
                        ]);
                    }
                }
            }
        }

        // 4. SEND RECEIPT EMAIL
        $receipt_url = $this->get_receipt_url($payment_intent_id);
        if ($receipt_url) {
            $this->send_receipt_email($customer_email, $customer_name, [
                'product_name' => $product_name,
                'amount' => $amount_total / 100,
                'currency' => $currency,
                'receipt_url' => $receipt_url,
                'transaction_id' => $payment_intent_id,
                'date' => current_time('mysql')
            ]);
        }

        // 5. SEND ORDER CONFIRMATION EMAIL
        $this->send_order_confirmation_email($customer_email, $customer_name, [
            'product_name' => $product_name,
            'amount' => $amount_total / 100,
            'currency' => $currency,
            'order_date' => current_time('mysql')
        ]);

        // 6. SEND SALE NOTIFICATION TO STORE OWNER
        $this->send_owner_sale_notification($user_id, [
            'customer_name' => $customer_name,
            'customer_email' => $customer_email,
            'product_name' => $product_name,
            'product_id' => $product_id,
            'amount' => $amount_total / 100,
            'currency' => $currency,
            'transaction_id' => $payment_intent_id,
            'order_date' => current_time('mysql'),
            'session_id' => $session_id,
            'fulfillment_guidance' => function_exists('vmo_business_flow_guidance_for_order_meta') ? vmo_business_flow_guidance_for_order_meta((array) $metadata) : ''
        ]);

        error_log("VMO Stripe webhook: Processed checkout for {$customer_email}, amount: {$currency} " . ($amount_total/100));

        $order_id = (int) $wpdb->get_var($wpdb->prepare(
            "SELECT id FROM {$orders_table} WHERE stripe_checkout_session_id = %s LIMIT 1",
            $session_id
        ));

        if ($order_id > 0 && function_exists('vmo_business_flow_sync_paid_order')) {
            vmo_business_flow_sync_paid_order($order_id, [
                'session_id' => $session_id,
                'buyer_email' => $customer_email,
                'buyer_name' => $customer_name,
                'customer_email' => $customer_email,
                'customer_name' => $customer_name,
                'amount_total' => $amount_total,
                'currency' => $currency,
                'stripe_payment_intent_id' => $payment_intent_id,
            ]);
        }

        // 7. NOTIFY ABANDONED CART SYSTEM (mark as recovered if applicable)
        do_action('vmo_checkout_completed', $order_id, [
            'session_id' => $session_id,
            'customer_email' => $customer_email,
        ]);
    }

    /**
     * Ensure customer exists in CRM (wp_vmo_contacts)
     * Creates new contact or updates existing one
     */
    private function ensure_customer_in_crm($user_id, $email, $name, $session) {
        $phone = $session->customer_details->phone ?? '';

        // Use the universal upsert helper
        if ( function_exists( 'vmo_upsert_contact' ) ) {
            $contact_id = vmo_upsert_contact( (int) $user_id, [
                'email'            => $email,
                'full_name'        => $name,
                'phone'            => $phone,
                'source'           => 'other',
                'primary_category' => 'customer',
                'lifecycle_stage'  => 'customer',
                'lead_score'       => 100,
                'engagement_level' => 'high',
                'value_potential'   => 100,
                'notes'            => 'Customer from VMO Payments',
            ] );
            return $contact_id;
        }

        return '';
    }

    /**
     * Get receipt URL from Stripe
     */
    private function get_receipt_url($payment_intent_id) {
        if (!$payment_intent_id) return null;
        
        try {
            $payment_intent = \Stripe\PaymentIntent::retrieve($payment_intent_id);
            $charges = $payment_intent->charges->data ?? [];
            
            if (is_array($charges) && count($charges) > 0) {
                $charge = $charges[0];
                return $charge->receipt_url ?? null;
            }
        } catch (Exception $e) {
            error_log("VMO Stripe: Error getting receipt URL - " . $e->getMessage());
        }
        return null;
    }

    /**
     * Send receipt email to customer
     */
    private function send_receipt_email($customer_email, $customer_name, $order_data) {
        $site_name = get_bloginfo('name');
        $subject = "Receipt from {$site_name}";
        
        $amount = number_format($order_data['amount'], 2);
        $currency = $order_data['currency'];
        $product_name = $order_data['product_name'];
        $receipt_url = $order_data['receipt_url'];
        $transaction_id = $order_data['transaction_id'];
        $date = date('F j, Y', strtotime($order_data['date']));

        $message = "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='UTF-8'>
            <style>
                body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background: #0b1117; color: #65f1ff; padding: 20px; text-align: center; border-radius: 8px 8px 0 0; }
                .content { background: #fff; padding: 30px; border: 1px solid #e0e0e0; }
                .amount { font-size: 32px; font-weight: bold; color: #10b981; margin: 20px 0; }
                .button { display: inline-block; background: #65f1ff; color: #0b1117; padding: 12px 24px; text-decoration: none; border-radius: 6px; font-weight: bold; margin: 20px 0; }
                .details { background: #f9f9f9; padding: 15px; border-radius: 6px; margin: 20px 0; }
                .footer { text-align: center; color: #666; font-size: 12px; margin-top: 30px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h1>🧾 Payment Receipt</h1>
                </div>
                <div class='content'>
                    <h2>Thank you for your purchase!</h2>
                    <p>Hi {$customer_name},</p>
                    <p>Your payment was successful. Here are the details:</p>
                    
                    <div class='amount'>{$currency} {$amount}</div>
                    
                    <div class='details'>
                        <p><strong>Product:</strong> {$product_name}</p>
                        <p><strong>Transaction ID:</strong> {$transaction_id}</p>
                        <p><strong>Date:</strong> {$date}</p>
                        <p><strong>Payment Method:</strong> Card</p>
                    </div>
                    
                    " . ($receipt_url ? "<p style='text-align:center;'><a href='{$receipt_url}' class='button'>View Official Receipt</a></p>" : "") . "
                    
                    <p>If you have any questions about this payment, please don't hesitate to contact us.</p>
                    
                    <p>Best regards,<br>The {$site_name} Team</p>
                </div>
                <div class='footer'>
                    <p>This is an automated receipt from {$site_name}.</p>
                    <p>Powered by VMO Payments</p>
                </div>
            </div>
        </body>
        </html>";

        $headers = ['Content-Type: text/html; charset=UTF-8'];
        wp_mail($customer_email, $subject, $message, $headers);
        
        error_log("VMO Stripe: Receipt email sent to {$customer_email}");
    }

    /**
     * Send order confirmation email
     */
    private function send_order_confirmation_email($customer_email, $customer_name, $order_data) {
        $site_name = get_bloginfo('name');
        $subject = "Order Confirmation - {$order_data['product_name']}";
        
        $amount = number_format($order_data['amount'], 2);
        $currency = $order_data['currency'];
        $product_name = $order_data['product_name'];
        $date = date('F j, Y', strtotime($order_data['order_date']));

        $message = "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='UTF-8'>
            <style>
                body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background: #10b981; color: #fff; padding: 20px; text-align: center; border-radius: 8px 8px 0 0; }
                .content { background: #fff; padding: 30px; border: 1px solid #e0e0e0; }
                .product { background: #f0fdf4; padding: 20px; border-radius: 8px; margin: 20px 0; border-left: 4px solid #10b981; }
                .footer { text-align: center; color: #666; font-size: 12px; margin-top: 30px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h1>✅ Order Confirmed!</h1>
                </div>
                <div class='content'>
                    <h2>Your order is confirmed</h2>
                    <p>Hi {$customer_name},</p>
                    <p>We've received your order and payment. Thank you for your business!</p>
                    
                    <div class='product'>
                        <h3>{$product_name}</h3>
                        <p><strong>Amount:</strong> {$currency} {$amount}</p>
                        <p><strong>Order Date:</strong> {$date}</p>
                    </div>
                    
                    <p>You'll receive access to your purchase shortly. If you have any questions, we're here to help!</p>
                    
                    <p>Best regards,<br>The {$site_name} Team</p>
                </div>
                <div class='footer'>
                    <p>This is an automated confirmation from {$site_name}.</p>
                    <p>Powered by VMO Payments</p>
                </div>
            </div>
        </body>
        </html>";

        $headers = ['Content-Type: text/html; charset=UTF-8'];
        wp_mail($customer_email, $subject, $message, $headers);
        
        error_log("VMO Stripe: Order confirmation sent to {$customer_email}");
    }

    /**
     * Handle invoice.payment_succeeded event (for subscriptions)
     */
    private function handle_invoice_payment_succeeded($invoice) {
        global $wpdb;
        
        $subscription_id = $invoice->subscription ?? '';
        $customer_email = $invoice->customer_email ?? '';
        $amount = $invoice->amount_paid ?? 0;
        $currency = strtoupper($invoice->currency ?? 'USD');
        
        if (!$customer_email) return;
        
        // Send subscription invoice receipt
        $site_name = get_bloginfo('name');
        $subject = "Invoice Receipt from {$site_name}";
        $amount_formatted = number_format($amount / 100, 2);
        
        $message = "
        <html><body style='font-family:Arial,sans-serif;'>
        <div style='max-width:600px;margin:0 auto;padding:20px;'>
            <h2>Subscription Payment Received</h2>
            <p>Your subscription payment of {$currency} {$amount_formatted} was processed successfully.</p>
            <p>Thank you for your continued support!</p>
            <p>Best regards,<br>{$site_name}</p>
        </div>
        </body></html>";
        
        wp_mail($customer_email, $subject, $message, ['Content-Type: text/html; charset=UTF-8']);
        
        error_log("VMO Stripe: Invoice receipt sent to {$customer_email} for subscription {$subscription_id}");
    }

    /**
     * Handle customer.subscription.updated event
     */
    private function handle_subscription_updated($subscription) {
        global $wpdb;
        
        $subscription_id = $subscription->id ?? '';
        $status = $subscription->status ?? '';
        $customer_id = $subscription->customer ?? '';
        
        // Update subscription status in database
        $subscriptions_table = $wpdb->prefix . 'vmo_subscriptions';
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->update(
            $subscriptions_table,
            ['status' => $status, 'updated_at' => current_time('mysql')],
            ['stripe_subscription_id' => $subscription_id],
            ['%s', '%s'],
            ['%s']
        );
        
        error_log("VMO Stripe: Subscription {$subscription_id} updated to status: {$status}");
    }

    /**
     * Handle customer.subscription.deleted event
     */
    private function handle_subscription_deleted($subscription) {
        global $wpdb;
        
        $subscription_id = $subscription->id ?? '';
        $customer_email = $subscription->customer_email ?? '';
        
        // Update subscription status to cancelled
        $subscriptions_table = $wpdb->prefix . 'vmo_subscriptions';
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->update(
            $subscriptions_table,
            ['status' => 'cancelled', 'updated_at' => current_time('mysql')],
            ['stripe_subscription_id' => $subscription_id],
            ['%s', '%s'],
            ['%s']
        );
        
        // Send cancellation confirmation email
        if ($customer_email) {
            $site_name = get_bloginfo('name');
            $subject = "Subscription Cancelled";
            
            $message = "
            <html><body style='font-family:Arial,sans-serif;'>
            <div style='max-width:600px;margin:0 auto;padding:20px;'>
                <h2>Subscription Cancelled</h2>
                <p>Your subscription has been cancelled as requested.</p>
                <p>We're sorry to see you go! If you have any feedback, we'd love to hear it.</p>
                <p>Best regards,<br>{$site_name}</p>
            </div>
            </body></html>";
            
            wp_mail($customer_email, $subject, $message, ['Content-Type: text/html; charset=UTF-8']);
        }
        
        error_log("VMO Stripe: Subscription {$subscription_id} cancelled");
    }

    /**
     * Handle charge.refunded event
     * - Update purchase status to 'refunded'
     * - Send refund notification email
     */
    private function handle_charge_refunded($charge) {
        global $wpdb;

        $charge_id = $charge->id ?? '';
        $payment_intent_id = $charge->payment_intent ?? '';
        $amount_refunded = $charge->amount_refunded ?? 0; // in cents
        $currency = strtoupper($charge->currency ?? 'USD');
        $customer_email = $charge->billing_details->email ?? '';
        $refund_reason = $charge->refunds->data[0]->reason ?? 'requested';

        error_log("VMO Stripe webhook: Processing refund for charge {$charge_id}, amount: {$amount_refunded}");

        // 1. UPDATE PURCHASE STATUS TO REFUNDED
        if ($payment_intent_id) {
            // Try to find purchase by payment_intent (transaction_id)
            $table = $wpdb->prefix . 'vmo_contact_purchases';
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $updated = $wpdb->update(
                $table,
                [
                    'status' => 'refunded',
                    'purchase_date' => current_time('mysql') // Update timestamp
                ],
                ['transaction_id' => $payment_intent_id],
                ['%s', '%s'],
                ['%s']
            );

            if ($updated) {
                error_log("VMO Stripe: Updated purchase status to refunded for payment_intent {$payment_intent_id}");
            } else {
                error_log("VMO Stripe: Could not find purchase with transaction_id {$payment_intent_id}");
            }
        }

        // 2. SEND REFUND NOTIFICATION EMAIL
        if ($customer_email) {
            $amount_formatted = number_format($amount_refunded / 100, 2);
            $site_name = get_bloginfo('name');
            $subject = "Refund Processed - {$site_name}";
            
            $message = "
            <html><body style='font-family:Arial,sans-serif;'>
            <div style='max-width:600px;margin:0 auto;padding:20px;border:1px solid #ddd;border-radius:8px;'>
                <h2 style='color:#4CAF50;'>↩️ Refund Processed</h2>
                <p>Hi there,</p>
                <p>Your refund has been processed successfully.</p>
                <div style='background:#f5f5f5;padding:15px;border-radius:5px;margin:20px 0;'>
                    <p style='margin:5px 0;'><strong>Refund Amount:</strong> {$currency} {$amount_formatted}</p>
                    <p style='margin:5px 0;'><strong>Transaction ID:</strong> {$payment_intent_id}</p>
                    <p style='margin:5px 0;'><strong>Reason:</strong> " . ucfirst($refund_reason) . "</p>
                </div>
                <p>The refund will appear in your account within 5-10 business days, depending on your bank.</p>
                <p>If you have any questions, please don't hesitate to contact us.</p>
                <p style='margin-top:30px;'>Best regards,<br><strong>{$site_name}</strong></p>
                <hr style='border:none;border-top:1px solid #eee;margin:20px 0;'>
                <p style='font-size:12px;color:#999;'>Powered by VMO Payments</p>
            </div>
            </body></html>";
            
            wp_mail($customer_email, $subject, $message, ['Content-Type: text/html; charset=UTF-8']);
            error_log("VMO Stripe: Refund notification sent to {$customer_email}");
        }
    }

    /**
     * Send sale notification email to store owner
     * Notifies the merchant when a customer purchases from their store
     * 
     * @param int $merchant_user_id The store owner's WordPress user ID
     * @param array $sale_data Sale details including customer info, product, amount
     */
    private function send_owner_sale_notification($merchant_user_id, $sale_data) {
        if ($merchant_user_id <= 0) return;

        // Get owner's email
        $owner = get_userdata($merchant_user_id);
        if (!$owner || !$owner->user_email) {
            error_log("VMO Stripe: Cannot send owner notification - user {$merchant_user_id} not found");
            return;
        }

        $owner_email = $owner->user_email;
        $site_name = get_bloginfo('name');
        $amount = number_format($sale_data['amount'], 2);
        $currency = strtoupper($sale_data['currency']);
        $customer_name = esc_html($sale_data['customer_name'] ?: 'Anonymous');
        $customer_email = esc_html($sale_data['customer_email']);
        $product_name = esc_html($sale_data['product_name']);
        $transaction_id = esc_html($sale_data['transaction_id']);
        $date = date('F j, Y g:i A', strtotime($sale_data['order_date']));
        $dashboard_url = admin_url('admin.php?page=vmo-ai-dashboard');
        $fulfillment_guidance = sanitize_text_field((string) ($sale_data['fulfillment_guidance'] ?? 'Review the dashboard and complete the next fulfillment step.'));

        $subject = "💰 New Sale! {$currency} {$amount} - {$product_name}";

        $message = "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='UTF-8'>
            <meta name='viewport' content='width=device-width, initial-scale=1.0'>
            <style>
                body { margin: 0; padding: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; background-color: #0f172a; }
                @media only screen and (max-width: 480px) {
                    .mobile-padding { padding-left: 20px !important; padding-right: 20px !important; }
                    .amount-display { font-size: 36px !important; }
                }
            </style>
        </head>
        <body style='margin: 0; padding: 0; background-color: #0f172a;'>
            <table border='0' cellpadding='0' cellspacing='0' width='100%' style='background-color: #0f172a;'>
                <tr>
                    <td align='center' style='padding: 40px 10px;'>
                        <table border='0' cellpadding='0' cellspacing='0' width='100%' style='max-width: 600px;'>
                            <!-- Main Card -->
                            <tr>
                                <td style='background-color: #1e293b; border-radius: 16px; overflow: hidden; border: 1px solid rgba(255,255,255,0.05);'>
                                    <!-- Gradient Header -->
                                    <table border='0' cellpadding='0' cellspacing='0' width='100%'>
                                        <tr>
                                            <td style='background: linear-gradient(135deg, #10b981, #06b6d4); padding: 30px; text-align: center;'>
                                                <div style='font-size: 48px; margin-bottom: 10px;'>🎉</div>
                                                <h1 style='margin: 0; color: #ffffff; font-size: 24px; font-weight: 700;'>New Sale!</h1>
                                                <p style='margin: 8px 0 0; color: rgba(255,255,255,0.9); font-size: 14px;'>Ka-ching! Someone just bought from your store</p>
                                            </td>
                                        </tr>
                                    </table>

                                    <!-- Amount Display -->
                                    <table border='0' cellpadding='0' cellspacing='0' width='100%'>
                                            <tr>
                                                <td style='padding: 12px 0; border-bottom: 1px solid rgba(255,255,255,0.1);'>
                                                    <span style='color: #94a3b8; font-size: 14px;'>Next Action</span><br>
                                                    <span style='color: #e2e8f0; font-size: 15px;'>{$fulfillment_guidance}</span>
                                                </td>
                                            </tr>
                                        <tr>
                                            <td class='mobile-padding' style='padding: 30px 40px; text-align: center;'>
                                                <p style='margin: 0 0 5px; color: #94a3b8; font-size: 14px; text-transform: uppercase; letter-spacing: 1px;'>Amount Received</p>
                                                <p class='amount-display' style='margin: 0; color: #10b981; font-size: 48px; font-weight: 800; letter-spacing: -1px;'>{$currency} {$amount}</p>
                                            </td>
                                        </tr>
                                    </table>

                                    <!-- Order Details -->
                                    <table border='0' cellpadding='0' cellspacing='0' width='100%'>
                                        <tr>
                                            <td class='mobile-padding' style='padding: 0 40px 30px;'>
                                                <table border='0' cellpadding='12' cellspacing='0' width='100%' style='background-color: rgba(255,255,255,0.03); border-radius: 12px; border: 1px solid rgba(255,255,255,0.05);'>
                                                    <tr>
                                                        <td style='color: #94a3b8; border-bottom: 1px solid rgba(255,255,255,0.05); width: 120px;'>Product</td>
                                                        <td style='color: #ffffff; border-bottom: 1px solid rgba(255,255,255,0.05); font-weight: 600;'>{$product_name}</td>
                                                    </tr>
                                                    <tr>
                                                        <td style='color: #94a3b8; border-bottom: 1px solid rgba(255,255,255,0.05);'>Customer</td>
                                                        <td style='color: #ffffff; border-bottom: 1px solid rgba(255,255,255,0.05);'>{$customer_name}</td>
                                                    </tr>
                                                    <tr>
                                                        <td style='color: #94a3b8; border-bottom: 1px solid rgba(255,255,255,0.05);'>Email</td>
                                                        <td style='color: #06b6d4; border-bottom: 1px solid rgba(255,255,255,0.05);'>
                                                            <a href='mailto:{$customer_email}' style='color: #06b6d4; text-decoration: none;'>{$customer_email}</a>
                                                        </td>
                                                    </tr>
                                                    <tr>
                                                        <td style='color: #94a3b8; border-bottom: 1px solid rgba(255,255,255,0.05);'>Transaction</td>
                                                        <td style='color: #ffffff; border-bottom: 1px solid rgba(255,255,255,0.05); font-family: monospace; font-size: 12px;'>{$transaction_id}</td>
                                                    </tr>
                                                    <tr>
                                                        <td style='color: #94a3b8;'>Date</td>
                                                        <td style='color: #ffffff;'>{$date}</td>
                                                    </tr>
                                                </table>
                                            </td>
                                        </tr>
                                    </table>

                                    <!-- CTA Button -->
                                    <table border='0' cellpadding='0' cellspacing='0' width='100%'>
                                        <tr>
                                            <td align='center' style='padding: 0 40px 30px;'>
                                                <a href='{$dashboard_url}' style='display: inline-block; background: linear-gradient(135deg, #06b6d4, #8b5cf6); color: #ffffff; padding: 14px 32px; text-decoration: none; border-radius: 8px; font-weight: 600; font-size: 16px;'>View Dashboard</a>
                                            </td>
                                        </tr>
                                    </table>

                                    <!-- Quick Actions -->
                                    <table border='0' cellpadding='0' cellspacing='0' width='100%' style='background-color: rgba(255,255,255,0.02); border-top: 1px solid rgba(255,255,255,0.05);'>
                                        <tr>
                                            <td style='padding: 20px 40px; text-align: center;'>
                                                <p style='margin: 0 0 10px; color: #94a3b8; font-size: 13px;'>Quick Actions</p>
                                                <a href='mailto:{$customer_email}' style='color: #06b6d4; text-decoration: none; margin: 0 10px; font-size: 14px;'>📧 Email Customer</a>
                                                <span style='color: #334155;'>|</span>
                                                <a href='{$dashboard_url}' style='color: #06b6d4; text-decoration: none; margin: 0 10px; font-size: 14px;'>📊 View Orders</a>
                                            </td>
                                        </tr>
                                    </table>
                                </td>
                            </tr>

                            <!-- Footer -->
                            <tr>
                                <td align='center' style='padding: 30px 0;'>
                                    <p style='margin: 0; color: #475569; font-size: 12px;'>
                                        This notification was sent by VMO Payments<br>
                                        <a href='{$dashboard_url}' style='color: #06b6d4; text-decoration: none;'>Manage notification preferences</a>
                                    </p>
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        </body>
        </html>";

        $headers = ['Content-Type: text/html; charset=UTF-8'];
        $sent = wp_mail($owner_email, $subject, $message, $headers);

        if ($sent) {
            error_log("VMO Stripe: Owner sale notification sent to {$owner_email} for {$currency} {$amount}");
        } else {
            error_log("VMO Stripe: Failed to send owner sale notification to {$owner_email}");
        }
    }

    /**
     * Send low stock alert to store owner
     * Triggered when stock drops below threshold after a sale
     *
     * @param int $merchant_user_id The store owner's user ID
     * @param array $product_data Product info: name, slug, stock_qty, product_id
     */
    private function send_low_stock_alert($merchant_user_id, $product_data) {
        if ($merchant_user_id <= 0) return;

        $owner = get_userdata($merchant_user_id);
        if (!$owner || !$owner->user_email) return;

        $owner_email = $owner->user_email;
        $site_name = get_bloginfo('name');
        $product_name = esc_html($product_data['name']);
        $stock_qty = intval($product_data['stock_qty']);
        $dashboard_url = admin_url('admin.php?page=vmo-ai-dashboard');

        $urgency_color = $stock_qty <= 0 ? '#ef4444' : '#f59e0b';
        $urgency_label = $stock_qty <= 0 ? '🚨 OUT OF STOCK' : "⚠️ Only {$stock_qty} left";
        $subject = $stock_qty <= 0
            ? "🚨 OUT OF STOCK: {$product_name}"
            : "⚠️ Low Stock Alert: {$product_name} ({$stock_qty} remaining)";

        $message = "
        <!DOCTYPE html>
        <html>
        <head><meta charset='UTF-8'></head>
        <body style='margin:0;padding:0;background-color:#0f172a;font-family:Helvetica Neue,Arial,sans-serif;'>
            <table border='0' cellpadding='0' cellspacing='0' width='100%' style='background:#0f172a;'>
                <tr><td align='center' style='padding:40px 10px;'>
                    <table border='0' cellpadding='0' cellspacing='0' width='100%' style='max-width:600px;'>
                        <tr><td style='background:#1e293b;border-radius:16px;overflow:hidden;border:1px solid rgba(255,255,255,0.05);'>
                            <table border='0' cellpadding='0' cellspacing='0' width='100%'>
                                <tr><td style='background:{$urgency_color};padding:25px;text-align:center;'>
                                    <h1 style='margin:0;color:#fff;font-size:22px;'>{$urgency_label}</h1>
                                    <p style='margin:8px 0 0;color:rgba(255,255,255,0.9);font-size:18px;font-weight:700;'>{$product_name}</p>
                                </td></tr>
                            </table>
                            <table border='0' cellpadding='0' cellspacing='0' width='100%'>
                                <tr><td style='padding:30px 40px;text-align:center;'>
                                    <p style='color:#e2e8f0;font-size:16px;line-height:1.6;margin:0 0 20px;'>
                                        " . ($stock_qty <= 0
                                            ? "This product is now <strong style='color:#ef4444;'>out of stock</strong>. Customers will not be able to purchase it until you restock."
                                            : "Stock is running low. Consider restocking soon to avoid missed sales."
                                        ) . "
                                    </p>
                                    <div style='background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.05);border-radius:10px;padding:20px;margin:20px 0;'>
                                        <p style='margin:0;color:#94a3b8;font-size:14px;text-transform:uppercase;letter-spacing:1px;'>Current Stock</p>
                                        <p style='margin:5px 0 0;color:{$urgency_color};font-size:36px;font-weight:800;'>{$stock_qty}</p>
                                    </div>
                                    <a href='{$dashboard_url}' style='display:inline-block;background:linear-gradient(135deg,#06b6d4,#8b5cf6);color:#fff;padding:14px 32px;text-decoration:none;border-radius:8px;font-weight:600;font-size:16px;'>Manage Inventory</a>
                                </td></tr>
                            </table>
                        </td></tr>
                        <tr><td align='center' style='padding:20px 0;'>
                            <p style='color:#475569;font-size:12px;margin:0;'>VMO Payments Stock Alert</p>
                        </td></tr>
                    </table>
                </td></tr>
            </table>
        </body>
        </html>";

        wp_mail($owner_email, $subject, $message, ['Content-Type: text/html; charset=UTF-8']);
        error_log("VMO Stripe: Low stock alert sent to {$owner_email} for product '{$product_name}' (qty: {$stock_qty})");
    }
}
